From 4636da34f97b7f9e7501212487dfde441eec3858 Mon Sep 17 00:00:00 2001 From: Thomas B Date: Tue, 6 Aug 2013 22:23:33 +0200 Subject: [PATCH] Cloned from git.kolab.org/git/roundcubemail-plugins-kolab --- LICENSE | 661 ++ README | 24 + UPGRADING | 17 + calendar.php | 2199 +++++++ calendar_base.js | 182 + calendar_ui.js | 2758 ++++++++ composer.json | 31 + config.inc.php.dist | 123 + drivers/calendar_driver.php | 402 ++ drivers/database/SQL/mysql.initial.sql | 83 + drivers/database/SQL/mysql/2012080600.sql | 3 + drivers/database/SQL/mysql/2013011000.sql | 1 + drivers/database/SQL/mysql/2013042700.sql | 1 + drivers/database/SQL/mysql/2013051600.sql | 3 + drivers/database/SQL/mysql/2013071800.sql | 3 + drivers/database/SQL/postgres.initial.sql | 107 + drivers/database/SQL/postgres/2012080600.sql | 3 + drivers/database/SQL/postgres/2013011000.sql | 1 + drivers/database/SQL/postgres/2013042700.sql | 8 + drivers/database/SQL/postgres/2013051600.sql | 3 + drivers/database/SQL/postgres/2013071800.sql | 3 + drivers/database/SQL/sqlite.initial.sql | 77 + drivers/database/SQL/sqlite/2013011000.sql | 1 + drivers/database/SQL/sqlite/2013042700.sql | 1 + drivers/database/SQL/sqlite/2013051600.sql | 63 + drivers/database/SQL/sqlite/2013071800.sql | 64 + drivers/database/database_driver.php | 1028 +++ drivers/kolab/SQL/mysql.initial.sql | 32 + drivers/kolab/SQL/mysql/2012080600.sql | 11 + drivers/kolab/SQL/mysql/2013011000.sql | 1 + drivers/kolab/SQL/postgres.initial.sql | 30 + drivers/kolab/kolab_calendar.php | 656 ++ drivers/kolab/kolab_driver.php | 1229 ++++ lib/Horde_Date.php | 1304 ++++ lib/Horde_Date_Recurrence.php | 1673 +++++ lib/calendar_itip.php | 374 ++ lib/calendar_recurrence.php | 115 + lib/calendar_ui.php | 771 +++ lib/js/fullcalendar.js | 5917 ++++++++++++++++++ lib/js/jquery.miniColors.min.js | 16 + localization/bg_BG.inc | 38 + localization/cs_CZ.inc | 235 + localization/de_CH.inc | 229 + localization/de_DE.inc | 229 + localization/en_US.inc | 236 + localization/es_ES.inc | 39 + localization/et_EE.inc | 230 + localization/fr_FR.inc | 230 + localization/hu_HU.inc | 38 + localization/it_IT.inc | 38 + localization/ja_JP.inc | 230 + localization/nl_NL.inc | 39 + localization/pl_PL.inc | 224 + localization/pt_BR.inc | 38 + localization/ru_RU.inc | 242 + print.js | 168 + skins/classic/README | 5 + skins/classic/calendar.css | 1269 ++++ skins/classic/fullcalendar.css | 724 +++ skins/classic/iehacks.css | 88 + skins/classic/images/attendee-status.gif | Bin 0 -> 2041 bytes skins/classic/images/badge_confidential.gif | Bin 0 -> 1325 bytes skins/classic/images/badge_confidential.png | Bin 0 -> 3441 bytes skins/classic/images/badge_private.gif | Bin 0 -> 1221 bytes skins/classic/images/badge_private.png | Bin 0 -> 3359 bytes skins/classic/images/calendar-blue.png | Bin 0 -> 896 bytes skins/classic/images/calendar.gif | Bin 0 -> 546 bytes skins/classic/images/calendar.png | Bin 0 -> 888 bytes skins/classic/images/calendars.gif | Bin 0 -> 1928 bytes skins/classic/images/calendars.png | Bin 0 -> 2103 bytes skins/classic/images/eventicons.gif | Bin 0 -> 107 bytes skins/classic/images/export.png | Bin 0 -> 746 bytes skins/classic/images/freebusy-colors.gif | Bin 0 -> 408 bytes skins/classic/images/freebusy-colors.png | Bin 0 -> 631 bytes skins/classic/images/invitation.png | Bin 0 -> 1909 bytes skins/classic/images/listheader.gif | Bin 0 -> 322 bytes skins/classic/images/loading_blue.gif | Bin 0 -> 847 bytes skins/classic/images/minicolors-all.png | Bin 0 -> 13370 bytes skins/classic/images/minicolors-handles.gif | Bin 0 -> 421 bytes skins/classic/images/preview.png | Bin 0 -> 1131 bytes skins/classic/images/print.png | Bin 0 -> 869 bytes skins/classic/images/spacer.gif | Bin 0 -> 807 bytes skins/classic/images/toggle.gif | Bin 0 -> 110 bytes skins/classic/images/toolbar.gif | Bin 0 -> 6186 bytes skins/classic/images/toolbar.png | Bin 0 -> 14308 bytes skins/classic/jquery.miniColors.css | 106 + skins/classic/print.css | 209 + skins/classic/print.iehacks.css | 25 + skins/classic/templates/attachment.html | 26 + skins/classic/templates/calendar.html | 201 + skins/classic/templates/eventedit.html | 108 + skins/classic/templates/freebusylegend.html | 7 + skins/classic/templates/itipattend.html | 21 + skins/classic/templates/kolabacl.html | 13 + skins/classic/templates/kolabform.html | 7 + skins/classic/templates/print.html | 28 + skins/larry/README | 11 + skins/larry/calendar.css | 1441 +++++ skins/larry/fullcalendar.css | 724 +++ skins/larry/iehacks.css | 77 + skins/larry/images/attendee-status.gif | Bin 0 -> 2041 bytes skins/larry/images/badge_confidential.png | Bin 0 -> 3441 bytes skins/larry/images/badge_private.png | Bin 0 -> 3359 bytes skins/larry/images/calendar.png | Bin 0 -> 888 bytes skins/larry/images/calendars.png | Bin 0 -> 2239 bytes skins/larry/images/eventicons.png | Bin 0 -> 1233 bytes skins/larry/images/freebusy-colors.png | Bin 0 -> 490 bytes skins/larry/images/invitation.png | Bin 0 -> 1909 bytes skins/larry/images/loading_blue.gif | Bin 0 -> 847 bytes skins/larry/images/minicolors-all.png | Bin 0 -> 13370 bytes skins/larry/images/minicolors-handles.gif | Bin 0 -> 421 bytes skins/larry/images/toggle.gif | Bin 0 -> 110 bytes skins/larry/images/toolbar.png | Bin 0 -> 5142 bytes skins/larry/jquery.miniColors.css | 106 + skins/larry/print.css | 209 + skins/larry/print.iehacks.css | 25 + skins/larry/templates/attachment.html | 33 + skins/larry/templates/calendar.html | 203 + skins/larry/templates/eventedit.html | 106 + skins/larry/templates/freebusylegend.html | 7 + skins/larry/templates/itipattend.html | 37 + skins/larry/templates/kolabacl.html | 26 + skins/larry/templates/kolabform.html | 9 + skins/larry/templates/print.html | 28 + 124 files changed, 28341 insertions(+) create mode 100644 LICENSE create mode 100644 README create mode 100644 UPGRADING create mode 100644 calendar.php create mode 100644 calendar_base.js create mode 100644 calendar_ui.js create mode 100644 composer.json create mode 100644 config.inc.php.dist create mode 100644 drivers/calendar_driver.php create mode 100644 drivers/database/SQL/mysql.initial.sql create mode 100644 drivers/database/SQL/mysql/2012080600.sql create mode 100644 drivers/database/SQL/mysql/2013011000.sql create mode 100644 drivers/database/SQL/mysql/2013042700.sql create mode 100644 drivers/database/SQL/mysql/2013051600.sql create mode 100644 drivers/database/SQL/mysql/2013071800.sql create mode 100644 drivers/database/SQL/postgres.initial.sql create mode 100644 drivers/database/SQL/postgres/2012080600.sql create mode 100644 drivers/database/SQL/postgres/2013011000.sql create mode 100644 drivers/database/SQL/postgres/2013042700.sql create mode 100644 drivers/database/SQL/postgres/2013051600.sql create mode 100644 drivers/database/SQL/postgres/2013071800.sql create mode 100644 drivers/database/SQL/sqlite.initial.sql create mode 100644 drivers/database/SQL/sqlite/2013011000.sql create mode 100644 drivers/database/SQL/sqlite/2013042700.sql create mode 100644 drivers/database/SQL/sqlite/2013051600.sql create mode 100644 drivers/database/SQL/sqlite/2013071800.sql create mode 100644 drivers/database/database_driver.php create mode 100644 drivers/kolab/SQL/mysql.initial.sql create mode 100644 drivers/kolab/SQL/mysql/2012080600.sql create mode 100644 drivers/kolab/SQL/mysql/2013011000.sql create mode 100644 drivers/kolab/SQL/postgres.initial.sql create mode 100644 drivers/kolab/kolab_calendar.php create mode 100644 drivers/kolab/kolab_driver.php create mode 100644 lib/Horde_Date.php create mode 100644 lib/Horde_Date_Recurrence.php create mode 100644 lib/calendar_itip.php create mode 100644 lib/calendar_recurrence.php create mode 100644 lib/calendar_ui.php create mode 100644 lib/js/fullcalendar.js create mode 100644 lib/js/jquery.miniColors.min.js create mode 100644 localization/bg_BG.inc create mode 100644 localization/cs_CZ.inc create mode 100644 localization/de_CH.inc create mode 100644 localization/de_DE.inc create mode 100644 localization/en_US.inc create mode 100644 localization/es_ES.inc create mode 100644 localization/et_EE.inc create mode 100644 localization/fr_FR.inc create mode 100644 localization/hu_HU.inc create mode 100644 localization/it_IT.inc create mode 100644 localization/ja_JP.inc create mode 100644 localization/nl_NL.inc create mode 100644 localization/pl_PL.inc create mode 100644 localization/pt_BR.inc create mode 100644 localization/ru_RU.inc create mode 100644 print.js create mode 100644 skins/classic/README create mode 100644 skins/classic/calendar.css create mode 100644 skins/classic/fullcalendar.css create mode 100644 skins/classic/iehacks.css create mode 100644 skins/classic/images/attendee-status.gif create mode 100644 skins/classic/images/badge_confidential.gif create mode 100644 skins/classic/images/badge_confidential.png create mode 100644 skins/classic/images/badge_private.gif create mode 100644 skins/classic/images/badge_private.png create mode 100644 skins/classic/images/calendar-blue.png create mode 100644 skins/classic/images/calendar.gif create mode 100644 skins/classic/images/calendar.png create mode 100644 skins/classic/images/calendars.gif create mode 100644 skins/classic/images/calendars.png create mode 100644 skins/classic/images/eventicons.gif create mode 100644 skins/classic/images/export.png create mode 100644 skins/classic/images/freebusy-colors.gif create mode 100644 skins/classic/images/freebusy-colors.png create mode 100644 skins/classic/images/invitation.png create mode 100644 skins/classic/images/listheader.gif create mode 100644 skins/classic/images/loading_blue.gif create mode 100644 skins/classic/images/minicolors-all.png create mode 100644 skins/classic/images/minicolors-handles.gif create mode 100644 skins/classic/images/preview.png create mode 100644 skins/classic/images/print.png create mode 100644 skins/classic/images/spacer.gif create mode 100644 skins/classic/images/toggle.gif create mode 100644 skins/classic/images/toolbar.gif create mode 100644 skins/classic/images/toolbar.png create mode 100644 skins/classic/jquery.miniColors.css create mode 100644 skins/classic/print.css create mode 100644 skins/classic/print.iehacks.css create mode 100644 skins/classic/templates/attachment.html create mode 100644 skins/classic/templates/calendar.html create mode 100644 skins/classic/templates/eventedit.html create mode 100644 skins/classic/templates/freebusylegend.html create mode 100644 skins/classic/templates/itipattend.html create mode 100644 skins/classic/templates/kolabacl.html create mode 100644 skins/classic/templates/kolabform.html create mode 100644 skins/classic/templates/print.html create mode 100644 skins/larry/README create mode 100644 skins/larry/calendar.css create mode 100644 skins/larry/fullcalendar.css create mode 100644 skins/larry/iehacks.css create mode 100644 skins/larry/images/attendee-status.gif create mode 100644 skins/larry/images/badge_confidential.png create mode 100644 skins/larry/images/badge_private.png create mode 100644 skins/larry/images/calendar.png create mode 100644 skins/larry/images/calendars.png create mode 100644 skins/larry/images/eventicons.png create mode 100644 skins/larry/images/freebusy-colors.png create mode 100644 skins/larry/images/invitation.png create mode 100644 skins/larry/images/loading_blue.gif create mode 100644 skins/larry/images/minicolors-all.png create mode 100644 skins/larry/images/minicolors-handles.gif create mode 100644 skins/larry/images/toggle.gif create mode 100644 skins/larry/images/toolbar.png create mode 100644 skins/larry/jquery.miniColors.css create mode 100644 skins/larry/print.css create mode 100644 skins/larry/print.iehacks.css create mode 100644 skins/larry/templates/attachment.html create mode 100644 skins/larry/templates/calendar.html create mode 100644 skins/larry/templates/eventedit.html create mode 100644 skins/larry/templates/freebusylegend.html create mode 100644 skins/larry/templates/itipattend.html create mode 100644 skins/larry/templates/kolabacl.html create mode 100644 skins/larry/templates/kolabform.html create mode 100644 skins/larry/templates/print.html diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + 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 +them 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README b/README new file mode 100644 index 0000000..e73efe9 --- /dev/null +++ b/README @@ -0,0 +1,24 @@ +A calendar module for Roundcube +------------------------------- + +This plugin currently supports a local database as well as a Kolab groupware +server as backends for calendar and event storage. For both drivers, some +initialization of the local database is necessary. To do so, execute the +SQL commands in drivers//SQL/.initial.sql + +The client-side calendar UI relies on the "fullcalendar" project by Adam Arshaw +with extensions made for the use in Roundcube. All changes are published in +an official fork at https://github.com/roundcube/fullcalendar + +For some general calendar-based operations such as alarms handling or iCal +parsing/exporting this plugins requires the `libcalendaring` plugin which +is also part of the Kolab Roundcube Plugins repository. Make sure that plugin +is installed and configured correctly. + +For recurring event computation, some utility classes from the Horde project +are used. They are packaged in a slightly modified version with this plugin. + +IMPORTANT +--------- +The calendar module makes heavy use of PHP's DateTime as well as DateInterval +classes. The latter one requires at least PHP 5.3.0 to run. diff --git a/UPGRADING b/UPGRADING new file mode 100644 index 0000000..524c2ac --- /dev/null +++ b/UPGRADING @@ -0,0 +1,17 @@ +UPGRADING instructions +====================== + +To update database schema, depending on the driver you're using, +please run in Roundcube bin/ directory: + +updatedb.sh --package=calendar- --version= \ + --dir=../plugins/calendar/drivers//SQL + +[*] Replace with "database" or "kolab" (without quotes) +[*] Replace with Roundcube version e.g. 0.7.3 +[*] Roundcube should be upgraded before plugin upgrades + +Example: + +updatedb.sh --package=calendar-kolab --version=0.8.0 \ + --dir=../plugins/calendar/drivers/kolab/SQL diff --git a/calendar.php b/calendar.php new file mode 100644 index 0000000..5c866da --- /dev/null +++ b/calendar.php @@ -0,0 +1,2199 @@ + + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +class calendar extends rcube_plugin +{ + const FREEBUSY_UNKNOWN = 0; + const FREEBUSY_FREE = 1; + const FREEBUSY_BUSY = 2; + const FREEBUSY_TENTATIVE = 3; + const FREEBUSY_OOF = 4; + + const SESSION_KEY = 'calendar_temp'; + + public $task = '?(?!logout).*'; + public $rc; + public $lib; + public $driver; + public $home; // declare public to be used in other classes + public $urlbase; + public $timezone; + public $timezone_offset; + public $gmt_offset; + + public $ical; + public $ui; + + public $defaults = array( + 'calendar_default_view' => "agendaWeek", + 'calendar_timeslots' => 2, + 'calendar_work_start' => 6, + 'calendar_work_end' => 18, + 'calendar_agenda_range' => 60, + 'calendar_agenda_sections' => 'smart', + 'calendar_event_coloring' => 0, + 'calendar_time_indicator' => true, + 'calendar_allow_invite_shared' => false, + ); + + private $ics_parts = array(); + + + /** + * Plugin initialization. + */ + function init() + { + $this->require_plugin('libcalendaring'); + + $this->rc = rcube::get_instance(); + $this->lib = libcalendaring::get_instance(); + + $this->register_task('calendar', 'calendar'); + + // load calendar configuration + $this->load_config(); + + // load localizations + $this->add_texts('localization/', $this->rc->task == 'calendar' && (!$this->rc->action || $this->rc->action == 'print')); + + $this->timezone = $this->lib->timezone; + $this->gmt_offset = $this->lib->gmt_offset; + $this->dst_active = $this->lib->dst_active; + $this->timezone_offset = $this->gmt_offset / 3600 - $this->dst_active; + + require($this->home . '/lib/calendar_ui.php'); + $this->ui = new calendar_ui($this); + + // load Calendar user interface which includes jquery-ui + if (!$this->rc->output->ajax_call && !$this->rc->output->env['framed']) { + $this->ui->init(); + + // settings are required in (almost) every GUI step + if ($this->rc->action != 'attend') + $this->rc->output->set_env('calendar_settings', $this->load_settings()); + } + + // catch iTIP confirmation requests that don're require a valid session + if ($this->rc->action == 'attend' && !empty($_REQUEST['_t'])) { + $this->add_hook('startup', array($this, 'itip_attend_response')); + } + else if ($this->rc->action == 'feed' && !empty($_REQUEST['_cal'])) { + $this->add_hook('startup', array($this, 'ical_feed_export')); + } + else if ($this->rc->task == 'calendar' && $this->rc->action != 'save-pref') { + if ($this->rc->action != 'upload') { + $this->load_driver(); + } + + // register calendar actions + $this->register_action('index', array($this, 'calendar_view')); + $this->register_action('event', array($this, 'event_action')); + $this->register_action('calendar', array($this, 'calendar_action')); + $this->register_action('load_events', array($this, 'load_events')); + $this->register_action('export_events', array($this, 'export_events')); + $this->register_action('import_events', array($this, 'import_events')); + $this->register_action('upload', array($this, 'attachment_upload')); + $this->register_action('get-attachment', array($this, 'attachment_get')); + $this->register_action('freebusy-status', array($this, 'freebusy_status')); + $this->register_action('freebusy-times', array($this, 'freebusy_times')); + $this->register_action('randomdata', array($this, 'generate_randomdata')); + $this->register_action('print', array($this,'print_view')); + $this->register_action('mailimportevent', array($this, 'mail_import_event')); + $this->register_action('mailtoevent', array($this, 'mail_message2event')); + $this->register_action('inlineui', array($this, 'get_inline_ui')); + $this->register_action('check-recent', array($this, 'check_recent')); + + // remove undo information... + if ($undo = $_SESSION['calendar_event_undo']) { + // ...after timeout + $undo_time = $this->rc->config->get('undo_timeout', 0); + if ($undo['ts'] < time() - $undo_time) { + $this->rc->session->remove('calendar_event_undo'); + // @TODO: do EXPUNGE on kolab objects? + } + } + } + else if ($this->rc->task == 'settings') { + // add hooks for Calendar settings + $this->add_hook('preferences_sections_list', array($this, 'preferences_sections_list')); + $this->add_hook('preferences_list', array($this, 'preferences_list')); + $this->add_hook('preferences_save', array($this, 'preferences_save')); + } + else if ($this->rc->task == 'mail') { + // hooks to catch event invitations on incoming mails + if ($this->rc->action == 'show' || $this->rc->action == 'preview') { + $this->add_hook('message_load', array($this, 'mail_message_load')); + $this->add_hook('template_object_messagebody', array($this, 'mail_messagebody_html')); + } + + // add 'Create event' item to message menu + if ($this->api->output->type == 'html') { + $this->api->add_content(html::tag('li', null, + $this->api->output->button(array( + 'command' => 'calendar-create-from-mail', + 'label' => 'calendar.createfrommail', + 'type' => 'link', + 'classact' => 'icon calendarlink active', + 'class' => 'icon calendarlink', + 'innerclass' => 'icon calendar', + ))), + 'messagemenu'); + } + } + + // add hooks to display alarms + $this->add_hook('pending_alarms', array($this, 'pending_alarms')); + $this->add_hook('dismiss_alarms', array($this, 'dismiss_alarms')); + } + + /** + * Helper method to load the backend driver according to local config + */ + private function load_driver() + { + if (is_object($this->driver)) + return; + + $driver_name = $this->rc->config->get('calendar_driver', 'database'); + $driver_class = $driver_name . '_driver'; + + require_once($this->home . '/drivers/calendar_driver.php'); + require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php'); + + switch ($driver_name) { + case "kolab": + $this->require_plugin('libkolab'); + default: + $this->driver = new $driver_class($this); + break; + } + + if ($this->driver->undelete) + $this->driver->undelete = $this->rc->config->get('undo_timeout', 0) > 0; + } + + /** + * Load iTIP functions + */ + private function load_itip() + { + if (!$this->itip) { + require_once($this->home . '/lib/calendar_itip.php'); + + $plugin = $this->rc->plugins->exec_hook('calendar_load_itip', + array('identity' => null)); + + $this->itip = new calendar_itip($this, $plugin['identity']); + } + + return $this->itip; + } + + /** + * Load iCalendar functions + */ + public function get_ical() + { + if (!$this->ical) { + $this->ical = libcalendaring::get_ical(); + } + + return $this->ical; + } + + /** + * Get properties of the calendar this user has specified as default + */ + public function get_default_calendar($writeable = false) + { + $default_id = $this->rc->config->get('calendar_default_calendar'); + $calendars = $this->driver->list_calendars(false, true); + $calendar = $calendars[$default_id] ?: null; + if (!$calendar || ($writeable && $calendar['readonly'])) { + foreach ($calendars as $cal) { + if ($cal['default']) { + $calendar = $cal; + break; + } + if (!$writeable || !$cal['readonly']) { + $first = $cal; + } + } + } + + return $calendar ?: $first; + } + + + /** + * Render the main calendar view from skin template + */ + function calendar_view() + { + $this->rc->output->set_pagetitle($this->gettext('calendar')); + + // Add CSS stylesheets to the page header + $this->ui->addCSS(); + + // Add JS files to the page header + $this->ui->addJS(); + + $this->ui->init_templates(); + $this->rc->output->add_label('lowest','low','normal','high','highest','delete','cancel','uploading','noemailwarning'); + + // initialize attendees autocompletion + rcube_autocomplete_init(); + + $this->rc->output->set_env('timezone', $this->timezone->getName()); + $this->rc->output->set_env('calendar_driver', $this->rc->config->get('calendar_driver'), false); + $this->rc->output->set_env('mscolors', $this->driver->get_color_values()); + $this->rc->output->set_env('identities-selector', $this->ui->identity_select(array('id' => 'edit-identities-list'))); + + $view = get_input_value('view', RCUBE_INPUT_GPC); + if (in_array($view, array('agendaWeek', 'agendaDay', 'month', 'table'))) + $this->rc->output->set_env('view', $view); + + if ($date = get_input_value('date', RCUBE_INPUT_GPC)) + $this->rc->output->set_env('date', $date); + + $this->rc->output->send("calendar.calendar"); + } + + /** + * Handler for preferences_sections_list hook. + * Adds Calendar settings sections into preferences sections list. + * + * @param array Original parameters + * @return array Modified parameters + */ + function preferences_sections_list($p) + { + $p['list']['calendar'] = array( + 'id' => 'calendar', 'section' => $this->gettext('calendar'), + ); + + return $p; + } + + /** + * Handler for preferences_list hook. + * Adds options blocks into Calendar settings sections in Preferences. + * + * @param array Original parameters + * @return array Modified parameters + */ + function preferences_list($p) + { + if ($p['section'] != 'calendar') { + return $p; + } + + $no_override = array_flip((array)$this->rc->config->get('dont_override')); + + $p['blocks']['view']['name'] = $this->gettext('mainoptions'); + + if (!isset($no_override['calendar_default_view'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_default_view'; + $select = new html_select(array('name' => '_default_view', 'id' => $field_id)); + $select->add($this->gettext('day'), "agendaDay"); + $select->add($this->gettext('week'), "agendaWeek"); + $select->add($this->gettext('month'), "month"); + $select->add($this->gettext('agenda'), "table"); + $p['blocks']['view']['options']['default_view'] = array( + 'title' => html::label($field_id, Q($this->gettext('default_view'))), + 'content' => $select->show($this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view'])), + ); + } + + if (!isset($no_override['calendar_timeslots'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_timeslot'; + $choices = array('1', '2', '3', '4', '6'); + $select = new html_select(array('name' => '_timeslots', 'id' => $field_id)); + $select->add($choices); + $p['blocks']['view']['options']['timeslots'] = array( + 'title' => html::label($field_id, Q($this->gettext('timeslots'))), + 'content' => $select->show(strval($this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']))), + ); + } + + if (!isset($no_override['calendar_first_day'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_firstday'; + $select = new html_select(array('name' => '_first_day', 'id' => $field_id)); + $select->add(rcube_label('sunday'), '0'); + $select->add(rcube_label('monday'), '1'); + $select->add(rcube_label('tuesday'), '2'); + $select->add(rcube_label('wednesday'), '3'); + $select->add(rcube_label('thursday'), '4'); + $select->add(rcube_label('friday'), '5'); + $select->add(rcube_label('saturday'), '6'); + $p['blocks']['view']['options']['first_day'] = array( + 'title' => html::label($field_id, Q($this->gettext('first_day'))), + 'content' => $select->show(strval($this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']))), + ); + } + + if (!isset($no_override['calendar_first_hour'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $time_format = $this->rc->config->get('time_format', libcalendaring::to_php_date_format($this->rc->config->get('calendar_time_format', $this->defaults['calendar_time_format']))); + $select_hours = new html_select(); + for ($h = 0; $h < 24; $h++) + $select_hours->add(date($time_format, mktime($h, 0, 0)), $h); + + $field_id = 'rcmfd_firsthour'; + $p['blocks']['view']['options']['first_hour'] = array( + 'title' => html::label($field_id, Q($this->gettext('first_hour'))), + 'content' => $select_hours->show($this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']), array('name' => '_first_hour', 'id' => $field_id)), + ); + } + + if (!isset($no_override['calendar_work_start'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_workstart'; + $p['blocks']['view']['options']['workinghours'] = array( + 'title' => html::label($field_id, Q($this->gettext('workinghours'))), + 'content' => $select_hours->show($this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']), array('name' => '_work_start', 'id' => $field_id)) . + ' — ' . $select_hours->show($this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']), array('name' => '_work_end', 'id' => $field_id)), + ); + } + + if (!isset($no_override['calendar_event_coloring'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_coloring'; + $select_colors = new html_select(array('name' => '_event_coloring', 'id' => $field_id)); + $select_colors->add($this->gettext('coloringmode0'), 0); + $select_colors->add($this->gettext('coloringmode1'), 1); + $select_colors->add($this->gettext('coloringmode2'), 2); + $select_colors->add($this->gettext('coloringmode3'), 3); + + $p['blocks']['view']['options']['eventcolors'] = array( + 'title' => html::label($field_id . 'value', Q($this->gettext('eventcoloring'))), + 'content' => $select_colors->show($this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring'])), + ); + } + + // loading driver is expensive, don't do it if not needed + $this->load_driver(); + + if (!isset($no_override['calendar_default_alarm_type'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_alarm'; + $select_type = new html_select(array('name' => '_alarm_type', 'id' => $field_id)); + $select_type->add($this->gettext('none'), ''); + foreach ($this->driver->alarm_types as $type) + $select_type->add(rcube_label(strtolower("alarm{$type}option"), 'libcalendaring'), $type); + + $p['blocks']['view']['options']['alarmtype'] = array( + 'title' => html::label($field_id, Q($this->gettext('defaultalarmtype'))), + 'content' => $select_type->show($this->rc->config->get('calendar_default_alarm_type', '')), + ); + } + + if (!isset($no_override['calendar_default_alarm_offset'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + + $field_id = 'rcmfd_alarm'; + $input_value = new html_inputfield(array('name' => '_alarm_value', 'id' => $field_id . 'value', 'size' => 3)); + $select_offset = new html_select(array('name' => '_alarm_offset', 'id' => $field_id . 'offset')); + foreach (array('-M','-H','-D','+M','+H','+D') as $trigger) + $select_offset->add(rcube_label('trigger' . $trigger, 'libcalendaring'), $trigger); + + $preset = libcalendaring::parse_alaram_value($this->rc->config->get('calendar_default_alarm_offset', '-15M')); + $p['blocks']['view']['options']['alarmoffset'] = array( + 'title' => html::label($field_id . 'value', Q($this->gettext('defaultalarmoffset'))), + 'content' => $input_value->show($preset[0]) . ' ' . $select_offset->show($preset[1]), + ); + } + + if (!isset($no_override['calendar_default_calendar'])) { + if (!$p['current']) { + $p['blocks']['view']['content'] = true; + return $p; + } + // default calendar selection + $field_id = 'rcmfd_default_calendar'; + $select_cal = new html_select(array('name' => '_default_calendar', 'id' => $field_id, 'is_escaped' => true)); + foreach ((array)$this->driver->list_calendars(false, true) as $id => $prop) { + $select_cal->add($prop['name'], strval($id)); + if ($prop['default']) + $default_calendar = $id; + } + $p['blocks']['view']['options']['defaultcalendar'] = array( + 'title' => html::label($field_id . 'value', Q($this->gettext('defaultcalendar'))), + 'content' => $select_cal->show($this->rc->config->get('calendar_default_calendar', $default_calendar)), + ); + } + + // category definitions + if (!$this->driver->nocategories && !isset($no_override['calendar_categories'])) { + $p['blocks']['categories']['name'] = $this->gettext('categories'); + + if (!$p['current']) { + $p['blocks']['categories']['content'] = true; + return $p; + } + + $categories = (array) $this->driver->list_categories(); + $categories_list = ''; + foreach ($categories as $name => $color) { + $key = md5($name); + $field_class = 'rcmfd_category_' . str_replace(' ', '_', $name); + $category_remove = new html_inputfield(array('type' => 'button', 'value' => 'X', 'class' => 'button', 'onclick' => '$(this).parent().remove()', 'title' => $this->gettext('remove_category'))); + $category_name = new html_inputfield(array('name' => "_categories[$key]", 'class' => $field_class, 'size' => 30, 'disabled' => $this->driver->categoriesimmutable)); + $category_color = new html_inputfield(array('name' => "_colors[$key]", 'class' => "$field_class colors", 'size' => 6)); + $hidden = $this->driver->categoriesimmutable ? html::tag('input', array('type' => 'hidden', 'name' => "_categories[$key]", 'value' => $name)) : ''; + $categories_list .= html::div(null, $hidden . $category_name->show($name) . ' ' . $category_color->show($color) . ' ' . $category_remove->show()); + } + + $p['blocks']['categories']['options']['category_' . $name] = array( + 'content' => html::div(array('id' => 'calendarcategories'), $categories_list), + ); + + $field_id = 'rcmfd_new_category'; + $new_category = new html_inputfield(array('name' => '_new_category', 'id' => $field_id, 'size' => 30)); + $add_category = new html_inputfield(array('type' => 'button', 'class' => 'button', 'value' => $this->gettext('add_category'), 'onclick' => "rcube_calendar_add_category()")); + $p['blocks']['categories']['options']['categories'] = array( + 'content' => $new_category->show('') . ' ' . $add_category->show(), + ); + + $this->rc->output->add_script('function rcube_calendar_add_category(){ + var name = $("#rcmfd_new_category").val(); + if (name.length) { + var input = $("").attr("type", "text").attr("name", "_categories[]").attr("size", 30).val(name); + var color = $("").attr("type", "text").attr("name", "_colors[]").attr("size", 6).addClass("colors").val("000000"); + var button = $("").attr("type", "button").attr("value", "X").addClass("button").click(function(){ $(this).parent().remove() }); + $("
").append(input).append(" ").append(color).append(" ").append(button).appendTo("#calendarcategories"); + color.miniColors({ colorValues:(rcmail.env.mscolors || []) }); + $("#rcmfd_new_category").val(""); + } + }'); + + $this->rc->output->add_script('$("#rcmfd_new_category").keypress(function(event){ + if (event.which == 13) { + rcube_calendar_add_category(); + event.preventDefault(); + } + }); + ', 'docready'); + + // include color picker + $this->include_script('lib/js/jquery.miniColors.min.js'); + $this->include_stylesheet($this->local_skin_path() . '/jquery.miniColors.css'); + $this->rc->output->set_env('mscolors', $this->driver->get_color_values()); + $this->rc->output->add_script('$("input.colors").miniColors({ colorValues:rcmail.env.mscolors })', 'docready'); + } + + return $p; + } + + /** + * Handler for preferences_save hook. + * Executed on Calendar settings form submit. + * + * @param array Original parameters + * @return array Modified parameters + */ + function preferences_save($p) + { + if ($p['section'] == 'calendar') { + $this->load_driver(); + + // compose default alarm preset value + $alarm_offset = get_input_value('_alarm_offset', RCUBE_INPUT_POST); + $default_alarm = $alarm_offset[0] . intval(get_input_value('_alarm_value', RCUBE_INPUT_POST)) . $alarm_offset[1]; + + $p['prefs'] = array( + 'calendar_default_view' => get_input_value('_default_view', RCUBE_INPUT_POST), + 'calendar_timeslots' => intval(get_input_value('_timeslots', RCUBE_INPUT_POST)), + 'calendar_first_day' => intval(get_input_value('_first_day', RCUBE_INPUT_POST)), + 'calendar_first_hour' => intval(get_input_value('_first_hour', RCUBE_INPUT_POST)), + 'calendar_work_start' => intval(get_input_value('_work_start', RCUBE_INPUT_POST)), + 'calendar_work_end' => intval(get_input_value('_work_end', RCUBE_INPUT_POST)), + 'calendar_event_coloring' => intval(get_input_value('_event_coloring', RCUBE_INPUT_POST)), + 'calendar_default_alarm_type' => get_input_value('_alarm_type', RCUBE_INPUT_POST), + 'calendar_default_alarm_offset' => $default_alarm, + 'calendar_default_calendar' => get_input_value('_default_calendar', RCUBE_INPUT_POST), + 'calendar_date_format' => null, // clear previously saved values + 'calendar_time_format' => null, + ); + + // categories + if (!$this->driver->nocategories) { + $old_categories = $new_categories = array(); + foreach ($this->driver->list_categories() as $name => $color) { + $old_categories[md5($name)] = $name; + } + + $categories = (array) get_input_value('_categories', RCUBE_INPUT_POST); + $colors = (array) get_input_value('_colors', RCUBE_INPUT_POST); + + foreach ($categories as $key => $name) { + $color = preg_replace('/^#/', '', strval($colors[$key])); + + // rename categories in existing events -> driver's job + if ($oldname = $old_categories[$key]) { + $this->driver->replace_category($oldname, $name, $color); + unset($old_categories[$key]); + } + else + $this->driver->add_category($name, $color); + + $new_categories[$name] = $color; + } + + // these old categories have been removed, alter events accordingly -> driver's job + foreach ((array)$old_categories[$key] as $key => $name) { + $this->driver->remove_category($name); + } + + $p['prefs']['calendar_categories'] = $new_categories; + } + } + + return $p; + } + + /** + * Dispatcher for calendar actions initiated by the client + */ + function calendar_action() + { + $action = get_input_value('action', RCUBE_INPUT_GPC); + $cal = get_input_value('c', RCUBE_INPUT_GPC); + $success = $reload = false; + + if (isset($cal['showalarms'])) + $cal['showalarms'] = intval($cal['showalarms']); + + switch ($action) { + case "form-new": + case "form-edit": + echo $this->ui->calendar_editform($action, $cal); + exit; + case "new": + $success = $this->driver->create_calendar($cal); + $reload = true; + break; + case "edit": + $success = $this->driver->edit_calendar($cal); + $reload = true; + break; + case "remove": + if ($success = $this->driver->remove_calendar($cal)) + $this->rc->output->command('plugin.destroy_source', array('id' => $cal['id'])); + break; + case "subscribe": + if (!$this->driver->subscribe_calendar($cal)) + $this->rc->output->show_message($this->gettext('errorsaving'), 'error'); + return; + } + + if ($success) + $this->rc->output->show_message('successfullysaved', 'confirmation'); + else { + $error_msg = $this->gettext('errorsaving') . ($this->driver->last_error ? ': ' . $this->driver->last_error :''); + $this->rc->output->show_message($error_msg, 'error'); + } + + $this->rc->output->command('plugin.unlock_saving'); + + // TODO: keep view and date selection + if ($success && $reload) + $this->rc->output->redirect(''); + } + + + /** + * Dispatcher for event actions initiated by the client + */ + function event_action() + { + $action = get_input_value('action', RCUBE_INPUT_GPC); + $event = get_input_value('e', RCUBE_INPUT_POST, true); + $success = $reload = $got_msg = false; + + // don't notify if modifying a recurring instance (really?) + if ($event['_savemode'] && $event['_savemode'] != 'all' && $event['_notify']) + unset($event['_notify']); + + // read old event data in order to find changes + if (($event['_notify'] || $event['decline']) && $action != 'new') + $old = $this->driver->get_event($event); + + switch ($action) { + case "new": + // create UID for new event + $event['uid'] = $this->generate_uid(); + $this->prepare_event($event, $action); + if ($success = $this->driver->new_event($event)) { + $event['id'] = $event['uid']; + $this->cleanup_event($event); + } + $reload = $success && $event['recurrence'] ? 2 : 1; + break; + + case "edit": + $this->prepare_event($event, $action); + if ($success = $this->driver->edit_event($event)) + $this->cleanup_event($event); + $reload = $success && ($event['recurrence'] || $event['_savemode'] || $event['_fromcalendar']) ? 2 : 1; + break; + + case "resize": + $this->prepare_event($event, $action); + $success = $this->driver->resize_event($event); + $reload = $event['_savemode'] ? 2 : 1; + break; + + case "move": + $this->prepare_event($event, $action); + $success = $this->driver->move_event($event); + $reload = $success && $event['_savemode'] ? 2 : 1; + break; + + case "remove": + // remove previous deletes + $undo_time = $this->driver->undelete ? $this->rc->config->get('undo_timeout', 0) : 0; + $this->rc->session->remove('calendar_event_undo'); + + // search for event if only UID is given + if (!isset($event['calendar']) && $event['uid']) { + if (!($event = $this->driver->get_event($event, true))) { + break; + } + $undo_time = 0; + } + + $success = $this->driver->remove_event($event, $undo_time < 1); + $reload = (!$success || $event['_savemode']) ? 2 : 1; + + if ($undo_time > 0 && $success) { + $_SESSION['calendar_event_undo'] = array('ts' => time(), 'data' => $event); + // display message with Undo link. + $msg = html::span(null, $this->gettext('successremoval')) + . ' ' . html::a(array('onclick' => sprintf("%s.http_request('event', 'action=undo', %s.display_message('', 'loading'))", + JS_OBJECT_NAME, JS_OBJECT_NAME)), rcube_label('undo')); + $this->rc->output->show_message($msg, 'confirmation', null, true, $undo_time); + $got_msg = true; + } + else if ($success) { + $this->rc->output->show_message('calendar.successremoval', 'confirmation'); + $got_msg = true; + } + + // send iTIP reply that participant has declined the event + if ($success && $event['decline']) { + $emails = $this->get_user_emails(); + foreach ($old['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') + $organizer = $attendee; + else if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { + $old['attendees'][$i]['status'] = 'DECLINED'; + $reply_sender = $attendee['email']; + } + } + + $itip = $this->load_itip(); + $itip->set_sender_email($reply_sender); + if ($organizer && $itip->send_itip_message($old, 'REPLY', $organizer, 'itipsubjectdeclined', 'itipmailbodydeclined')) + $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation'); + else + $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); + } + break; + + case "undo": + // Restore deleted event + $event = $_SESSION['calendar_event_undo']['data']; + + if ($event) + $success = $this->driver->restore_event($event); + + if ($success) { + $this->rc->session->remove('calendar_event_undo'); + $this->rc->output->show_message('calendar.successrestore', 'confirmation'); + $got_msg = true; + $reload = 2; + } + + break; + + case "rsvp-status": + $action = 'rsvp'; + $status = $event['fallback']; + $latest = false; + $html = html::div('rsvp-status', $status != 'CANCELLED' ? $this->gettext('acceptinvitation') : ''); + if (is_numeric($event['changed'])) + $event['changed'] = new DateTime('@'.$event['changed']); + $this->load_driver(); + if ($existing = $this->driver->get_event($event, true, false, true)) { + $latest = ($event['sequence'] && $existing['sequence'] == $event['sequence']) || (!$event['sequence'] && $existing['changed'] && $existing['changed'] >= $event['changed']); + $emails = $this->get_user_emails(); + foreach ($existing['attendees'] as $i => $attendee) { + if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { + $status = $attendee['status']; + break; + } + } + } + else { + // get a list of writeable calendars + $calendars = $this->driver->list_calendars(false, true); + $calendar_select = new html_select(array('name' => 'calendar', 'id' => 'calendar-saveto', 'is_escaped' => true)); + $numcals = 0; + foreach ($calendars as $calendar) { + if (!$calendar['readonly']) { + $calendar_select->add($calendar['name'], $calendar['id']); + $numcals++; + } + } + if ($numcals <= 1) + $calendar_select = null; + } + + if ($status == 'unknown') { + $html = html::div('rsvp-status', $this->gettext('notanattendee')); + $action = 'import'; + } + else if (in_array($status, array('ACCEPTED','TENTATIVE','DECLINED'))) { + $html = html::div('rsvp-status ' . strtolower($status), $this->gettext('youhave'.strtolower($status))); + if ($existing['sequence'] > $event['sequence'] || (!$event['sequence'] && $existing['changed'] && $existing['changed'] > $event['changed'])) { + $action = ''; // nothing to do here, outdated invitation + } + } + + $default_calendar = $calendar_select ? $this->get_default_calendar(true) : null; + $this->rc->output->command('plugin.update_event_rsvp_status', array( + 'uid' => $event['uid'], + 'id' => asciiwords($event['uid'], true), + 'saved' => $existing ? true : false, + 'latest' => $latest, + 'status' => $status, + 'action' => $action, + 'html' => $html, + 'select' => $calendar_select ? html::span('calendar-select', $this->gettext('saveincalendar') . ' ' . $calendar_select->show($this->rc->config->get('calendar_default_calendar', $default_calendar['id']))) : '', + )); + return; + + case "rsvp": + $ev = $this->driver->get_event($event); + $ev['attendees'] = $event['attendees']; + $event = $ev; + + if ($success = $this->driver->edit_event($event)) { + $status = get_input_value('status', RCUBE_INPUT_GPC); + $organizer = null; + foreach ($event['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') { + $organizer = $attendee; + break; + } + } + $itip = $this->load_itip(); + if ($organizer && $itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status)) + $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation'); + else + $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); + } + break; + + case "dismiss": + $event['ids'] = explode(',', $event['id']); + $plugin = $this->rc->plugins->exec_hook('dismiss_alarms', $event); + $success = $plugin['success']; + foreach ($event['ids'] as $id) { + if (strpos($id, 'cal:') === 0) + $success |= $this->driver->dismiss_alarm(substr($id, 4), $event['snooze']); + } + break; + } + + // show confirmation/error message + if (!$got_msg) { + if ($success) + $this->rc->output->show_message('successfullysaved', 'confirmation'); + else + $this->rc->output->show_message('calendar.errorsaving', 'error'); + } + + // send out notifications + if ($success && $event['_notify'] && ($event['attendees'] || $old['attendees'])) { + // make sure we have the complete record + $event = $action == 'remove' ? $old : $this->driver->get_event($event); + + // only notify if data really changed (TODO: do diff check on client already) + if (!$old || $action == 'remove' || self::event_diff($event, $old)) { + $sent = $this->notify_attendees($event, $old, $action); + if ($sent > 0) + $this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation'); + else if ($sent < 0) + $this->rc->output->show_message('calendar.errornotifying', 'error'); + } + } + + // unlock client + $this->rc->output->command('plugin.unlock_saving'); + + // update event object on the client or trigger a complete refretch if too complicated + if ($reload) { + $args = array('source' => $event['calendar']); + if ($reload > 1) + $args['refetch'] = true; + else if ($success && $action != 'remove') + $args['update'] = $this->_client_event($this->driver->get_event($event)); + $this->rc->output->command('plugin.refresh_calendar', $args); + } + } + + /** + * Handler for load-requests from fullcalendar + * This will return pure JSON formatted output + */ + function load_events() + { + $events = $this->driver->load_events( + get_input_value('start', RCUBE_INPUT_GET), + get_input_value('end', RCUBE_INPUT_GET), + ($query = get_input_value('q', RCUBE_INPUT_GET)), + get_input_value('source', RCUBE_INPUT_GET) + ); + echo $this->encode($events, !empty($query)); + exit; + } + + /** + * Handler for pending_alarms plugin hook triggered by the calendar module on keep-alive requests. + * This will check for pending notifications and pass them to the client + */ + public function pending_alarms($p) + { + $this->load_driver(); + if ($alarms = $this->driver->pending_alarms($p['time'] ?: time())) { + foreach ($alarms as $alarm) { + $alarm['id'] = 'cal:' . $alarm['id']; // prefix ID with cal: + $p['alarms'][] = $alarm; + } + } + + return $p; + } + + /** + * Handler for alarm dismiss hook triggered by libcalendaring + */ + public function dismiss_alarms($p) + { + $this->load_driver(); + foreach ((array)$p['ids'] as $id) { + if (strpos($id, 'cal:') === 0) + $p['success'] |= $this->driver->dismiss_alarm(substr($id, 4), $p['snooze']); + } + + return $p; + } + + /** + * Handler for check-recent requests which are accidentally sent to calendar taks + */ + function check_recent() + { + // NOP + $this->rc->output->send(); + } + + /** + * + */ + function import_events() + { + // Upload progress update + if (!empty($_GET['_progress'])) { + rcube_upload_progress(); + } + + $calendar = get_input_value('calendar', RCUBE_INPUT_GPC); + + // process uploaded file if there is no error + $err = $_FILES['_data']['error']; + + if (!$err && $_FILES['_data']['tmp_name']) { + $calendar = get_input_value('calendar', RCUBE_INPUT_GPC); + $events = $this->get_ical()->import_from_file($_FILES['_data']['tmp_name']); + + $count = $errors = 0; + $rangestart = $_REQUEST['_range'] ? date_create("now -" . intval($_REQUEST['_range']) . " months") : 0; + foreach ($events as $event) { + // TODO: correctly handle recurring events which start before $rangestart + if ($event['end'] < $rangestart && (!$event['recurrence'] || ($event['recurrence']['until'] && $event['recurrence']['until'] < $rangestart))) + continue; + + $event['calendar'] = $calendar; + if ($this->driver->new_event($event)) { + $count++; + } + else + $errors++; + } + + if ($count) { + $this->rc->output->command('display_message', $this->gettext(array('name' => 'importsuccess', 'vars' => array('nr' => $count))), 'confirmation'); + $this->rc->output->command('plugin.import_success', array('source' => $calendar, 'refetch' => true)); + } + else if (!$errors) { + $this->rc->output->command('display_message', $this->gettext('importnone'), 'notice'); + $this->rc->output->command('plugin.import_success', array('source' => $calendar)); + } + else + $this->rc->output->command('display_message', $this->gettext('importerror'), 'error'); + } + else { + if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { + $msg = rcube_label(array('name' => 'filesizeerror', 'vars' => array( + 'size' => show_bytes(parse_bytes(ini_get('upload_max_filesize')))))); + } + else { + $msg = rcube_label('fileuploaderror'); + } + + $this->rc->output->command('display_message', $msg, 'error'); + $this->rc->output->command('plugin.unlock_saving', false); + } + + $this->rc->output->send('iframe'); + } + + /** + * Construct the ics file for exporting events to iCalendar format; + */ + function export_events($terminate = true) + { + $start = get_input_value('start', RCUBE_INPUT_GET); + $end = get_input_value('end', RCUBE_INPUT_GET); + if (!$start) $start = mktime(0, 0, 0, 1, date('n'), date('Y')-1); + if (!$end) $end = mktime(0, 0, 0, 31, 12, date('Y')+10); + $calid = $calname = get_input_value('source', RCUBE_INPUT_GET); + $calendars = $this->driver->list_calendars(true); + + if ($calendars[$calid]) { + $calname = $calendars[$calid]['name'] ? $calendars[$calid]['name'] : $calid; + $calname = preg_replace('/[^a-z0-9_.-]/i', '', html_entity_decode($calname)); // to 7bit ascii + if (empty($calname)) $calname = $calid; + $events = $this->driver->load_events($start, $end, null, $calid, 0); + } + else + $events = array(); + + header("Content-Type: text/calendar"); + header("Content-Disposition: inline; filename=".$calname.'.ics'); + + $this->get_ical()->export($events, '', true, array($this->driver, 'get_attachment_body')); + + if ($terminate) + exit; + } + + + /** + * Handler for iCal feed requests + */ + function ical_feed_export() + { + // process HTTP auth info + if (!empty($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { + $_POST['_user'] = $_SERVER['PHP_AUTH_USER']; // used for rcmail::autoselect_host() + $auth = $this->rc->plugins->exec_hook('authenticate', array( + 'host' => $this->rc->autoselect_host(), + 'user' => trim($_SERVER['PHP_AUTH_USER']), + 'pass' => $_SERVER['PHP_AUTH_PW'], + 'cookiecheck' => true, + 'valid' => true, + )); + if ($auth['valid'] && !$auth['abort']) + $this->rc->login($auth['user'], $auth['pass'], $auth['host']); + } + + // require HTTP auth + if (empty($_SESSION['user_id'])) { + header('WWW-Authenticate: Basic realm="Roundcube Calendar"'); + header('HTTP/1.0 401 Unauthorized'); + exit; + } + + // decode calendar feed hash + $format = 'ics'; + $calhash = get_input_value('_cal', RCUBE_INPUT_GET); + if (preg_match(($suff_regex = '/\.([a-z0-9]{3,5})$/i'), $calhash, $m)) { + $format = strtolower($m[1]); + $calhash = preg_replace($suff_regex, '', $calhash); + } + + if (!strpos($calhash, ':')) + $calhash = base64_decode($calhash); + + list($user, $_GET['source']) = explode(':', $calhash, 2); + + // sanity check user + if ($this->rc->user->get_username() == $user) { + $this->load_driver(); + $this->export_events(false); + } + else { + header('HTTP/1.0 404 Not Found'); + } + + // don't save session data + session_destroy(); + exit; + } + + + /** + * + */ + function load_settings() + { + $this->lib->load_settings(); + $this->defaults += $this->lib->defaults; + + $settings = array(); + + // configuration + $settings['default_calendar'] = $this->rc->config->get('calendar_default_calendar'); + $settings['default_view'] = (string)$this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view']); + $settings['date_agenda'] = (string)$this->rc->config->get('calendar_date_agenda', $this->defaults['calendar_date_agenda']); + + $settings['timeslots'] = (int)$this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']); + $settings['first_day'] = (int)$this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']); + $settings['first_hour'] = (int)$this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']); + $settings['work_start'] = (int)$this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']); + $settings['work_end'] = (int)$this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']); + $settings['agenda_range'] = (int)$this->rc->config->get('calendar_agenda_range', $this->defaults['calendar_agenda_range']); + $settings['agenda_sections'] = $this->rc->config->get('calendar_agenda_sections', $this->defaults['calendar_agenda_sections']); + $settings['event_coloring'] = (int)$this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']); + $settings['time_indicator'] = (int)$this->rc->config->get('calendar_time_indicator', $this->defaults['calendar_time_indicator']); + $settings['invite_shared'] = (int)$this->rc->config->get('calendar_allow_invite_shared', $this->defaults['calendar_allow_invite_shared']); + + // get user identity to create default attendee + if ($this->ui->screen == 'calendar') { + foreach ($this->rc->user->list_identities() as $rec) { + if (!$identity) + $identity = $rec; + $identity['emails'][] = $rec['email']; + $settings['identities'][$rec['identity_id']] = $rec['email']; + } + $identity['emails'][] = $this->rc->user->get_username(); + $settings['identity'] = array('name' => $identity['name'], 'email' => strtolower($identity['email']), 'emails' => ';' . strtolower(join(';', $identity['emails']))); + } + + return $settings; + } + + /** + * Encode events as JSON + * + * @param array Events as array + * @param boolean Add CSS class names according to calendar and categories + * @return string JSON encoded events + */ + function encode($events, $addcss = false) + { + $json = array(); + foreach ($events as $event) { + $json[] = $this->_client_event($event, $addcss); + } + return json_encode($json); + } + + /** + * Convert an event object to be used on the client + */ + private function _client_event($event, $addcss = false) + { + // compose a human readable strings for alarms_text and recurrence_text + if ($event['alarms']) + $event['alarms_text'] = libcalendaring::alarms_text($event['alarms']); + if ($event['recurrence']) { + $event['recurrence_text'] = $this->_recurrence_text($event['recurrence']); + if ($event['recurrence']['UNTIL']) + $event['recurrence']['UNTIL'] = $this->lib->adjust_timezone($event['recurrence']['UNTIL'])->format('c'); + unset($event['recurrence']['EXCEPTIONS']); + } + + foreach ((array)$event['attachments'] as $k => $attachment) { + $event['attachments'][$k]['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']); + } + + // check for organizer in attendees list + $organizer = null; + foreach ((array)$event['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') { + $organizer = $attendee; + break; + } + } + + if ($organizer === null && !empty($event['organizer'])) { + $organizer = $event['organizer']; + $organizer['role'] = 'ORGANIZER'; + if (!is_array($event['attendees'])) + $event['attendees'] = array(); + array_unshift($event['attendees'], $organizer); + } + + // mapping url => vurl because of the fullcalendar client script + $event['vurl'] = $event['url']; + unset($event['url']); + + return array( + '_id' => $event['calendar'] . ':' . $event['id'], // unique identifier for fullcalendar + 'start' => $this->lib->adjust_timezone($event['start'])->format('c'), + 'end' => $this->lib->adjust_timezone($event['end'])->format('c'), + 'changed' => $this->lib->adjust_timezone($event['changed'])->format('c'), + 'title' => strval($event['title']), + 'description' => strval($event['description']), + 'location' => strval($event['location']), + 'className' => ($addcss ? 'fc-event-cal-'.asciiwords($event['calendar'], true).' ' : '') . 'fc-event-cat-' . asciiwords(strtolower(join('-', (array)$event['categories'])), true), + 'allDay' => ($event['allday'] == 1), + ) + $event; + } + + + /** + * Render localized text describing the recurrence rule of an event + */ + private function _recurrence_text($rrule) + { + // TODO: finish this + $freq = sprintf('%s %d ', $this->gettext('every'), $rrule['INTERVAL']); + $details = ''; + switch ($rrule['FREQ']) { + case 'DAILY': + $freq .= $this->gettext('days'); + break; + case 'WEEKLY': + $freq .= $this->gettext('weeks'); + break; + case 'MONTHLY': + $freq .= $this->gettext('months'); + break; + case 'YEARLY': + $freq .= $this->gettext('years'); + break; + } + + if ($rrule['INTERVAL'] <= 1) + $freq = $this->gettext(strtolower($rrule['FREQ'])); + + if ($rrule['COUNT']) + $until = $this->gettext(array('name' => 'forntimes', 'vars' => array('nr' => $rrule['COUNT']))); + else if ($rrule['UNTIL']) + $until = $this->gettext('recurrencend') . ' ' . format_date($rrule['UNTIL'], libcalendaring::to_php_date_format($this->rc->config->get('calendar_date_format', $this->defaults['calendar_date_format']))); + else + $until = $this->gettext('forever'); + + return rtrim($freq . $details . ', ' . $until); + } + + /** + * Generate a unique identifier for an event + */ + public function generate_uid() + { + return strtoupper(md5(time() . uniqid(rand())) . '-' . substr(md5($this->rc->user->get_username()), 0, 16)); + } + + + /** + * TEMPORARY: generate random event data for testing + * Create events by opening http:///?_task=calendar&_action=randomdata&_num=500 + */ + public function generate_randomdata() + { + $num = $_REQUEST['_num'] ? intval($_REQUEST['_num']) : 100; + $cats = array_keys($this->driver->list_categories()); + $cals = $this->driver->list_calendars(true); + $count = 0; + + while ($count++ < $num) { + $start = round((time() + rand(-2600, 2600) * 1000) / 300) * 300; + $duration = round(rand(30, 360) / 30) * 30 * 60; + $allday = rand(0,20) > 18; + $alarm = rand(-30,12) * 5; + $fb = rand(0,2); + + if (date('G', $start) > 23) + $start -= 3600; + + if ($allday) { + $start = strtotime(date('Y-m-d 00:00:00', $start)); + $duration = 86399; + } + + $title = ''; + $len = rand(2, 12); + $words = explode(" ", "The Hough transform is named after Paul Hough who patented the method in 1962. It is a technique which can be used to isolate features of a particular shape within an image. Because it requires that the desired features be specified in some parametric form, the classical Hough transform is most commonly used for the de- tection of regular curves such as lines, circles, ellipses, etc. A generalized Hough transform can be employed in applications where a simple analytic description of a feature(s) is not possible. Due to the computational complexity of the generalized Hough algorithm, we restrict the main focus of this discussion to the classical Hough transform. Despite its domain restrictions, the classical Hough transform (hereafter referred to without the classical prefix ) retains many applications, as most manufac- tured parts (and many anatomical parts investigated in medical imagery) contain feature boundaries which can be described by regular curves. The main advantage of the Hough transform technique is that it is tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise."); +// $chars = "!# abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890"; + for ($i = 0; $i < $len; $i++) + $title .= $words[rand(0,count($words)-1)] . " "; + + $this->driver->new_event(array( + 'uid' => $this->generate_uid(), + 'start' => new DateTime('@'.$start), + 'end' => new DateTime('@'.($start + $duration)), + 'allday' => $allday, + 'title' => rtrim($title), + 'free_busy' => $fb == 2 ? 'outofoffice' : ($fb ? 'busy' : 'free'), + 'categories' => $cats[array_rand($cats)], + 'calendar' => array_rand($cals), + 'alarms' => $alarm > 0 ? "-{$alarm}M:DISPLAY" : '', + 'priority' => rand(0,9), + )); + } + + $this->rc->output->redirect(''); + } + + /** + * Handler for attachments upload + */ + public function attachment_upload() + { + $this->lib->attachment_upload(self::SESSION_KEY, 'cal:'); + } + + /** + * Handler for attachments download/displaying + */ + public function attachment_get() + { + // show loading page + if (!empty($_GET['_preload'])) { + return $this->lib->attachment_loading_page(); + } + + $event_id = get_input_value('_event', RCUBE_INPUT_GPC); + $calendar = get_input_value('_cal', RCUBE_INPUT_GPC); + $id = get_input_value('_id', RCUBE_INPUT_GPC); + + $event = array('id' => $event_id, 'calendar' => $calendar); + $attachment = $this->driver->get_attachment($id, $event); + + // show part page + if (!empty($_GET['_frame'])) { + $this->lib->attachment = $attachment; + $this->register_handler('plugin.attachmentframe', array($this->lib, 'attachment_frame')); + $this->register_handler('plugin.attachmentcontrols', array($this->lib, 'attachment_header')); + $this->rc->output->send('calendar.attachment'); + } + // deliver attachment content + else if ($attachment) { + $attachment['body'] = $this->driver->get_attachment_body($id, $event); + $this->lib->attachment_get($attachment); + } + + // if we arrive here, the requested part was not found + header('HTTP/1.1 404 Not Found'); + exit; + } + + + /** + * Prepares new/edited event properties before save + */ + private function prepare_event(&$event, $action) + { + // convert dates into DateTime objects in user's current timezone + $event['start'] = new DateTime($event['start'], $this->timezone); + $event['end'] = new DateTime($event['end'], $this->timezone); + + // start/end is all we need for 'move' action (#1480) + if ($action == 'move') { + return; + } + + if ($event['recurrence']['UNTIL']) + $event['recurrence']['UNTIL'] = new DateTime($event['recurrence']['UNTIL'], $this->timezone); + + $attachments = array(); + $eventid = 'cal:'.$event['id']; + if (is_array($_SESSION[self::SESSION_KEY]) && $_SESSION[self::SESSION_KEY]['id'] == $eventid) { + if (!empty($_SESSION[self::SESSION_KEY]['attachments'])) { + foreach ($_SESSION[self::SESSION_KEY]['attachments'] as $id => $attachment) { + if (is_array($event['attachments']) && in_array($id, $event['attachments'])) { + $attachments[$id] = $this->rc->plugins->exec_hook('attachment_get', $attachment); + } + } + } + } + + $event['attachments'] = $attachments; + + // check for organizer in attendees + if ($action == 'new' || $action == 'edit') { + if (!$event['attendees']) + $event['attendees'] = array(); + + $emails = $this->get_user_emails(); + $organizer = $owner = false; + foreach ((array)$event['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') + $organizer = $i; + if ($attendee['email'] == in_array(strtolower($attendee['email']), $emails)) + $owner = $i; + else if (!isset($attendee['rsvp'])) + $event['attendees'][$i]['rsvp'] = true; + } + + // set new organizer identity + if ($organizer !== false && !empty($event['_identity']) && ($identity = $this->rc->user->get_identity($event['_identity']))) { + $event['attendees'][$organizer]['name'] = $identity['name']; + $event['attendees'][$organizer]['email'] = $identity['email']; + } + + // set owner as organizer if yet missing + if ($organizer === false && $owner !== false) { + $event['attendees'][$owner]['role'] = 'ORGANIZER'; + unset($event['attendees'][$owner]['rsvp']); + } + else if ($organizer === false && $action == 'new' && ($identity = $this->rc->user->get_identity($event['_identity'])) && $identity['email']) { + array_unshift($event['attendees'], array('role' => 'ORGANIZER', 'name' => $identity['name'], 'email' => $identity['email'], 'status' => 'ACCEPTED')); + } + } + + // mapping url => vurl because of the fullcalendar client script + $event['url'] = $event['vurl']; + unset($event['vurl']); + } + + /** + * Releases some resources after successful event save + */ + private function cleanup_event(&$event) + { + // remove temp. attachment files + if (!empty($_SESSION[self::SESSION_KEY]) && ($eventid = $_SESSION[self::SESSION_KEY]['id'])) { + $this->rc->plugins->exec_hook('attachments_cleanup', array('group' => $eventid)); + $this->rc->session->remove(self::SESSION_KEY); + } + } + + /** + * Send out an invitation/notification to all event attendees + */ + private function notify_attendees($event, $old, $action = 'edit') + { + if ($action == 'remove') { + $event['cancelled'] = true; + $is_cancelled = true; + } + + $itip = $this->load_itip(); + $emails = $this->get_user_emails(); + + // compose multipart message using PEAR:Mail_Mime + $method = $action == 'remove' ? 'CANCEL' : 'REQUEST'; + $message = $itip->compose_itip_message($event, $method); + + // list existing attendees from $old event + $old_attendees = array(); + foreach ((array)$old['attendees'] as $attendee) { + $old_attendees[] = $attendee['email']; + } + + // send to every attendee + $sent = 0; + foreach ((array)$event['attendees'] as $attendee) { + // skip myself for obvious reasons + if (!$attendee['email'] || in_array(strtolower($attendee['email']), $emails)) + continue; + + // which template to use for mail text + $is_new = !in_array($attendee['email'], $old_attendees); + $bodytext = $is_cancelled ? 'eventcancelmailbody' : ($is_new ? 'invitationmailbody' : 'eventupdatemailbody'); + $subject = $is_cancelled ? 'eventcancelsubject' : ($is_new ? 'invitationsubject' : ($event['title'] ? 'eventupdatesubject':'eventupdatesubjectempty')); + + // finally send the message + if ($itip->send_itip_message($event, $method, $attendee, $subject, $bodytext, $message)) + $sent++; + else + $sent = -100; + } + + return $sent; + } + + /** + * Echo simple free/busy status text for the given user and time range + */ + public function freebusy_status() + { + $email = get_input_value('email', RCUBE_INPUT_GPC); + $start = get_input_value('start', RCUBE_INPUT_GPC); + $end = get_input_value('end', RCUBE_INPUT_GPC); + + // convert dates into unix timestamps + if (!empty($start) && !is_numeric($start)) { + $dts = new DateTime($start, $this->timezone); + $start = $dts->format('U'); + } + if (!empty($end) && !is_numeric($end)) { + $dte = new DateTime($end, $this->timezone); + $end = $dte->format('U'); + } + + if (!$start) $start = time(); + if (!$end) $end = $start + 3600; + + $fbtypemap = array(calendar::FREEBUSY_UNKNOWN => 'UNKNOWN', calendar::FREEBUSY_FREE => 'FREE', calendar::FREEBUSY_BUSY => 'BUSY', calendar::FREEBUSY_TENTATIVE => 'TENTATIVE', calendar::FREEBUSY_OOF => 'OUT-OF-OFFICE'); + $status = 'UNKNOWN'; + + // if the backend has free-busy information + $fblist = $this->driver->get_freebusy_list($email, $start, $end); + if (is_array($fblist)) { + $status = 'FREE'; + + foreach ($fblist as $slot) { + list($from, $to, $type) = $slot; + if ($from < $end && $to > $start) { + $status = isset($type) && $fbtypemap[$type] ? $fbtypemap[$type] : 'BUSY'; + break; + } + } + } + + // let this information be cached for 5min + send_future_expire_header(300); + + echo $status; + exit; + } + + /** + * Return a list of free/busy time slots within the given period + * Echo data in JSON encoding + */ + public function freebusy_times() + { + $email = get_input_value('email', RCUBE_INPUT_GPC); + $start = get_input_value('start', RCUBE_INPUT_GPC); + $end = get_input_value('end', RCUBE_INPUT_GPC); + $interval = intval(get_input_value('interval', RCUBE_INPUT_GPC)); + $strformat = $interval > 60 ? 'Ymd' : 'YmdHis'; + + // convert dates into unix timestamps + if (!empty($start) && !is_numeric($start)) { + $dts = new DateTime($start, $this->timezone); + $start = $dts->format('U'); + } + if (!empty($end) && !is_numeric($end)) { + $dte = new DateTime($end, $this->timezone); + $end = $dte->format('U'); + } + + if (!$start) $start = time(); + if (!$end) $end = $start + 86400 * 30; + if (!$interval) $interval = 60; // 1 hour + + if (!$dte) { + $dts = new DateTime('@'.$start); + $dts->setTimezone($this->timezone); + } + + $fblist = $this->driver->get_freebusy_list($email, $start, $end); + $slots = array(); + + // build a list from $start till $end with blocks representing the fb-status + for ($s = 0, $t = $start; $t <= $end; $s++) { + $status = self::FREEBUSY_UNKNOWN; + $t_end = $t + $interval * 60; + $dt = new DateTime('@'.$t); + $dt->setTimezone($this->timezone); + + // determine attendee's status + if (is_array($fblist)) { + $status = self::FREEBUSY_FREE; + foreach ($fblist as $slot) { + list($from, $to, $type) = $slot; + if ($from < $t_end && $to > $t) { + $status = isset($type) ? $type : self::FREEBUSY_BUSY; + if ($status == self::FREEBUSY_BUSY) // can't get any worse :-) + break; + } + } + } + + $slots[$s] = $status; + $times[$s] = intval($dt->format($strformat)); + $t = $t_end; + } + + $dte = new DateTime('@'.$t_end); + $dte->setTimezone($this->timezone); + + // let this information be cached for 5min + send_future_expire_header(300); + + echo json_encode(array( + 'email' => $email, + 'start' => $dts->format('c'), + 'end' => $dte->format('c'), + 'interval' => $interval, + 'slots' => $slots, + 'times' => $times, + )); + exit; + } + + /** + * Handler for printing calendars + */ + public function print_view() + { + $title = $this->gettext('print'); + + $view = get_input_value('view', RCUBE_INPUT_GPC); + if (!in_array($view, array('agendaWeek', 'agendaDay', 'month', 'table'))) + $view = 'agendaDay'; + + $this->rc->output->set_env('view',$view); + + if ($date = get_input_value('date', RCUBE_INPUT_GPC)) + $this->rc->output->set_env('date', $date); + + if ($range = get_input_value('range', RCUBE_INPUT_GPC)) + $this->rc->output->set_env('listRange', intval($range)); + + if (isset($_REQUEST['sections'])) + $this->rc->output->set_env('listSections', get_input_value('sections', RCUBE_INPUT_GPC)); + + if ($search = get_input_value('search', RCUBE_INPUT_GPC)) { + $this->rc->output->set_env('search', $search); + $title .= ' "' . $search . '"'; + } + + // Add CSS stylesheets to the page header + $skin_path = $this->local_skin_path(); + $this->include_stylesheet($skin_path . '/fullcalendar.css'); + $this->include_stylesheet($skin_path . '/print.css'); + + // Add JS files to the page header + $this->include_script('print.js'); + $this->include_script('lib/js/fullcalendar.js'); + + $this->register_handler('plugin.calendar_css', array($this->ui, 'calendar_css')); + $this->register_handler('plugin.calendar_list', array($this->ui, 'calendar_list')); + + $this->rc->output->set_pagetitle($title); + $this->rc->output->send("calendar.print"); + } + + /** + * + */ + public function get_inline_ui() + { + foreach (array('save','cancel','savingdata') as $label) + $texts['calendar.'.$label] = $this->gettext($label); + + $texts['calendar.new_event'] = $this->gettext('createfrommail'); + + $this->ui->init_templates(); + $this->ui->calendar_list(); # set env['calendars'] + echo $this->api->output->parse('calendar.eventedit', false, false); + echo html::tag('script', array('type' => 'text/javascript'), + "rcmail.set_env('calendars', " . json_encode($this->api->output->env['calendars']) . ");\n". + "rcmail.set_env('deleteicon', '" . $this->api->output->env['deleteicon'] . "');\n". + "rcmail.set_env('cancelicon', '" . $this->api->output->env['cancelicon'] . "');\n". + "rcmail.set_env('loadingicon', '" . $this->api->output->env['loadingicon'] . "');\n". + "rcmail.gui_object('attachmentlist', '" . $this->ui->attachmentlist_id . "');\n". + "rcmail.add_label(" . json_encode($texts) . ");\n" + ); + exit; + } + + /** + * Compare two event objects and return differing properties + * + * @param array Event A + * @param array Event B + * @return array List of differing event properties + */ + public static function event_diff($a, $b) + { + $diff = array(); + $ignore = array('changed' => 1, 'attachments' => 1); + foreach (array_unique(array_merge(array_keys($a), array_keys($b))) as $key) { + if (!$ignore[$key] && $a[$key] != $b[$key]) + $diff[] = $key; + } + + // only compare number of attachments + if (count($a['attachments']) != count($b['attachments'])) + $diff[] = 'attachments'; + + return $diff; + } + + + /**** Event invitation plugin hooks ****/ + + /** + * Handler for URLs that allow an invitee to respond on his invitation mail + */ + public function itip_attend_response($p) + { + if ($p['action'] == 'attend') { + $this->rc->output->set_env('task', 'calendar'); // override some env vars + $this->rc->output->set_env('refresh_interval', 0); + $this->rc->output->set_pagetitle($this->gettext('calendar')); + + $itip = $this->load_itip(); + $token = get_input_value('_t', RCUBE_INPUT_GPC); + + // read event info stored under the given token + if ($invitation = $itip->get_invitation($token)) { + $this->token = $token; + $this->event = $invitation['event']; + + // show message about cancellation + if ($invitation['cancelled']) { + $this->invitestatus = html::div('rsvp-status declined', $this->gettext('eventcancelled')); + } + // save submitted RSVP status + else if (!empty($_POST['rsvp'])) { + $status = null; + foreach (array('accepted','tentative','declined') as $method) { + if ($_POST['rsvp'] == $this->gettext('itip' . $method)) { + $status = $method; + break; + } + } + + // send itip reply to organizer + if ($status && $itip->update_invitation($invitation, $invitation['attendee'], strtoupper($status))) { + $this->invitestatus = html::div('rsvp-status ' . strtolower($status), $this->gettext('youhave'.strtolower($status))); + } + else + $this->rc->output->command('display_message', $this->gettext('errorsaving'), 'error', -1); + + // if user is logged in... + if ($this->rc->user->ID) { + $this->load_driver(); + $invitation = $itip->get_invitation($token); + + // save the event to his/her default calendar if not yet present + if (!$this->driver->get_event($this->event) && ($calendar = $this->get_default_calendar(true))) { + $invitation['event']['calendar'] = $calendar['id']; + if ($this->driver->new_event($invitation['event'])) + $this->rc->output->command('display_message', $this->gettext(array('name' => 'importedsuccessfully', 'vars' => array('calendar' => $calendar['name']))), 'confirmation'); + } + } + } + + $this->register_handler('plugin.event_inviteform', array($this, 'itip_event_inviteform')); + $this->register_handler('plugin.event_invitebox', array($this->ui, 'event_invitebox')); + + if (!$this->invitestatus) + $this->register_handler('plugin.event_rsvp_buttons', array($this->ui, 'event_rsvp_buttons')); + + $this->rc->output->set_pagetitle($this->gettext('itipinvitation') . ' ' . $this->event['title']); + } + else + $this->rc->output->command('display_message', $this->gettext('itipinvalidrequest'), 'error', -1); + + $this->rc->output->send('calendar.itipattend'); + } + } + + /** + * + */ + public function itip_event_inviteform($attrib) + { + $hidden = new html_hiddenfield(array('name' => "_t", 'value' => $this->token)); + return html::tag('form', array('action' => $this->rc->url(array('task' => 'calendar', 'action' => 'attend')), 'method' => 'post', 'noclose' => true) + $attrib) . $hidden->show(); + } + + /** + * Check mail message structure of there are .ics files attached + */ + public function mail_message_load($p) + { + $this->message = $p['object']; + $itip_part = null; + + // check all message parts for .ics files + foreach ((array)$this->message->mime_parts as $part) { + if ($this->is_vcalendar($part)) { + if ($part->ctype_parameters['method']) + $itip_part = $part->mime_id; + else + $this->ics_parts[] = $part->mime_id; + } + } + + // priorize part with method parameter + if ($itip_part) + $this->ics_parts = array($itip_part); + } + + /** + * Add UI element to copy event invitations or updates to the calendar + */ + public function mail_messagebody_html($p) + { + // load iCalendar functions (if necessary) + if (!empty($this->ics_parts)) { + $this->get_ical(); + } + + $html = ''; + foreach ($this->ics_parts as $mime_id) { + $part = $this->message->mime_parts[$mime_id]; + $charset = $part->ctype_parameters['charset'] ? $part->ctype_parameters['charset'] : RCMAIL_CHARSET; + $events = $this->ical->import($this->message->get_part_content($mime_id), $charset); + $title = $this->gettext('title'); + + // successfully parsed events? + if (empty($events)) + continue; + + // show a box for every event in the file + foreach ($events as $idx => $event) { + // define buttons according to method + if ($this->ical->method == 'REPLY') { + $title = $this->gettext('itipreply'); + $buttons = html::tag('input', array( + 'type' => 'button', + 'class' => 'button', + 'onclick' => "rcube_calendar.add_event_from_mail('" . JQ($mime_id.':'.$idx) . "')", + 'value' => $this->gettext('updateattendeestatus'), + )); + } + else if ($this->ical->method == 'REQUEST') { + $emails = $this->get_user_emails(); + $title = $event['sequence'] > 0 ? $this->gettext('itipupdate') : $this->gettext('itipinvitation'); + + // add (hidden) buttons and activate them from asyncronous request + foreach (array('accepted','tentative','declined') as $method) { + $rsvp_buttons .= html::tag('input', array( + 'type' => 'button', + 'class' => "button $method", + 'onclick' => "rcube_calendar.add_event_from_mail('" . JQ($mime_id.':'.$idx) . "', '$method')", + 'value' => $this->gettext('itip' . $method), + )); + } + $import_button = html::tag('input', array( + 'type' => 'button', + 'class' => 'button', + 'onclick' => "rcube_calendar.add_event_from_mail('" . JQ($mime_id.':'.$idx) . "')", + 'value' => $this->gettext('importtocalendar'), + )); + + // check my status + $status = 'unknown'; + foreach ($event['attendees'] as $attendee) { + if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { + $status = strtoupper($attendee['status']); + break; + } + } + + $dom_id = asciiwords($event['uid'], true); + $buttons = html::div(array('id' => 'rsvp-'.$dom_id, 'style' => 'display:none'), $rsvp_buttons); + $buttons .= html::div(array('id' => 'import-'.$dom_id, 'style' => 'display:none'), $import_button); + $buttons_pre = html::div(array('id' => 'loading-'.$dom_id, 'class' => 'rsvp-status loading'), $this->gettext('loading')); + + $this->rc->output->add_script('rcube_calendar.fetch_event_rsvp_status(' . json_serialize(array('uid' => $event['uid'], 'changed' => $event['changed']->format('U'), 'sequence' => intval($event['sequence']), 'fallback' => $status)) . ')', 'docready'); + } + else if ($this->ical->method == 'CANCEL') { + $title = $this->gettext('itipcancellation'); + + // create buttons to be activated from async request checking existence of this event in local calendars + $button_import = html::tag('input', array( + 'type' => 'button', + 'class' => 'button', + 'onclick' => "rcube_calendar.add_event_from_mail('" . JQ($mime_id.':'.$idx) . "')", + 'value' => $this->gettext('importtocalendar'), + )); + $button_remove = html::tag('input', array( + 'type' => 'button', + 'class' => 'button', + 'onclick' => "rcube_calendar.remove_event_from_mail('" . JQ($event['uid']) . "', '" . JQ($event['title']) . "')", + 'value' => $this->gettext('removefromcalendar'), + )); + + $dom_id = asciiwords($event['uid'], true); + $buttons = html::div(array('id' => 'rsvp-'.$dom_id, 'style' => 'display:none'), $button_remove); + $buttons .= html::div(array('id' => 'import-'.$dom_id, 'style' => 'display:none'), $button_import); + $buttons_pre = html::div(array('id' => 'loading-'.$dom_id, 'class' => 'rsvp-status loading'), $this->gettext('loading')); + + $this->rc->output->add_script('rcube_calendar.fetch_event_rsvp_status(' . json_serialize(array('uid' => $event['uid'], 'changed' => $event['changed']->format('U'), 'sequence' => intval($event['sequence']), 'fallback' => 'CANCELLED')) . ')', 'docready'); + } + else { + $buttons = html::tag('input', array( + 'type' => 'button', + 'class' => 'button', + 'onclick' => "rcube_calendar.add_event_from_mail('" . JQ($mime_id.':'.$idx) . "')", + 'value' => $this->gettext('importtocalendar'), + )); + } + + // show event details with buttons + $html .= html::div('calendar-invitebox', $this->ui->event_details_table($event, $title) . $buttons_pre . html::div('rsvp-buttons', $buttons)); + + // limit listing + if ($idx >= 3) + break; + } + } + + // prepend event boxes to message body + if ($html) { + $this->ui->init(); + $p['content'] = $html . $p['content']; + $this->rc->output->add_label('calendar.savingdata','calendar.deleteventconfirm','calendar.declinedeleteconfirm'); + } + + return $p; + } + + + /** + * Handler for POST request to import an event attached to a mail message + */ + public function mail_import_event() + { + $uid = get_input_value('_uid', RCUBE_INPUT_POST); + $mbox = get_input_value('_mbox', RCUBE_INPUT_POST); + $mime_id = get_input_value('_part', RCUBE_INPUT_POST); + $status = get_input_value('_status', RCUBE_INPUT_POST); + $delete = intval(get_input_value('_del', RCUBE_INPUT_POST)); + $charset = RCMAIL_CHARSET; + + // establish imap connection + $imap = $this->rc->get_storage(); + $imap->set_mailbox($mbox); + + if ($uid && $mime_id) { + list($mime_id, $index) = explode(':', $mime_id); + $part = $imap->get_message_part($uid, $mime_id); + if ($part->ctype_parameters['charset']) + $charset = $part->ctype_parameters['charset']; + $headers = $imap->get_message_headers($uid); + } + + $events = $this->get_ical()->import($part, $charset); + + $error_msg = $this->gettext('errorimportingevent'); + $success = false; + + // successfully parsed events? + if (!empty($events) && ($event = $events[$index])) { + // find writeable calendar to store event + $cal_id = !empty($_REQUEST['_calendar']) ? get_input_value('_calendar', RCUBE_INPUT_POST) : null; + $calendars = $this->driver->list_calendars(false, true); + $calendar = $calendars[$cal_id] ?: $this->get_default_calendar(true); + + // update my attendee status according to submitted method + if (!empty($status)) { + $organizer = null; + $emails = $this->get_user_emails(); + foreach ($event['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') { + $organizer = $attendee; + } + else if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { + $event['attendees'][$i]['status'] = strtoupper($status); + $reply_sender = $attendee['email']; + } + } + } + + // save to calendar + if ($calendar && !$calendar['readonly']) { + $event['calendar'] = $calendar['id']; + + // check for existing event with the same UID + $existing = $this->driver->get_event($event['uid'], true, false, true); + + if ($existing) { + // only update attendee status + if ($this->ical->method == 'REPLY') { + // try to identify the attendee using the email sender address + $sender = preg_match('/([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,}))/', $headers->from, $m) ? $m[1] : ''; + $sender_utf = rcube_idn_to_utf8($sender); + + $existing_attendee = -1; + foreach ($existing['attendees'] as $i => $attendee) { + if ($sender && ($attendee['email'] == $sender || $attendee['email'] == $sender_utf)) { + $existing_attendee = $i; + break; + } + } + $event_attendee = null; + foreach ($event['attendees'] as $attendee) { + if ($sender && ($attendee['email'] == $sender || $attendee['email'] == $sender_utf)) { + $event_attendee = $attendee; + break; + } + } + + // found matching attendee entry in both existing and new events + if ($existing_attendee >= 0 && $event_attendee) { + $existing['attendees'][$existing_attendee] = $event_attendee; + $success = $this->driver->edit_event($existing); + } + // update the entire attendees block + else if ($event['changed'] >= $existing['changed'] && $event['attendees']) { + $existing['attendees'] = $event['attendees']; + $success = $this->driver->edit_event($existing); + } + else { + $error_msg = $this->gettext('newerversionexists'); + } + } + // delete the event when declined (#1670) + else if ($status == 'declined' && $delete) { + $deleted = $this->driver->remove_event($existing, true); + $success = true; + } + // import the (newer) event + else if ($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed']) { + $event['id'] = $existing['id']; + $event['calendar'] = $existing['calendar']; + if ($status == 'declined') // show me as free when declined (#1670) + $event['free_busy'] = 'free'; + $success = $this->driver->edit_event($event); + } + else if (!empty($status)) { + $existing['attendees'] = $event['attendees']; + if ($status == 'declined') // show me as free when declined (#1670) + $existing['free_busy'] = 'free'; + $success = $this->driver->edit_event($existing); + } + else + $error_msg = $this->gettext('newerversionexists'); + } + else if (!$existing && $status != 'declined') { + $success = $this->driver->new_event($event); + } + else if ($status == 'declined') + $error_msg = null; + } + else if ($status == 'declined') + $error_msg = null; + else + $error_msg = $this->gettext('nowritecalendarfound'); + } + + if ($success) { + $message = $this->ical->method == 'REPLY' ? 'attendeupdateesuccess' : ($deleted ? 'successremoval' : 'importedsuccessfully'); + $this->rc->output->command('display_message', $this->gettext(array('name' => $message, 'vars' => array('calendar' => $calendar['name']))), 'confirmation'); + $this->rc->output->command('plugin.fetch_event_rsvp_status', array('uid' => $event['uid'], 'changed' => $event['changed']->format('U'), 'sequence' => intval($event['sequence']), 'fallback' => strtoupper($status))); + $error_msg = null; + } + else if ($error_msg) + $this->rc->output->command('display_message', $error_msg, 'error'); + + + // send iTip reply + if ($this->ical->method == 'REQUEST' && $organizer && !in_array(strtolower($organizer['email']), $emails) && !$error_msg) { + $itip = $this->load_itip(); + $itip->set_sender_email($reply_sender); + if ($itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status)) + $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation'); + else + $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); + } + + $this->rc->output->send(); + } + + + /** + * Read email message and return contents for a new event based on that message + */ + public function mail_message2event() + { + $uid = get_input_value('_uid', RCUBE_INPUT_POST); + $mbox = get_input_value('_mbox', RCUBE_INPUT_POST); + $event = array(); + + // establish imap connection + $imap = $this->rc->get_storage(); + $imap->set_mailbox($mbox); + $message = new rcube_message($uid); + + if ($message->headers) { + $event['title'] = trim($message->subject); + $event['description'] = trim($message->first_text_part()); + + // copy mail attachments to event + if ($message->attachments) { + $eventid = 'cal:'; + if (!is_array($_SESSION[self::SESSION_KEY]) || $_SESSION[self::SESSION_KEY]['id'] != $eventid) { + $_SESSION[self::SESSION_KEY] = array(); + $_SESSION[self::SESSION_KEY]['id'] = $eventid; + $_SESSION[self::SESSION_KEY]['attachments'] = array(); + } + + foreach ((array)$message->attachments as $part) { + $attachment = array( + 'data' => $imap->get_message_part($uid, $part->mime_id, $part), + 'size' => $part->size, + 'name' => $part->filename, + 'mimetype' => $part->mimetype, + 'group' => $eventid, + ); + + $attachment = $this->rc->plugins->exec_hook('attachment_save', $attachment); + + if ($attachment['status'] && !$attachment['abort']) { + $id = $attachment['id']; + $attachment['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']); + + // store new attachment in session + unset($attachment['status'], $attachment['abort'], $attachment['data']); + $_SESSION[self::SESSION_KEY]['attachments'][$id] = $attachment; + + $attachment['id'] = 'rcmfile' . $attachment['id']; // add prefix to consider it 'new' + $event['attachments'][] = $attachment; + } + } + } + + $this->rc->output->command('plugin.mail2event_dialog', $event); + } + else { + $this->rc->output->command('display_message', $this->gettext('messageopenerror'), 'error'); + } + + $this->rc->output->send(); + } + + + /** + * Checks if specified message part is a vcalendar data + * + * @param rcube_message_part Part object + * @return boolean True if part is of type vcard + */ + private function is_vcalendar($part) + { + return ( + in_array($part->mimetype, array('text/calendar', 'text/x-vcalendar', 'application/ics')) || + // Apple sends files as application/x-any (!?) + ($part->mimetype == 'application/x-any' && $part->filename && preg_match('/\.ics$/i', $part->filename)) + ); + } + + + /** + * Get a list of email addresses of the current user (from login and identities) + */ + private function get_user_emails() + { + $emails = array(); + $plugin = $this->rc->plugins->exec_hook('calendar_user_emails', array('emails' => $emails)); + $emails = array_map('strtolower', $plugin['emails']); + + if ($plugin['abort']) { + return $emails; + } + + $emails[] = $this->rc->user->get_username(); + foreach ($this->rc->user->list_identities() as $identity) + $emails[] = strtolower($identity['email']); + + return array_unique($emails); + } + + + /** + * Build an absolute URL with the given parameters + */ + public function get_url($param = array()) + { + $param += array('task' => 'calendar'); + + $schema = 'http'; + $default_port = 80; + if (rcube_https_check()) { + $schema = 'https'; + $default_port = 443; + } + $url = $schema . '://' . $_SERVER['HTTP_HOST']; + if ($_SERVER['SERVER_PORT'] != $default_port) + $url .= ':' . $_SERVER['SERVER_PORT']; + if (dirname($_SERVER['SCRIPT_NAME']) != '/') + $url .= dirname($_SERVER['SCRIPT_NAME']); + $url .= preg_replace('!^\./!', '/', $this->rc->url($param)); + + return $url; + } + + + public function ical_feed_hash($source) + { + return base64_encode($this->rc->user->get_username() . ':' . $source); + } + +} diff --git a/calendar_base.js b/calendar_base.js new file mode 100644 index 0000000..c60c89a --- /dev/null +++ b/calendar_base.js @@ -0,0 +1,182 @@ +/** + * Base Javascript class for the Calendar plugin + * + * @version @package_version@ + * @author Lazlo Westerhof + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +// Basic setup for Roundcube calendar client class +function rcube_calendar(settings) +{ + // extend base class + rcube_libcalendaring.call(this, settings); + + // member vars + this.ui; + this.ui_loaded = false; + + // private vars + var me = this; + + // create new event from current mail message + this.create_from_mail = function() + { + var uid; + if ((uid = rcmail.get_single_uid())) { + // load calendar UI (scripts and edit dialog template) + if (!this.ui_loaded) { + $.when( + $.getScript('./plugins/calendar/calendar_ui.js'), + $.getScript('./plugins/calendar/lib/js/fullcalendar.js'), + $.get(rcmail.url('calendar/inlineui'), function(html){ $(document.body).append(html); }, 'html') + ).then(function() { + // disable attendees feature (autocompletion and stuff is not initialized) + for (var c in rcmail.env.calendars) + rcmail.env.calendars[c].attendees = false; + + me.ui_loaded = true; + me.ui = new rcube_calendar_ui(me.settings); + me.create_from_mail(); // start over + }); + return; + } + else { + // get message contents for event dialog + var lock = rcmail.set_busy(true, 'loading'); + rcmail.http_post('calendar/mailtoevent', { + '_mbox': rcmail.env.mailbox, + '_uid': uid + }, lock); + } + } + }; + + // callback function triggered from server with contents for the new event + this.mail2event_dialog = function(event) + { + if (event.title) { + this.ui.add_event(event); + rcmail.message_list.blur(); + } + }; +} + +// static methods +rcube_calendar.add_event_from_mail = function(mime_id, status) +{ + // ask user to delete the declined event from the local calendar (#1670) + var del = false; + if (rcmail.env.rsvp_saved && status == 'declined') { + del = confirm(rcmail.gettext('calendar.declinedeleteconfirm')); + } + + var lock = rcmail.set_busy(true, 'calendar.savingdata'); + rcmail.http_post('calendar/mailimportevent', { + '_uid': rcmail.env.uid, + '_mbox': rcmail.env.mailbox, + '_part': mime_id, + '_calendar': $('#calendar-saveto').val(), + '_status': status, + '_del': del?1:0 + }, lock); + + return false; +}; + +rcube_calendar.remove_event_from_mail = function(uid, title) +{ + if (confirm(rcmail.gettext('calendar.deleteventconfirm'))) { + var lock = rcmail.set_busy(true, 'calendar.savingdata'); + rcmail.http_post('calendar/event', { + e:{ uid:uid }, + action: 'remove' + }, lock); + } +}; + +rcube_calendar.fetch_event_rsvp_status = function(event) +{ +/* + var id = event.uid.replace(rcmail.identifier_expr, ''); + $('#import-'+id+', #rsvp-'+id+', div.rsvp-status').hide(); + $('#loading-'+id).show(); +*/ + rcmail.http_post('calendar/event', { + e:event, + action:'rsvp-status' + }); +}; + + +/* calendar plugin initialization (for non-calendar tasks) */ +window.rcmail && rcmail.addEventListener('init', function(evt) { + if (rcmail.task != 'calendar') { + var cal = new rcube_calendar($.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings)); + + rcmail.addEventListener('plugin.update_event_rsvp_status', function(p){ + rcmail.env.rsvp_saved = p.saved; + + if (p.html) { + // append/replace rsvp status display + $('#loading-'+p.id).next('.rsvp-status').remove(); + $('#loading-'+p.id).hide().after(p.html); + } + else { + $('#loading-'+p.id).hide(); + } + + // enable/disable rsvp buttons + $('.rsvp-buttons input.button').prop('disabled', false) + .filter('.'+String(p.status).toLowerCase()).prop('disabled', p.latest); + + // show rsvp/import buttons with or without calendar selector + if (!p.select) + $('#rsvp-'+p.id+' .calendar-select').remove(); + $('#'+p.action+'-'+p.id).show().append(p.select); + }); + + rcmail.addEventListener('plugin.fetch_event_rsvp_status', rcube_calendar.fetch_event_rsvp_status); + + // register create-from-mail command to message_commands array + if (rcmail.env.task == 'mail') { + // place link above 'view source' + $('#messagemenu a.calendarlink').parent().insertBefore($('#messagemenu a.sourcelink').parent()); + + rcmail.register_command('calendar-create-from-mail', function() { cal.create_from_mail() }); + rcmail.addEventListener('plugin.mail2event_dialog', function(p){ cal.mail2event_dialog(p) }); + rcmail.addEventListener('plugin.unlock_saving', function(p){ cal.ui && cal.ui.unlock_saving(); }); + + if (rcmail.env.action != 'show') { + rcmail.env.message_commands.push('calendar-create-from-mail'); + rcmail.add_element($('')); + } + else + rcmail.enable_command('calendar-create-from-mail', true); + } + } + + rcmail.register_command('plugin.calendar', function() { rcmail.switch_task('calendar'); }, true); + + rcmail.addEventListener('plugin.ping_url', function(p){ + var action = p.action; + p.action = p.event = null; + new Image().src = rcmail.url(action, p); + }); +}); diff --git a/calendar_ui.js b/calendar_ui.js new file mode 100644 index 0000000..a0bc0bb --- /dev/null +++ b/calendar_ui.js @@ -0,0 +1,2758 @@ +/** + * Client UI Javascript for the Calendar plugin + * + * @version @package_version@ + * @author Lazlo Westerhof + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +// Roundcube calendar UI client class +function rcube_calendar_ui(settings) +{ + // extend base class + rcube_calendar.call(this, settings); + + /*** member vars ***/ + this.is_loading = false; + this.selected_event = null; + this.selected_calendar = null; + this.search_request = null; + this.saving_lock; + + + /*** private vars ***/ + var DAY_MS = 86400000; + var HOUR_MS = 3600000; + var me = this; + var gmt_offset = (new Date().getTimezoneOffset() / -60) - (settings.timezone || 0) - (settings.dst || 0); + var client_timezone = new Date().getTimezoneOffset(); + var day_clicked = day_clicked_ts = 0; + var ignore_click = false; + var event_defaults = { free_busy:'busy', alarms:'' }; + var event_attendees = []; + var attendees_list; + var freebusy_ui = { workinhoursonly:false, needsupdate:false }; + var freebusy_data = {}; + var current_view = null; + var exec_deferred = bw.ie6 ? 5 : 1; + var sensitivitylabels = { 'public':rcmail.gettext('public','calendar'), 'private':rcmail.gettext('private','calendar'), 'confidential':rcmail.gettext('confidential','calendar') }; + var ui_loading = rcmail.set_busy(true, 'loading'); + + // general datepicker settings + var datepicker_settings = { + // translate from fullcalendar format to datepicker format + dateFormat: settings['date_format'].replace(/M/g, 'm').replace(/mmmmm/, 'MM').replace(/mmm/, 'M').replace(/dddd/, 'DD').replace(/ddd/, 'D').replace(/yy/g, 'y'), + firstDay : settings['first_day'], + dayNamesMin: settings['days_short'], + monthNames: settings['months'], + monthNamesShort: settings['months'], + changeMonth: false, + showOtherMonths: true, + selectOtherMonths: true + }; + + /*** imports ***/ + var Q = this.quote_html; + var text2html = this.text2html; + var event_date_text = this.event_date_text; + var parse_datetime = this.parse_datetime; + var date2unixtime = this.date2unixtime; + var fromunixtime = this.fromunixtime; + var parseISO8601 = this.parseISO8601; + var init_alarms_edit = this.init_alarms_edit; + + + /*** private methods ***/ + + // same as str.split(delimiter) but it ignores delimiters within quoted strings + var explode_quoted_string = function(str, delimiter) + { + var result = [], + strlen = str.length, + q, p, i, char, last; + + for (q = p = i = 0; i < strlen; i++) { + char = str.charAt(i); + if (char == '"' && last != '\\') { + q = !q; + } + else if (!q && char == delimiter) { + result.push(str.substring(p, i)); + p = i + 1; + } + last = char; + } + + result.push(str.substr(p)); + return result; + }; + + + // clone the given date object and optionally adjust time + var clone_date = function(date, adjust) + { + var d = new Date(date.getTime()); + + // set time to 00:00 + if (adjust == 1) { + d.setHours(0); + d.setMinutes(0); + } + // set time to 23:59 + else if (adjust == 2) { + d.setHours(23); + d.setMinutes(59); + } + + return d; + }; + + // fix date if jumped over a DST change + var fix_date = function(date) + { + if (date.getHours() == 23) + date.setTime(date.getTime() + HOUR_MS); + else if (date.getHours() > 0) + date.setHours(0); + }; + + // turn the given date into an ISO 8601 date string understandable by PHPs strtotime() + var date2servertime = function(date) + { + return date.getFullYear()+'-'+zeropad(date.getMonth()+1)+'-'+zeropad(date.getDate()) + + 'T'+zeropad(date.getHours())+':'+zeropad(date.getMinutes())+':'+zeropad(date.getSeconds()); + } + + var date2timestring = function(date, dateonly) + { + return date2servertime(date).replace(/[^0-9]/g, '').substr(0, (dateonly ? 8 : 14)); + } + + var zeropad = function(num) + { + return (num < 10 ? '0' : '') + num; + } + + var render_link = function(url) + { + var islink = false, href = url; + if (url.match(/^[fhtpsmailo]+?:\/\//i)) { + islink = true; + } + else if (url.match(/^[a-z0-9.-:]+(\/|$)/i)) { + islink = true; + href = 'http://' + url; + } + return islink ? '' + Q(url) + '' : Q(url); + } + + // determine whether the given date is on a weekend + var is_weekend = function(date) + { + return date.getDay() == 0 || date.getDay() == 6; + }; + + var is_workinghour = function(date) + { + if (settings['work_start'] > settings['work_end']) + return date.getHours() >= settings['work_start'] || date.getHours() < settings['work_end']; + else + return date.getHours() >= settings['work_start'] && date.getHours() < settings['work_end']; + }; + + // check if the event has 'real' attendees, excluding the current user + var has_attendees = function(event) + { + return (event.attendees && event.attendees.length && (event.attendees.length > 1 || String(event.attendees[0].email).toLowerCase() != settings.identity.email)); + }; + + // check if the current user is an attendee of this event + var is_attendee = function(event, role, email) + { + var emails = email ? ';'+email.toLowerCase() : settings.identity.emails; + for (var i=0; event.attendees && i < event.attendees.length; i++) { + if ((!role || event.attendees[i].role == role) && event.attendees[i].email && emails.indexOf(';'+event.attendees[i].email.toLowerCase()) >= 0) + return event.attendees[i]; + } + return false; + }; + + // check if the current user is the organizer + var is_organizer = function(event, email) + { + return is_attendee(event, 'ORGANIZER', email) || !event.id; + }; + + var load_attachment = function(event, att) + { + var qstring = '_id='+urlencode(att.id)+'&_event='+urlencode(event.recurrence_id||event.id)+'&_cal='+urlencode(event.calendar); + + // open attachment in frame if it's of a supported mimetype + if (id && att.mimetype && $.inArray(att.mimetype, settings.mimetypes)>=0) { + if (rcmail.open_window(rcmail.env.comm_path+'&_action=get-attachment&'+qstring+'&_frame=1', true, true)) { + return; + } + } + + rcmail.goto_url('get-attachment', qstring+'&_download=1', false); + }; + + // build event attachments list + var event_show_attachments = function(list, container, event, edit) + { + var i, id, len, img, content, li, elem, + ul = document.createElement('UL'); + ul.className = 'attachmentslist'; + + for (i=0, len=list.length; i now shown in dialog title + // $('#event-date').html(Q(me.event_date_text(event))).show(); + + if (event.recurrence && event.recurrence_text) + $('#event-repeat').show().children('.event-text').html(Q(event.recurrence_text)); + + if (event.alarms && event.alarms_text) + $('#event-alarm').show().children('.event-text').html(Q(event.alarms_text)); + + if (calendar.name) + $('#event-calendar').show().children('.event-text').html(Q(calendar.name)).removeClass().addClass('event-text').addClass('cal-'+calendar.id); + if (event.categories) + $('#event-category').show().children('.event-text').html(Q(event.categories)).removeClass().addClass('event-text cat-'+String(event.categories).replace(rcmail.identifier_expr, '')); + if (event.free_busy) + $('#event-free-busy').show().children('.event-text').html(Q(rcmail.gettext(event.free_busy, 'calendar'))); + if (event.priority > 0) { + var priolabels = [ '', rcmail.gettext('highest'), rcmail.gettext('high'), '', '', rcmail.gettext('normal'), '', '', rcmail.gettext('low'), rcmail.gettext('lowest') ]; + $('#event-priority').show().children('.event-text').html(Q(event.priority+' '+priolabels[event.priority])); + } + + if (event.sensitivity && event.sensitivity != 'public') { + $('#event-sensitivity').show().children('.event-text').html(Q(sensitivitylabels[event.sensitivity])); + $dialog.addClass('sensitivity-'+event.sensitivity); + } + + // create attachments list + if ($.isArray(event.attachments)) { + event_show_attachments(event.attachments, $('#event-attachments').children('.event-text'), event); + if (event.attachments.length > 0) { + $('#event-attachments').show(); + } + } + else if (calendar.attachments) { + // fetch attachments, some drivers doesn't set 'attachments' prop of the event? + } + + // list event attendees + if (calendar.attendees && event.attendees) { + var data, dispname, organizer = false, rsvp = false, html = ''; + for (var j=0; j < event.attendees.length; j++) { + data = event.attendees[j]; + dispname = Q(data.name || data.email); + if (data.email) { + dispname = '' + dispname + ''; + if (data.role == 'ORGANIZER') + organizer = true; + else if ((data.status == 'NEEDS-ACTION' || data.status == 'TENTATIVE') && settings.identity.emails.indexOf(';'+data.email) >= 0) + rsvp = data.status.toLowerCase(); + } + html += '' + dispname + ' '; + + // stop listing attendees + if (j == 7 && event.attendees.length >= 7) { + html += ' ' + rcmail.gettext('andnmore', 'calendar').replace('$nr', event.attendees.length - j - 1) + ''; + break; + } + } + + if (html && (event.attendees.length > 1 || !organizer)) { + $('#event-attendees').show() + .children('.event-text') + .html(html) + .find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); + } + + $('#event-rsvp')[(rsvp&&!organizer?'show':'hide')](); + $('#event-rsvp .rsvp-buttons input').prop('disabled', false).filter('input[rel='+rsvp+']').prop('disabled', true); + } + + var buttons = {}; + if (calendar.editable && event.editable !== false) { + buttons[rcmail.gettext('edit', 'calendar')] = function() { + event_edit_dialog('edit', event); + }; + buttons[rcmail.gettext('remove', 'calendar')] = function() { + me.delete_event(event); + $dialog.dialog('close'); + }; + } + else { + buttons[rcmail.gettext('close', 'calendar')] = function(){ + $dialog.dialog('close'); + }; + } + + // open jquery UI dialog + $dialog.dialog({ + modal: false, + resizable: !bw.ie6, + closeOnEscape: (!bw.ie6 && !bw.ie7), // disable for performance reasons + title: Q(me.event_date_text(event)), + open: function() { + $dialog.parent().find('.ui-button').first().focus(); + }, + close: function() { + $dialog.dialog('destroy').hide(); + }, + buttons: buttons, + minWidth: 320, + width: 420 + }).show(); + + // set dialog size according to content + me.dialog_resize($dialog.get(0), $dialog.height(), 420); +/* + // add link for "more options" drop-down + $('') + .attr('href', '#') + .html('More Options') + .addClass('dropdown-link') + .click(function(){ return false; }) + .insertBefore($dialog.parent().find('.ui-dialog-buttonset').children().first()); +*/ + }; + + // bring up the event dialog (jquery-ui popup) + var event_edit_dialog = function(action, event) + { + // close show dialog first + $("#eventshow:ui-dialog").dialog('close'); + + var $dialog = $('
'); + var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:action=='new' }; + me.selected_event = $.extend($.extend({}, event_defaults), event); // clone event object (with defaults) + event = me.selected_event; // change reference to clone + freebusy_ui.needsupdate = false; + + // reset dialog first + $('#eventtabs').get(0).reset(); + + // allow other plugins to do actions when event form is opened + rcmail.triggerEvent('calendar-event-init', {o: event}); + + // event details + var title = $('#edit-title').val(event.title || ''); + var location = $('#edit-location').val(event.location || ''); + var description = $('#edit-description').html(event.description || ''); + var vurl = $('#edit-url').val(event.vurl || ''); + var categories = $('#edit-categories').val(event.categories); + var calendars = $('#edit-calendar').val(event.calendar); + var freebusy = $('#edit-free-busy').val(event.free_busy); + var priority = $('#edit-priority').val(event.priority); + var sensitivity = $('#edit-sensitivity').val(event.sensitivity); + + var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000); + var startdate = $('#edit-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration); + var starttime = $('#edit-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show(); + var enddate = $('#edit-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format'])); + var endtime = $('#edit-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show(); + var allday = $('#edit-allday').get(0); + var notify = $('#edit-attendees-donotify').get(0); + var invite = $('#edit-attendees-invite').get(0); + notify.checked = has_attendees(event), invite.checked = true; + + if (event.allDay) { + starttime.val("12:00").hide(); + endtime.val("13:00").hide(); + allday.checked = true; + } + else { + allday.checked = false; + } + + // set alarm(s) + // TODO: support multiple alarm entries + if (event.alarms || action != 'new') { + if (typeof event.alarms == 'string') + event.alarms = event.alarms.split(';'); + + var valarms = event.alarms || ['']; + for (var alarm, i=0; i < valarms.length; i++) { + alarm = String(valarms[i]).split(':'); + if (!alarm[1] && alarm[0]) alarm[1] = 'DISPLAY'; + $('#eventedit select.edit-alarm-type').val(alarm[1]); + + if (alarm[0].match(/@(\d+)/)) { + var ondate = fromunixtime(parseInt(RegExp.$1)); + $('#eventedit select.edit-alarm-offset').val('@'); + $('#eventedit input.edit-alarm-date').val($.fullCalendar.formatDate(ondate, settings['date_format'])); + $('#eventedit input.edit-alarm-time').val($.fullCalendar.formatDate(ondate, settings['time_format'])); + } + else if (alarm[0].match(/([-+])(\d+)([MHD])/)) { + $('#eventedit input.edit-alarm-value').val(RegExp.$2); + $('#eventedit select.edit-alarm-offset').val(''+RegExp.$1+RegExp.$3); + } + } + } + // set correct visibility by triggering onchange handlers + $('#eventedit select.edit-alarm-type, #eventedit select.edit-alarm-offset').change(); + + // enable/disable alarm property according to backend support + $('#edit-alarms')[(calendar.alarms ? 'show' : 'hide')](); + + // check categories drop-down: add value if not exists + if (event.categories && !categories.find("option[value='"+event.categories+"']").length) { + $(' '; + list_html += '
' + role_html + dispname + '
'; + + // clone attendees data for local modifications + freebusy_ui.attendees[i] = freebusy_ui.attendees[domid] = $.extend({}, data); + } + + // add total row + list_html += '
 
'; + list_html += '
' + rcmail.gettext('reqallattendees','calendar') + '
'; + + $('#schedule-attendees-list').html(list_html) + .unbind('click.roleicons') + .bind('click.roleicons', function(e){ + // toggle attendee status upon click on icon + if (e.target.id && e.target.id.match(/rcmlia(.+)/)) { + var attendee, domid = RegExp.$1, roles = [ 'REQ-PARTICIPANT', 'OPT-PARTICIPANT', 'CHAIR' ]; + if ((attendee = freebusy_ui.attendees[domid]) && attendee.role != 'ORGANIZER') { + var req = attendee.role != 'OPT-PARTICIPANT'; + var j = $.inArray(attendee.role, roles); + j = (j+1) % roles.length; + attendee.role = roles[j]; + $(e.target).parent().removeClass().addClass('attendee '+String(attendee.role).toLowerCase()); + + // update total display if required-status changed + if (req != (roles[j] != 'OPT-PARTICIPANT')) { + compute_freebusy_totals(); + update_freebusy_display(attendee.email); + } + } + } + + return false; + }); + + // enable/disable buttons + $('#shedule-find-prev').button('option', 'disabled', (fb_start.getTime() < now.getTime())); + + // dialog buttons + var buttons = {}; + + buttons[rcmail.gettext('select', 'calendar')] = function() { + $('#edit-startdate').val(freebusy_ui.startdate.val()); + $('#edit-starttime').val(freebusy_ui.starttime.val()); + $('#edit-enddate').val(freebusy_ui.enddate.val()); + $('#edit-endtime').val(freebusy_ui.endtime.val()); + + // write role changes back to main dialog + $('select.edit-attendee-role').each(function(i, elem){ + if (event_attendees[i] && freebusy_ui.attendees[i]) { + event_attendees[i].role = freebusy_ui.attendees[i].role; + $(elem).val(event_attendees[i].role); + } + }); + + if (freebusy_ui.needsupdate) + update_freebusy_status(me.selected_event); + freebusy_ui.needsupdate = false; + $dialog.dialog("close"); + }; + + buttons[rcmail.gettext('cancel', 'calendar')] = function() { + $dialog.dialog("close"); + }; + + $dialog.dialog({ + modal: true, + resizable: true, + closeOnEscape: (!bw.ie6 && !bw.ie7), + title: rcmail.gettext('scheduletime', 'calendar'), + open: function() { + $dialog.parent().find('.ui-dialog-buttonset .ui-button').first().focus(); + }, + close: function() { + if (bw.ie6) + $("#edit-attendees-table").css('visibility','visible'); + $dialog.dialog("destroy").hide(); + }, + resizeStop: function() { + render_freebusy_overlay(); + }, + buttons: buttons, + minWidth: 640, + width: 850 + }).show(); + + // hide edit dialog on IE6 because of drop-down elements + if (bw.ie6) + $("#edit-attendees-table").css('visibility','hidden'); + + // adjust dialog size to fit grid without scrolling + var gridw = $('#schedule-freebusy-times').width(); + var overflow = gridw - $('#attendees-freebusy-table td.times').width() + 1; + me.dialog_resize($dialog.get(0), $dialog.height() + (bw.ie ? 20 : 0), 800 + Math.max(0, overflow)); + + // fetch data from server + freebusy_ui.loading = 0; + load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); + }; + + // render an HTML table showing free-busy status for all the event attendees + var render_freebusy_grid = function(delta) + { + if (delta) { + freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); + fix_date(freebusy_ui.start); + + // skip weekends if in workinhoursonly-mode + if (Math.abs(delta) == 1 && freebusy_ui.workinhoursonly) { + while (is_weekend(freebusy_ui.start)) + freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); + fix_date(freebusy_ui.start); + } + + freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); + } + + var dayslots = Math.floor(1440 / freebusy_ui.interval); + var date_format = 'ddd '+ (dayslots <= 2 ? settings.date_short : settings.date_format); + var lastdate, datestr, css, + curdate = new Date(), + allday = (freebusy_ui.interval == 1440), + times_css = (allday ? 'allday ' : ''), + dates_row = '', + times_row = '', + slots_row = ''; + for (var s = 0, t = freebusy_ui.start.getTime(); t < freebusy_ui.end.getTime(); s++) { + curdate.setTime(t); + datestr = fc.fullCalendar('formatDate', curdate, date_format); + if (datestr != lastdate) { + if (lastdate && !allday) break; + dates_row += '' + Q(datestr) + ''; + lastdate = datestr; + } + + // set css class according to working hours + css = is_weekend(curdate) || (freebusy_ui.interval <= 60 && !is_workinghour(curdate)) ? 'offhours' : 'workinghours'; + times_row += '' + Q(allday ? rcmail.gettext('all-day','calendar') : $.fullCalendar.formatDate(curdate, settings['time_format'])) + ''; + slots_row += ' '; + + t += freebusy_ui.interval * 60000; + } + dates_row += ''; + times_row += ''; + + // render list of attendees + var domid, data, list_html = '', times_html = ''; + for (var i=0; i < event_attendees.length; i++) { + data = event_attendees[i]; + domid = String(data.email).replace(rcmail.identifier_expr, ''); + times_html += '' + slots_row + ''; + } + + // add line for all/required attendees + times_html += ' '; + times_html += '' + slots_row + ''; + + var table = $('#schedule-freebusy-times'); + table.children('thead').html(dates_row + times_row); + table.children('tbody').html(times_html); + + // initialize event handlers on grid + if (!freebusy_ui.grid_events) { + freebusy_ui.grid_events = true; + table.children('thead').click(function(e){ + // move event to the clicked date/time + if (e.target.id && e.target.id.match(/t-(\d+)/)) { + var newstart = new Date(RegExp.$1 * 1000); + // set time to 00:00 + if (me.selected_event.allDay) { + newstart.setMinutes(0); + newstart.setHours(0); + } + update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); + render_freebusy_overlay(); + } + }) + } + + // if we have loaded free-busy data, show it + if (!freebusy_ui.loading) { + if (freebusy_ui.start < freebusy_data.start || freebusy_ui.end > freebusy_data.end || freebusy_ui.interval != freebusy_data.interval) { + load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); + } + else { + for (var email, i=0; i < event_attendees.length; i++) { + if ((email = event_attendees[i].email)) + update_freebusy_display(email); + } + } + } + + // render current event date/time selection over grid table + // use timeout to let the dom attributes (width/height/offset) be set first + window.setTimeout(function(){ render_freebusy_overlay(); }, 10); + }; + + // render overlay element over the grid to visiualize the current event date/time + var render_freebusy_overlay = function() + { + var overlay = $('#schedule-event-time'); + if (me.selected_event.end.getTime() <= freebusy_ui.start.getTime() || me.selected_event.start.getTime() >= freebusy_ui.end.getTime()) { + overlay.hide(); + if (overlay.data('isdraggable')) + overlay.draggable('disable'); + } + else { + var table = $('#schedule-freebusy-times'), + width = 0, + pos = { top:table.children('thead').height(), left:0 }, + eventstart = date2unixtime(clone_date(me.selected_event.start, me.selected_event.allDay?1:0)), + eventend = date2unixtime(clone_date(me.selected_event.end, me.selected_event.allDay?2:0)) - 60, + slotstart = date2unixtime(freebusy_ui.start), + slotsize = freebusy_ui.interval * 60, + slotend, fraction, $cell; + + // iterate through slots to determine position and size of the overlay + table.children('thead').find('td').each(function(i, cell){ + slotend = slotstart + slotsize - 1; + // event starts in this slot: compute left + if (eventstart >= slotstart && eventstart <= slotend) { + fraction = 1 - (slotend - eventstart) / slotsize; + pos.left = Math.round(cell.offsetLeft + cell.offsetWidth * fraction); + } + // event ends in this slot: compute width + if (eventend >= slotstart && eventend <= slotend) { + fraction = 1 - (slotend - eventend) / slotsize; + width = Math.round(cell.offsetLeft + cell.offsetWidth * fraction) - pos.left; + } + + slotstart = slotstart + slotsize; + }); + + if (!width) + width = table.width() - pos.left; + + // overlay is visible + if (width > 0) { + overlay.css({ width: (width-5)+'px', height:(table.children('tbody').height() - 4)+'px', left:pos.left+'px', top:pos.top+'px' }).show(); + + // configure draggable + if (!overlay.data('isdraggable')) { + overlay.draggable({ + axis: 'x', + scroll: true, + stop: function(e, ui){ + // convert pixels to time + var px = ui.position.left; + var range_p = $('#schedule-freebusy-times').width(); + var range_t = freebusy_ui.end.getTime() - freebusy_ui.start.getTime(); + var newstart = new Date(freebusy_ui.start.getTime() + px * (range_t / range_p)); + newstart.setSeconds(0); newstart.setMilliseconds(0); + // snap to day boundaries + if (me.selected_event.allDay) { + if (newstart.getHours() >= 12) // snap to next day + newstart.setTime(newstart.getTime() + DAY_MS); + newstart.setMinutes(0); + newstart.setHours(0); + } + else { + // round to 5 minutes + var round = newstart.getMinutes() % 5; + if (round > 2.5) newstart.setTime(newstart.getTime() + (5 - round) * 60000); + else if (round > 0) newstart.setTime(newstart.getTime() - round * 60000); + } + // update event times and display + update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); + if (me.selected_event.allDay) + render_freebusy_overlay(); + } + }).data('isdraggable', true); + } + else + overlay.draggable('enable'); + } + else + overlay.draggable('disable').hide(); + } + + }; + + + // fetch free-busy information for each attendee from server + var load_freebusy_data = function(from, interval) + { + var start = new Date(from.getTime() - DAY_MS * 2); // start 2 days before event + fix_date(start); + var end = new Date(start.getTime() + DAY_MS * Math.max(14, freebusy_ui.numdays + 7)); // load min. 14 days + freebusy_ui.numrequired = 0; + freebusy_data.all = []; + freebusy_data.required = []; + + // load free-busy information for every attendee + var domid, email; + for (var i=0; i < event_attendees.length; i++) { + if ((email = event_attendees[i].email)) { + domid = String(email).replace(rcmail.identifier_expr, ''); + $('#rcmli' + domid).addClass('loading'); + freebusy_ui.loading++; + + $.ajax({ + type: 'GET', + dataType: 'json', + url: rcmail.url('freebusy-times'), + data: { email:email, start:date2servertime(clone_date(start, 1)), end:date2servertime(clone_date(end, 2)), interval:interval, _remote:1 }, + success: function(data) { + freebusy_ui.loading--; + + // find attendee + var attendee = null; + for (var i=0; i < event_attendees.length; i++) { + if (freebusy_ui.attendees[i].email == data.email) { + attendee = freebusy_ui.attendees[i]; + break; + } + } + + // copy data to member var + var ts, req = attendee.role != 'OPT-PARTICIPANT'; + freebusy_data.start = parseISO8601(data.start); + freebusy_data[data.email] = {}; + for (var i=0; i < data.slots.length; i++) { + ts = data.times[i] + ''; + freebusy_data[data.email][ts] = data.slots[i]; + + // set totals + if (!freebusy_data.required[ts]) + freebusy_data.required[ts] = [0,0,0,0]; + if (req) + freebusy_data.required[ts][data.slots[i]]++; + + if (!freebusy_data.all[ts]) + freebusy_data.all[ts] = [0,0,0,0]; + freebusy_data.all[ts][data.slots[i]]++; + } + freebusy_data.end = parseISO8601(data.end); + freebusy_data.interval = data.interval; + + // hide loading indicator + var domid = String(data.email).replace(rcmail.identifier_expr, ''); + $('#rcmli' + domid).removeClass('loading'); + + // update display + update_freebusy_display(data.email); + } + }); + + // count required attendees + if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT') + freebusy_ui.numrequired++; + } + } + }; + + // re-calculate total status after role change + var compute_freebusy_totals = function() + { + freebusy_ui.numrequired = 0; + freebusy_data.all = []; + freebusy_data.required = []; + + var email, req, status; + for (var i=0; i < event_attendees.length; i++) { + if (!(email = event_attendees[i].email)) + continue; + + req = freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT'; + if (req) + freebusy_ui.numrequired++; + + for (var ts in freebusy_data[email]) { + if (!freebusy_data.required[ts]) + freebusy_data.required[ts] = [0,0,0,0]; + if (!freebusy_data.all[ts]) + freebusy_data.all[ts] = [0,0,0,0]; + + status = freebusy_data[email][ts]; + freebusy_data.all[ts][status]++; + + if (req) + freebusy_data.required[ts][status]++; + } + } + }; + + // update free-busy grid with status loaded from server + var update_freebusy_display = function(email) + { + var status_classes = ['unknown','free','busy','tentative','out-of-office']; + var domid = String(email).replace(rcmail.identifier_expr, ''); + var row = $('#fbrow' + domid); + var rowall = $('#fbrowall').children(); + var dateonly = freebusy_ui.interval > 60, + t, ts = date2timestring(freebusy_ui.start, dateonly), + curdate = new Date(), + fbdata = freebusy_data[email]; + + if (fbdata && fbdata[ts] !== undefined && row.length) { + t = freebusy_ui.start.getTime(); + row.children().each(function(i, cell){ + curdate.setTime(t); + ts = date2timestring(curdate, dateonly); + cell.className = cell.className.replace('unknown', fbdata[ts] ? status_classes[fbdata[ts]] : 'unknown'); + + // also update total row if all data was loaded + if (freebusy_ui.loading == 0 && freebusy_data.all[ts] && (cell = rowall.get(i))) { + var workinghours = cell.className.indexOf('workinghours') >= 0; + var all_status = freebusy_data.all[ts][2] ? 'busy' : 'unknown'; + req_status = freebusy_data.required[ts][2] ? 'busy' : 'free'; + for (var j=1; j < status_classes.length; j++) { + if (freebusy_ui.numrequired && freebusy_data.required[ts][j] >= freebusy_ui.numrequired) + req_status = status_classes[j]; + if (freebusy_data.all[ts][j] == event_attendees.length) + all_status = status_classes[j]; + } + + cell.className = (workinghours ? 'workinghours ' : 'offhours ') + req_status + ' all-' + all_status; + } + + t += freebusy_ui.interval * 60000; + }); + } + }; + + // write changed event date/times back to form fields + var update_freebusy_dates = function(start, end) + { + // fix all-day evebt times + if (me.selected_event.allDay) { + var numdays = Math.floor((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / DAY_MS); + start.setHours(12); + start.setMinutes(0); + end.setTime(start.getTime() + numdays * DAY_MS); + end.setHours(13); + end.setMinutes(0); + } + me.selected_event.start = start; + me.selected_event.end = end; + freebusy_ui.startdate.val($.fullCalendar.formatDate(start, settings['date_format'])); + freebusy_ui.starttime.val($.fullCalendar.formatDate(start, settings['time_format'])); + freebusy_ui.enddate.val($.fullCalendar.formatDate(end, settings['date_format'])); + freebusy_ui.endtime.val($.fullCalendar.formatDate(end, settings['time_format'])); + freebusy_ui.needsupdate = true; + }; + + // attempt to find a time slot where all attemdees are available + var freebusy_find_slot = function(dir) + { + // exit if free-busy data isn't available yet + if (!freebusy_data || !freebusy_data.start) + return false; + + var event = me.selected_event, + eventstart = clone_date(event.start, event.allDay ? 1 : 0).getTime(), // calculate with integers + eventend = clone_date(event.end, event.allDay ? 2 : 0).getTime(), + duration = eventend - eventstart - (event.allDay ? HOUR_MS : 0), // make sure we don't cross day borders on DST change + sinterval = freebusy_data.interval * 60000, + intvlslots = 1, + numslots = Math.ceil(duration / sinterval), + checkdate, slotend, email, ts, slot, slotdate = new Date(); + + // shift event times to next possible slot + eventstart += sinterval * intvlslots * dir; + eventend += sinterval * intvlslots * dir; + + // iterate through free-busy slots and find candidates + var candidatecount = 0, candidatestart = candidateend = success = false; + for (slot = dir > 0 ? freebusy_data.start.getTime() : freebusy_data.end.getTime() - sinterval; + (dir > 0 && slot < freebusy_data.end.getTime()) || (dir < 0 && slot >= freebusy_data.start.getTime()); + slot += sinterval * dir) { + slotdate.setTime(slot); + // fix slot if just crossed a DST change + if (event.allDay) { + fix_date(slotdate); + slot = slotdate.getTime(); + } + slotend = slot + sinterval; + + if ((dir > 0 && slotend <= eventstart) || (dir < 0 && slot >= eventend)) // skip + continue; + + // respect workingours setting + if (freebusy_ui.workinhoursonly) { + if (is_weekend(slotdate) || (freebusy_data.interval <= 60 && !is_workinghour(slotdate))) { // skip off-hours + candidatestart = candidateend = false; + candidatecount = 0; + continue; + } + } + + if (!candidatestart) + candidatestart = slot; + + // check freebusy data for all attendees + ts = date2timestring(slotdate, freebusy_data.interval > 60); + for (var i=0; i < event_attendees.length; i++) { + if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT' && (email = freebusy_ui.attendees[i].email) && freebusy_data[email] && freebusy_data[email][ts] > 1) { + candidatestart = candidateend = false; + break; + } + } + + // occupied slot + if (!candidatestart) { + slot += Math.max(0, intvlslots - candidatecount - 1) * sinterval * dir; + candidatecount = 0; + continue; + } + + // set candidate end to slot end time + candidatecount++; + if (dir < 0 && !candidateend) + candidateend = slotend; + + // if candidate is big enough, this is it! + if (candidatecount == numslots) { + if (dir > 0) { + event.start.setTime(candidatestart); + event.end.setTime(candidatestart + duration); + } + else { + event.end.setTime(candidateend); + event.start.setTime(candidateend - duration); + } + success = true; + break; + } + } + + // update event date/time display + if (success) { + update_freebusy_dates(event.start, event.end); + + // move freebusy grid if necessary + var offset = Math.ceil((event.start.getTime() - freebusy_ui.end.getTime()) / DAY_MS); + if (event.start.getTime() >= freebusy_ui.end.getTime()) + render_freebusy_grid(Math.max(1, offset)); + else if (event.end.getTime() <= freebusy_ui.start.getTime()) + render_freebusy_grid(Math.min(-1, offset)); + else + render_freebusy_overlay(); + + var now = new Date(); + $('#shedule-find-prev').button('option', 'disabled', (event.start.getTime() < now.getTime())); + } + else { + alert(rcmail.gettext('noslotfound','calendar')); + } + }; + + + // update event properties and attendees availability if event times have changed + var event_times_changed = function() + { + if (me.selected_event) { + var allday = $('#edit-allday').get(0); + me.selected_event.allDay = allday.checked; + me.selected_event.start = parse_datetime(allday.checked ? '12:00' : $('#edit-starttime').val(), $('#edit-startdate').val()); + me.selected_event.end = parse_datetime(allday.checked ? '13:00' : $('#edit-endtime').val(), $('#edit-enddate').val()); + if (event_attendees) + freebusy_ui.needsupdate = true; + $('#edit-startdate').data('duration', Math.round((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / 1000)); + } + }; + + // add the given list of participants + var add_attendees = function(names) + { + names = explode_quoted_string(names.replace(/,\s*$/, ''), ','); + + // parse name/email pairs + var item, email, name, success = false; + for (var i=0; i < names.length; i++) { + email = name = ''; + item = $.trim(names[i]); + + if (!item.length) { + continue; + } // address in brackets without name (do nothing) + else if (item.match(/^<[^@]+@[^>]+>$/)) { + email = item.replace(/[<>]/g, ''); + } // address without brackets and without name (add brackets) + else if (rcube_check_email(item)) { + email = item; + } // address with name + else if (item.match(/([^\s<@]+@[^>]+)>*$/)) { + email = RegExp.$1; + name = item.replace(email, '').replace(/^["\s<>]+/, '').replace(/["\s<>]+$/, ''); + } + + if (email) { + add_attendee({ email:email, name:name, role:'REQ-PARTICIPANT', status:'NEEDS-ACTION' }); + success = true; + } + else { + alert(rcmail.gettext('noemailwarning')); + } + } + + return success; + }; + + // add the given attendee to the list + var add_attendee = function(data, readonly) + { + // check for dupes... + var exists = false; + $.each(event_attendees, function(i, v){ exists |= (v.email == data.email); }); + if (exists) + return false; + + var dispname = Q(data.name || data.email); + if (data.email) + dispname = '' + dispname + ''; + + // role selection + var organizer = data.role == 'ORGANIZER'; + var opts = {}; + if (organizer) + opts.ORGANIZER = rcmail.gettext('calendar.roleorganizer'); + opts['REQ-PARTICIPANT'] = rcmail.gettext('calendar.rolerequired'); + opts['OPT-PARTICIPANT'] = rcmail.gettext('calendar.roleoptional'); + opts['CHAIR'] = rcmail.gettext('calendar.rolechair'); + + if (organizer && !readonly) + dispname = rcmail.env['identities-selector']; + + var select = ''; + + // availability + var avail = data.email ? 'loading' : 'unknown'; + + // delete icon + var icon = rcmail.env.deleteicon ? '' : rcmail.gettext('delete'); + var dellink = '' + icon + ''; + + var html = '' + select + '' + + '' + dispname + '' + + '' + + '' + Q(data.status) + '' + + '' + (organizer || readonly ? '' : dellink) + ''; + + var tr = $('') + .addClass(String(data.role).toLowerCase()) + .html(html) + .appendTo(attendees_list); + + tr.find('a.deletelink').click({ id:(data.email || data.name) }, function(e) { remove_attendee(this, e.data.id); return false; }); + tr.find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); + + // select organizer identity + if (data.identity_id) + $('#edit-identities-list').val(data.identity_id); + + // check free-busy status + if (avail == 'loading') { + check_freebusy_status(tr.find('img.availabilityicon'), data.email, me.selected_event); + } + + event_attendees.push(data); + }; + + // iterate over all attendees and update their free-busy status display + var update_freebusy_status = function(event) + { + var icons = attendees_list.find('img.availabilityicon'); + for (var i=0; i < event_attendees.length; i++) { + if (icons.get(i) && event_attendees[i].email) + check_freebusy_status(icons.get(i), event_attendees[i].email, event); + } + + freebusy_ui.needsupdate = false; + }; + + // load free-busy status from server and update icon accordingly + var check_freebusy_status = function(icon, email, event) + { + var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { freebusy:false }; + if (!calendar.freebusy) { + $(icon).removeClass().addClass('availabilityicon unknown'); + return; + } + + icon = $(icon).removeClass().addClass('availabilityicon loading'); + + $.ajax({ + type: 'GET', + dataType: 'html', + url: rcmail.url('freebusy-status'), + data: { email:email, start:date2servertime(clone_date(event.start, event.allDay?1:0)), end:date2servertime(clone_date(event.end, event.allDay?2:0)), _remote: 1 }, + success: function(status){ + icon.removeClass('loading').addClass(String(status).toLowerCase()); + }, + error: function(){ + icon.removeClass('loading').addClass('unknown'); + } + }); + }; + + // remove an attendee from the list + var remove_attendee = function(elem, id) + { + $(elem).closest('tr').remove(); + event_attendees = $.grep(event_attendees, function(data){ return (data.name != id && data.email != id) }); + }; + + // when the user accepts or declines an event invitation + var event_rsvp = function(response) + { + if (me.selected_event && me.selected_event.attendees && response) { + // update attendee status + for (var data, i=0; i < me.selected_event.attendees.length; i++) { + data = me.selected_event.attendees[i]; + if (settings.identity.emails.indexOf(';'+String(data.email).toLowerCase()) >= 0) + data.status = response.toUpperCase(); + } + event_show_dialog(me.selected_event); + + // submit status change to server + me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); + rcmail.http_post('event', { action:'rsvp', e:me.selected_event, status:response }); + } + } + + // post the given event data to server + var update_event = function(action, data) + { + me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); + rcmail.http_post('calendar/event', { action:action, e:data }); + + // render event temporarily into the calendar + if ((data.start && data.end) || data.id) { + var event = data.id ? $.extend(fc.fullCalendar('clientEvents', function(e){ return e.id == data.id; })[0], data) : data; + if (data.start) + event.start = data.start; + if (data.end) + event.end = data.end; + if (data.allday !== undefined) + event.allDay = data.allday; + event.editable = false; + event.temp = true; + event.className = 'fc-event-cal-'+data.calendar+' fc-event-temp'; + fc.fullCalendar(data.id ? 'updateEvent' : 'renderEvent', event); + } + }; + + // mouse-click handler to check if the show dialog is still open and prevent default action + var dialog_check = function(e) + { + var showd = $("#eventshow"); + if (showd.is(':visible') && !$(e.target).closest('.ui-dialog').length) { + showd.dialog('close'); + e.stopImmediatePropagation(); + ignore_click = true; + return false; + } + else if (ignore_click) { + window.setTimeout(function(){ ignore_click = false; }, 20); + return false; + } + return true; + }; + + // display confirm dialog when modifying/deleting an event + var update_event_confirm = function(action, event, data) + { + if (!data) data = event; + var decline = false, notify = false, html = '', cal = me.calendars[event.calendar]; + + // event has attendees, ask whether to notify them + if (has_attendees(event)) { + if (is_organizer(event)) { + notify = true; + html += '
' + + '
'; + } + else if (action == 'remove' && is_attendee(event)) { + decline = true; + html += '
' + + '
'; + } + else { + html += '
' + rcmail.gettext('localchangeswarning', 'calendar') + '
'; + } + } + + // recurring event: user needs to select the savemode + if (event.recurrence) { + html += '
' + + rcmail.gettext((action == 'remove' ? 'removerecurringeventwarning' : 'changerecurringeventwarning'), 'calendar') + '
' + + ''; + } + + // show dialog + if (html) { + var $dialog = $('
').html(html); + + $dialog.find('a.button').button().click(function(e){ + data._savemode = String(this.href).replace(/.+#/, ''); + if ($dialog.find('input.confirm-attendees-donotify').get(0)) + data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; + if (decline && $dialog.find('input.confirm-attendees-decline:checked')) + data.decline = 1; + update_event(action, data); + $dialog.dialog("destroy").hide(); + return false; + }); + + var buttons = [{ + text: rcmail.gettext('cancel', 'calendar'), + click: function() { + $(this).dialog("close"); + } + }]; + + if (!event.recurrence) { + buttons.push({ + text: rcmail.gettext((action == 'remove' ? 'remove' : 'save'), 'calendar'), + click: function() { + data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; + data.decline = decline && $dialog.find('input.confirm-attendees-decline:checked').length ? 1 : 0; + update_event(action, data); + $(this).dialog("close"); + } + }); + } + + $dialog.dialog({ + modal: true, + width: 460, + dialogClass: 'warning', + title: rcmail.gettext((action == 'remove' ? 'removeeventconfirm' : 'changeeventconfirm'), 'calendar'), + buttons: buttons, + close: function(){ + $dialog.dialog("destroy").hide(); + if (!rcmail.busy) + fc.fullCalendar('refetchEvents'); + } + }).addClass('event-update-confirm').show(); + + return false; + } + // show regular confirm box when deleting + else if (action == 'remove' && !cal.undelete) { + if (!confirm(rcmail.gettext('deleteventconfirm', 'calendar'))) + return false; + } + + // do update + update_event(action, data); + + return true; + }; + + var update_agenda_toolbar = function() + { + $('#agenda-listrange').val(fc.fullCalendar('option', 'listRange')); + $('#agenda-listsections').val(fc.fullCalendar('option', 'listSections')); + } + + /*** fullcalendar event handlers ***/ + + var fc_event_render = function(event, element, view) { + if (view.name != 'list' && view.name != 'table') { + var prefix = event.sensitivity && event.sensitivity != 'public' ? String(sensitivitylabels[event.sensitivity]).toUpperCase()+': ' : ''; + element.attr('title', prefix + event.title); + } + if (view.name != 'month') { + if (event.location) { + element.find('div.fc-event-title').after('
@ ' + Q(event.location) + '
'); + } + if (event.sensitivity && event.sensitivity != 'public') + element.find('div.fc-event-time').append(''); + if (event.recurrence) + element.find('div.fc-event-time').append(''); + if (event.alarms) + element.find('div.fc-event-time').append(''); + } + }; + + + /*** public methods ***/ + + /** + * Remove saving lock and free the UI for new input + */ + this.unlock_saving = function() + { + if (me.saving_lock) + rcmail.set_busy(false, null, me.saving_lock); + }; + + // opens calendar day-view in a popup + this.fisheye_view = function(date) + { + $('#fish-eye-view:ui-dialog').dialog('close'); + + // create list of active event sources + var src, cals = {}, sources = []; + for (var id in this.calendars) { + src = $.extend({}, this.calendars[id]); + src.editable = false; + src.url = null; + src.events = []; + + if (src.active) { + cals[id] = src; + sources.push(src); + } + } + + // copy events already loaded + var events = fc.fullCalendar('clientEvents'); + for (var event, i=0; i< events.length; i++) { + event = events[i]; + if (event.source && (src = cals[event.source.id])) { + src.events.push(event); + } + } + + var h = $(window).height() - 50; + var dialog = $('
') + .attr('id', 'fish-eye-view') + .dialog({ + modal: true, + width: 680, + height: h, + title: $.fullCalendar.formatDate(date, 'dddd ' + settings['date_long']), + close: function(){ + dialog.dialog("destroy"); + me.fisheye_date = null; + } + }) + .fullCalendar({ + header: { left: '', center: '', right: '' }, + height: h - 50, + defaultView: 'agendaDay', + date: date.getDate(), + month: date.getMonth(), + year: date.getFullYear(), + ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone + eventSources: sources, + monthNames : settings['months'], + monthNamesShort : settings['months_short'], + dayNames : settings['days'], + dayNamesShort : settings['days_short'], + firstDay : settings['first_day'], + firstHour : settings['first_hour'], + slotMinutes : 60/settings['timeslots'], + timeFormat: { '': settings['time_format'] }, + axisFormat : settings['time_format'], + columnFormat: { day: 'dddd ' + settings['date_short'] }, + titleFormat: { day: 'dddd ' + settings['date_long'] }, + allDayText: rcmail.gettext('all-day', 'calendar'), + currentTimeIndicator: settings.time_indicator, + eventRender: fc_event_render, + eventClick: function(event) { + event_show_dialog(event); + } + }); + + this.fisheye_date = date; + }; + + //public method to show the print dialog. + this.print_calendars = function(view) + { + if (!view) view = fc.fullCalendar('getView').name; + var date = fc.fullCalendar('getDate') || new Date(); + var range = fc.fullCalendar('option', 'listRange'); + var sections = fc.fullCalendar('option', 'listSections'); + rcmail.open_window(rcmail.url('print', { view: view, date: date2unixtime(date), range: range, sections: sections, search: this.search_query }), true, true); + }; + + // public method to bring up the new event dialog + this.add_event = function(templ) { + if (this.selected_calendar) { + var now = new Date(); + var date = fc.fullCalendar('getDate'); + if (typeof date != 'Date') + date = now; + date.setHours(now.getHours()+1); + date.setMinutes(0); + var end = new Date(date.getTime()); + end.setHours(date.getHours()+1); + event_edit_dialog('new', $.extend({ start:date, end:end, allDay:false, calendar:this.selected_calendar }, templ || {})); + } + }; + + // delete the given event after showing a confirmation dialog + this.delete_event = function(event) { + // show confirm dialog for recurring events, use jquery UI dialog + return update_event_confirm('remove', event, { id:event.id, calendar:event.calendar, attendees:event.attendees }); + }; + + // opens a jquery UI dialog with event properties (or empty for creating a new calendar) + this.calendar_edit_dialog = function(calendar) + { + // close show dialog first + var $dialog = $("#calendarform"); + if ($dialog.is(':ui-dialog')) + $dialog.dialog('close'); + + if (!calendar) + calendar = { name:'', color:'cc0000', editable:true, showalarms:true }; + + var form, name, color, alarms; + + $dialog.html(rcmail.get_label('loading')); + $.ajax({ + type: 'GET', + dataType: 'html', + url: rcmail.url('calendar'), + data: { action:(calendar.id ? 'form-edit' : 'form-new'), c:{ id:calendar.id } }, + success: function(data) { + $dialog.html(data); + // resize and reposition dialog window + form = $('#calendarpropform'); + me.dialog_resize('#calendarform', form.height(), form.width()); + name = $('#calendar-name').prop('disabled', !calendar.editable).val(calendar.editname || calendar.name); + color = $('#calendar-color').val(calendar.color).miniColors({ value: calendar.color, colorValues:rcmail.env.mscolors }); + alarms = $('#calendar-showalarms').prop('checked', calendar.showalarms).get(0); + name.select(); + } + }); + + // dialog buttons + var buttons = {}; + + buttons[rcmail.gettext('save', 'calendar')] = function() { + // form is not loaded + if (!form || !form.length) + return; + + // TODO: do some input validation + if (!name.val() || name.val().length < 2) { + alert(rcmail.gettext('invalidcalendarproperties', 'calendar')); + name.select(); + return; + } + + // post data to server + var data = form.serializeJSON(); + if (data.color) + data.color = data.color.replace(/^#/, ''); + if (calendar.id) + data.id = calendar.id; + if (alarms) + data.showalarms = alarms.checked ? 1 : 0; + + me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); + rcmail.http_post('calendar', { action:(calendar.id ? 'edit' : 'new'), c:data }); + $dialog.dialog("close"); + }; + + buttons[rcmail.gettext('cancel', 'calendar')] = function() { + $dialog.dialog("close"); + }; + + // open jquery UI dialog + $dialog.dialog({ + modal: true, + resizable: true, + closeOnEscape: false, + title: rcmail.gettext((calendar.id ? 'editcalendar' : 'createcalendar'), 'calendar'), + close: function() { + $dialog.html('').dialog("destroy").hide(); + }, + buttons: buttons, + minWidth: 400, + width: 420 + }).show(); + + }; + + this.calendar_remove = function(calendar) + { + if (confirm(rcmail.gettext('deletecalendarconfirm', 'calendar'))) { + rcmail.http_post('calendar', { action:'remove', c:{ id:calendar.id } }); + return true; + } + return false; + }; + + this.calendar_destroy_source = function(id) + { + if (this.calendars[id]) { + fc.fullCalendar('removeEventSource', this.calendars[id]); + $(rcmail.get_folder_li(id, 'rcmlical')).remove(); + $('#edit-calendar option[value="'+id+'"]').remove(); + delete this.calendars[id]; + } + }; + + // open a dialog to upload an .ics file with events to be imported + this.import_events = function(calendar) + { + // close show dialog first + var $dialog = $("#eventsimport"), + form = rcmail.gui_objects.importform; + + if ($dialog.is(':ui-dialog')) + $dialog.dialog('close'); + + $('#event-import-calendar').val(calendar.id); + + var buttons = {}; + buttons[rcmail.gettext('import', 'calendar')] = function() { + if (form && form.elements._data.value) { + rcmail.async_upload_form(form, 'import_events', function(e) { + rcmail.set_busy(false, null, me.saving_lock); + }); + + // display upload indicator + me.saving_lock = rcmail.set_busy(true, 'uploading'); + } + }; + + buttons[rcmail.gettext('cancel', 'calendar')] = function() { + $dialog.dialog("close"); + }; + + // open jquery UI dialog + $dialog.dialog({ + modal: true, + resizable: false, + closeOnEscape: false, + title: rcmail.gettext('importevents', 'calendar'), + close: function() { + $dialog.dialog("destroy").hide(); + }, + buttons: buttons, + width: 520 + }).show(); + + }; + + // callback from server if import succeeded + this.import_success = function(p) + { + $("#eventsimport:ui-dialog").dialog('close'); + rcmail.set_busy(false, null, me.saving_lock); + rcmail.gui_objects.importform.reset(); + + if (p.refetch) + this.refresh(p); + }; + + // show URL of the given calendar in a dialog box + this.showurl = function(calendar) + { + var $dialog = $('#calendarurlbox'); + + if ($dialog.is(':ui-dialog')) + $dialog.dialog('close'); + + if (calendar.feedurl) { + $dialog.dialog({ + resizable: true, + closeOnEscape: true, + title: rcmail.gettext('showurl', 'calendar'), + close: function() { + $dialog.dialog("destroy").hide(); + }, + width: 520 + }).show(); + + $('#calfeedurl').val(calendar.feedurl).select(); + } + }; + + // refresh the calendar view after saving event data + this.refresh = function(p) + { + var source = me.calendars[p.source]; + + if (source && (p.refetch || (p.update && !source.active))) { + // activate event source if new event was added to an invisible calendar + if (!source.active) { + source.active = true; + fc.fullCalendar('addEventSource', source); + $('#' + rcmail.get_folder_li(source.id, 'rcmlical').id + ' input').prop('checked', true); + } + else + fc.fullCalendar('refetchEvents', source); + } + // add/update single event object + else if (source && p.update) { + var event = p.update; + event.temp = false; + event.editable = source.editable; + var existing = fc.fullCalendar('clientEvents', event._id); + if (existing.length) { + $.extend(existing[0], event); + fc.fullCalendar('updateEvent', existing[0]); + } + else { + event.source = source; // link with source + fc.fullCalendar('renderEvent', event); + } + // refresh fish-eye view + if (me.fisheye_date) + me.fisheye_view(me.fisheye_date); + } + + // remove temp events + fc.fullCalendar('removeEvents', function(e){ return e.temp; }); + }; + + + /*** event searching ***/ + + // execute search + this.quicksearch = function() + { + if (rcmail.gui_objects.qsearchbox) { + var q = rcmail.gui_objects.qsearchbox.value; + if (q != '') { + var id = 'search-'+q; + var sources = []; + + if (this._search_message) + rcmail.hide_message(this._search_message); + + for (var sid in this.calendars) { + if (this.calendars[sid]) { + this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, '') + '&q='+escape(q); + sources.push(sid); + } + } + id += '@'+sources.join(','); + + // ignore if query didn't change + if (this.search_request == id) { + return; + } + // remember current view + else if (!this.search_request) { + this.default_view = fc.fullCalendar('getView').name; + } + + this.search_request = id; + this.search_query = q; + + // change to list view + fc.fullCalendar('option', 'listSections', 'month') + .fullCalendar('option', 'listRange', Math.max(60, settings['agenda_range'])) + .fullCalendar('changeView', 'table'); + + update_agenda_toolbar(); + + // refetch events with new url (if not already triggered by changeView) + if (!this.is_loading) + fc.fullCalendar('refetchEvents'); + } + else // empty search input equals reset + this.reset_quicksearch(); + } + }; + + // reset search and get back to normal event listing + this.reset_quicksearch = function() + { + $(rcmail.gui_objects.qsearchbox).val(''); + + if (this._search_message) + rcmail.hide_message(this._search_message); + + if (this.search_request) { + // hide bottom links of agenda view + fc.find('.fc-list-content > .fc-listappend').hide(); + + // restore original event sources and view mode from fullcalendar + fc.fullCalendar('option', 'listSections', settings['agenda_sections']) + .fullCalendar('option', 'listRange', settings['agenda_range']); + + update_agenda_toolbar(); + + for (var sid in this.calendars) { + if (this.calendars[sid]) + this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, ''); + } + if (this.default_view) + fc.fullCalendar('changeView', this.default_view); + + if (!this.is_loading) + fc.fullCalendar('refetchEvents'); + + this.search_request = this.search_query = null; + } + }; + + // callback if all sources have been fetched from server + this.events_loaded = function(count) + { + var addlinks, append = ''; + + // enhance list view when searching + if (this.search_request) { + if (!count) { + this._search_message = rcmail.display_message(rcmail.gettext('searchnoresults', 'calendar'), 'notice'); + append = '
' + rcmail.gettext('searchnoresults', 'calendar') + '
'; + } + append += ''; + addlinks = true; + } + + if (fc.fullCalendar('getView').name == 'table') { + var container = fc.find('.fc-list-content > .fc-listappend'); + if (append) { + if (!container.length) + container = $('
').appendTo(fc.find('.fc-list-content')); + container.html(append).show(); + } + else if (container.length) + container.hide(); + + // add links to adjust search date range + if (addlinks) { + var lc = container.find('.fc-bottomlinks'); + $('').attr('href', '#').html(rcmail.gettext('searchearlierdates', 'calendar')).appendTo(lc).click(function(){ + fc.fullCalendar('incrementDate', 0, -1, 0); + }); + lc.append(" "); + $('').attr('href', '#').html(rcmail.gettext('searchlaterdates', 'calendar')).appendTo(lc).click(function(){ + var range = fc.fullCalendar('option', 'listRange'); + if (range < 90) { + fc.fullCalendar('option', 'listRange', fc.fullCalendar('option', 'listRange') + 30).fullCalendar('render'); + update_agenda_toolbar(); + } + else + fc.fullCalendar('incrementDate', 0, 1, 0); + }); + } + } + + if (this.fisheye_date) + this.fisheye_view(this.fisheye_date); + }; + + // resize and reposition (center) the dialog window + this.dialog_resize = function(id, height, width) + { + var win = $(window), w = win.width(), h = win.height(); + $(id).dialog('option', { height: Math.min(h-20, height+130), width: Math.min(w-20, width+50) }) + .dialog('option', 'position', ['center', 'center']); // only works in a separate call (!?) + }; + + // adjust calendar view size + this.view_resize = function() + { + var footer = fc.fullCalendar('getView').name == 'table' ? $('#agendaoptions').outerHeight() : 0; + fc.fullCalendar('option', 'height', $('#calendar').height() - footer); + }; + + + /*** startup code ***/ + + // create list of event sources AKA calendars + this.calendars = {}; + var li, cal, active, event_sources = []; + for (var id in rcmail.env.calendars) { + cal = rcmail.env.calendars[id]; + this.calendars[id] = $.extend({ + url: "./?_task=calendar&_action=load_events&source="+escape(id), + editable: !cal.readonly, + className: 'fc-event-cal-'+id, + id: id + }, cal); + + this.calendars[id].color = settings.event_coloring % 2 ? '' : '#' + cal.color; + + if ((active = cal.active || false)) { + event_sources.push(this.calendars[id]); + } + + // init event handler on calendar list checkbox + if ((li = rcmail.get_folder_li(id, 'rcmlical'))) { + $('#'+li.id+' input').click(function(e){ + var id = $(this).data('id'); + if (me.calendars[id]) { // add or remove event source on click + var action; + if (this.checked) { + action = 'addEventSource'; + me.calendars[id].active = true; + } + else { + action = 'removeEventSource'; + me.calendars[id].active = false; + } + + // add/remove event source + fc.fullCalendar(action, me.calendars[id]); + rcmail.http_post('calendar', { action:'subscribe', c:{ id:id, active:me.calendars[id].active?1:0 } }); + } + }).data('id', id).get(0).checked = active; + + $(li).click(function(e){ + var id = $(this).data('id'); + rcmail.select_folder(id, 'rcmlical'); + rcmail.enable_command('calendar-edit', true); + rcmail.enable_command('calendar-remove', 'events-import', 'calendar-showurl', true); + me.selected_calendar = id; + }) + .dblclick(function(){ me.calendar_edit_dialog(me.calendars[me.selected_calendar]); }) + .data('id', id); + } + + if (!cal.readonly && !this.selected_calendar) { + this.selected_calendar = id; + rcmail.enable_command('addevent', true); + } + } + + // select default calendar + if (settings.default_calendar && this.calendars[settings.default_calendar] && !this.calendars[settings.default_calendar].readonly) + this.selected_calendar = settings.default_calendar; + + var viewdate = new Date(); + if (rcmail.env.date) + viewdate.setTime(fromunixtime(rcmail.env.date)); + + // initalize the fullCalendar plugin + var fc = $('#calendar').fullCalendar({ + header: { + right: 'prev,next today', + center: 'title', + left: 'agendaDay,agendaWeek,month,table' + }, + aspectRatio: 1, + date: viewdate.getDate(), + month: viewdate.getMonth(), + year: viewdate.getFullYear(), + ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone + height: $('#calendar').height(), + eventSources: event_sources, + monthNames : settings['months'], + monthNamesShort : settings['months_short'], + dayNames : settings['days'], + dayNamesShort : settings['days_short'], + firstDay : settings['first_day'], + firstHour : settings['first_hour'], + slotMinutes : 60/settings['timeslots'], + timeFormat: { + '': settings['time_format'], + agenda: settings['time_format'] + '{ - ' + settings['time_format'] + '}', + list: settings['time_format'] + '{ - ' + settings['time_format'] + '}', + table: settings['time_format'] + '{ - ' + settings['time_format'] + '}' + }, + axisFormat : settings['time_format'], + columnFormat: { + month: 'ddd', // Mon + week: 'ddd ' + settings['date_short'], // Mon 9/7 + day: 'dddd ' + settings['date_short'], // Monday 9/7 + table: settings['date_agenda'] + }, + titleFormat: { + month: 'MMMM yyyy', + week: settings['dates_long'], + day: 'dddd ' + settings['date_long'], + table: settings['dates_long'] + }, + listPage: 1, // advance one day in agenda view + listRange: settings['agenda_range'], + listSections: settings['agenda_sections'], + tableCols: ['handle', 'date', 'time', 'title', 'location'], + defaultView: rcmail.env.view || settings['default_view'], + allDayText: rcmail.gettext('all-day', 'calendar'), + buttonText: { + prev: (bw.ie6 ? ' << ' : ' ◄ '), + next: (bw.ie6 ? ' >> ' : ' ► '), + today: settings['today'], + day: rcmail.gettext('day', 'calendar'), + week: rcmail.gettext('week', 'calendar'), + month: rcmail.gettext('month', 'calendar'), + table: rcmail.gettext('agenda', 'calendar') + }, + listTexts: { + until: rcmail.gettext('until', 'calendar'), + past: rcmail.gettext('pastevents', 'calendar'), + today: rcmail.gettext('today', 'calendar'), + tomorrow: rcmail.gettext('tomorrow', 'calendar'), + thisWeek: rcmail.gettext('thisweek', 'calendar'), + nextWeek: rcmail.gettext('nextweek', 'calendar'), + thisMonth: rcmail.gettext('thismonth', 'calendar'), + nextMonth: rcmail.gettext('nextmonth', 'calendar'), + future: rcmail.gettext('futureevents', 'calendar'), + week: rcmail.gettext('weekofyear', 'calendar') + }, + selectable: true, + selectHelper: false, + currentTimeIndicator: settings.time_indicator, + loading: function(isLoading) { + me.is_loading = isLoading; + this._rc_loading = rcmail.set_busy(isLoading, 'loading', this._rc_loading); + // trigger callback + if (!isLoading) + me.events_loaded($(this).fullCalendar('clientEvents').length); + }, + // event rendering + eventRender: fc_event_render, + // render element indicating more (invisible) events + overflowRender: function(data, element) { + element.html(rcmail.gettext('andnmore', 'calendar').replace('$nr', data.count)) + .click(function(e){ me.fisheye_view(data.date); }); + }, + // callback for date range selection + select: function(start, end, allDay, e, view) { + var range_select = (!allDay || start.getDate() != end.getDate()) + if (dialog_check(e) && range_select) + event_edit_dialog('new', { start:start, end:end, allDay:allDay, calendar:me.selected_calendar }); + if (range_select || ignore_click) + view.calendar.unselect(); + }, + // callback for clicks in all-day box + dayClick: function(date, allDay, e, view) { + var now = new Date().getTime(); + if (now - day_clicked_ts < 400 && day_clicked == date.getTime()) { // emulate double-click on day + var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); + return event_edit_dialog('new', { start:date, end:enddate, allDay:allDay, calendar:me.selected_calendar }); + } + + if (!ignore_click) { + view.calendar.gotoDate(date); + if (day_clicked && new Date(day_clicked).getMonth() != date.getMonth()) + view.calendar.select(date, date, allDay); + } + day_clicked = date.getTime(); + day_clicked_ts = now; + }, + // callback when a specific event is clicked + eventClick: function(event) { + if (!event.temp) + event_show_dialog(event); + }, + // callback when an event was dragged and finally dropped + eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) { + if (event.end == null || event.end.getTime() < event.start.getTime()) { + event.end = new Date(event.start.getTime() + (allDay ? DAY_MS : HOUR_MS)); + } + // moved to all-day section: set times to 12:00 - 13:00 + if (allDay && !event.allDay) { + event.start.setHours(12); + event.start.setMinutes(0); + event.start.setSeconds(0); + event.end.setHours(13); + event.end.setMinutes(0); + event.end.setSeconds(0); + } + // moved from all-day section: set times to working hours + else if (event.allDay && !allDay) { + var newstart = event.start.getTime(); + revertFunc(); // revert to get original duration + var numdays = Math.max(1, Math.round((event.end.getTime() - event.start.getTime()) / DAY_MS)) - 1; + event.start = new Date(newstart); + event.end = new Date(newstart + numdays * DAY_MS); + event.end.setHours(settings['work_end'] || 18); + event.end.setMinutes(0); + + if (event.end.getTime() < event.start.getTime()) + event.end = new Date(newstart + HOUR_MS); + } + + // send move request to server + var data = { + id: event.id, + calendar: event.calendar, + start: date2servertime(event.start), + end: date2servertime(event.end), + allday: allDay?1:0 + }; + update_event_confirm('move', event, data); + }, + // callback for event resizing + eventResize: function(event, delta) { + // sanitize event dates + if (event.allDay) + event.start.setHours(12); + if (!event.end || event.end.getTime() < event.start.getTime()) + event.end = new Date(event.start.getTime() + HOUR_MS); + + // send resize request to server + var data = { + id: event.id, + calendar: event.calendar, + start: date2servertime(event.start), + end: date2servertime(event.end) + }; + update_event_confirm('resize', event, data); + }, + viewDisplay: function(view) { + $('#agendaoptions')[view.name == 'table' ? 'show' : 'hide'](); + if (minical) { + window.setTimeout(function(){ minical.datepicker('setDate', fc.fullCalendar('getDate')); }, exec_deferred); + if (view.name != current_view) + me.view_resize(); + current_view = view.name; + } + }, + viewRender: function(view) { + if (fc && view.name == 'month') + fc.fullCalendar('option', 'maxHeight', Math.floor((view.element.parent().height()-18) / 6) - 35); + } + }); + + // format time string + var formattime = function(hour, minutes, start) { + var time, diff, unit, duration = '', d = new Date(); + d.setHours(hour); + d.setMinutes(minutes); + time = $.fullCalendar.formatDate(d, settings['time_format']); + if (start) { + diff = Math.floor((d.getTime() - start.getTime()) / 60000); + if (diff > 0) { + unit = 'm'; + if (diff >= 60) { + unit = 'h'; + diff = Math.round(diff / 3) / 20; + } + duration = ' (' + diff + unit + ')'; + } + } + return [time, duration]; + }; + + var autocomplete_times = function(p, callback) { + /* Time completions */ + var result = []; + var now = new Date(); + var st, start = (String(this.element.attr('id')).indexOf('endtime') > 0 + && (st = $('#edit-starttime').val()) + && $('#edit-startdate').val() == $('#edit-enddate').val()) + ? parse_datetime(st, '') : null; + var full = p.term - 1 > 0 || p.term.length > 1; + var hours = start ? start.getHours() : + (full ? parse_datetime(p.term, '') : now).getHours(); + var step = 15; + var minutes = hours * 60 + (full ? 0 : now.getMinutes()); + var min = Math.ceil(minutes / step) * step % 60; + var hour = Math.floor(Math.ceil(minutes / step) * step / 60); + // list hours from 0:00 till now + for (var h = start ? start.getHours() : 0; h < hours; h++) + result.push(formattime(h, 0, start)); + // list 15min steps for the next two hours + for (; h < hour + 2 && h < 24; h++) { + while (min < 60) { + result.push(formattime(h, min, start)); + min += step; + } + min = 0; + } + // list the remaining hours till 23:00 + while (h < 24) + result.push(formattime((h++), 0, start)); + + return callback(result); + }; + + var autocomplete_open = function(event, ui) { + // scroll to current time + var $this = $(this); + var widget = $this.autocomplete('widget'); + var menu = $this.data('autocomplete').menu; + var amregex = /^(.+)(a[.m]*)/i; + var pmregex = /^(.+)(a[.m]*)/i; + var val = $(this).val().replace(amregex, '0:$1').replace(pmregex, '1:$1'); + var li, html; + widget.css('width', '10em'); + widget.children().each(function(){ + li = $(this); + html = li.children().first().html().replace(/\s+\(.+\)$/, '').replace(amregex, '0:$1').replace(pmregex, '1:$1'); + if (html.indexOf(val) == 0) + menu._scrollIntoView(li); + }); + }; + + // if start date is changed, shift end date according to initial duration + var shift_enddate = function(dateText) { + var newstart = parse_datetime('0', dateText); + var newend = new Date(newstart.getTime() + $('#edit-startdate').data('duration') * 1000); + $('#edit-enddate').val($.fullCalendar.formatDate(newend, me.settings['date_format'])); + event_times_changed(); + }; + + // Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. + // Uses the default $.datepicker.iso8601Week() function but takes firstDay setting into account. + // This is a temporary fix until http://bugs.jqueryui.com/ticket/8420 is resolved. + var iso8601Week = datepicker_settings.calculateWeek = function(date) { + var mondayOffset = Math.abs(1 - datepicker_settings.firstDay); + return $.datepicker.iso8601Week(new Date(date.getTime() + mondayOffset * 86400000)); + }; + + var minical; + var init_calendar_ui = function() + { + // initialize small calendar widget using jQuery UI datepicker + minical = $('#datepicker').datepicker($.extend(datepicker_settings, { + inline: true, + showWeek: true, + changeMonth: false, // maybe enable? + changeYear: false, // maybe enable? + onSelect: function(dateText, inst) { + ignore_click = true; + var d = minical.datepicker('getDate'); //parse_datetime('0:0', dateText); + fc.fullCalendar('gotoDate', d).fullCalendar('select', d, d, true); + }, + onChangeMonthYear: function(year, month, inst) { + minical.data('year', year).data('month', month); + }, + beforeShowDay: function(date) { + var view = fc.fullCalendar('getView'); + var active = view.visStart && date.getTime() >= view.visStart.getTime() && date.getTime() < view.visEnd.getTime(); + return [ true, (active ? 'ui-datepicker-activerange ui-datepicker-active-' + view.name : ''), '']; + } + })) // set event handler for clicks on calendar week cell of the datepicker widget + .click(function(e) { + var cell = $(e.target); + if (e.target.tagName == 'TD' && cell.hasClass('ui-datepicker-week-col')) { + var base_date = minical.datepicker('getDate'); + if (minical.data('month')) + base_date.setMonth(minical.data('month')-1); + if (minical.data('year')) + base_date.setYear(minical.data('year')); + base_date.setHours(12); + base_date.setDate(base_date.getDate() - ((base_date.getDay() + 6) % 7) + datepicker_settings.firstDay); + var day_off = base_date.getDay() - datepicker_settings.firstDay; + var base_kw = iso8601Week(base_date); + var target_kw = parseInt(cell.html()); + var diff = (target_kw - base_kw) * 7 * DAY_MS; + // select monday of the chosen calendar week + var date = new Date(base_date.getTime() - day_off * DAY_MS + diff); + fc.fullCalendar('gotoDate', date).fullCalendar('setDate', date).fullCalendar('changeView', 'agendaWeek'); + minical.datepicker('setDate', date); + } + }); + + // init event dialog + $('#eventtabs').tabs({ + show: function(event, ui) { + if (ui.panel.id == 'event-tab-3') { + $('#edit-attendee-name').select(); + // update free-busy status if needed + if (freebusy_ui.needsupdate && me.selected_event) + update_freebusy_status(me.selected_event); + // add current user as organizer if non added yet + if (!event_attendees.length) { + add_attendee($.extend({ role:'ORGANIZER' }, settings.identity)); + $('#edit-attendees-form .attendees-invitebox').show(); + } + } + } + }); + $('#edit-enddate').datepicker(datepicker_settings); + $('#edit-startdate').datepicker(datepicker_settings).datepicker('option', 'onSelect', shift_enddate).change(function(){ shift_enddate(this.value); }); + $('#edit-enddate').datepicker('option', 'onSelect', event_times_changed).change(event_times_changed); + $('#edit-allday').click(function(){ $('#edit-starttime, #edit-endtime')[(this.checked?'hide':'show')](); event_times_changed(); }); + + // configure drop-down menu on time input fields based on jquery UI autocomplete + $('#edit-starttime, #edit-endtime, #eventedit input.edit-alarm-time') + .attr('autocomplete', "off") + .autocomplete({ + delay: 100, + minLength: 1, + source: autocomplete_times, + open: autocomplete_open, + change: event_times_changed, + select: function(event, ui) { + $(this).val(ui.item[0]); + return false; + } + }) + .click(function() { // show drop-down upon clicks + $(this).autocomplete('search', $(this).val() ? $(this).val().replace(/\D.*/, "") : " "); + }).each(function(){ + $(this).data('autocomplete')._renderItem = function(ul, item) { + return $('
  • ') + .data('item.autocomplete', item) + .append('' + item[0] + item[1] + '') + .appendTo(ul); + }; + }); + + // register events on alarm fields + init_alarms_edit('#eventedit'); + + // toggle recurrence frequency forms + $('#edit-recurrence-frequency').change(function(e){ + var freq = $(this).val().toLowerCase(); + $('.recurrence-form').hide(); + if (freq) + $('#recurrence-form-'+freq+', #recurrence-form-until').show(); + }); + $('#edit-recurrence-enddate').datepicker(datepicker_settings).click(function(){ $("#edit-recurrence-repeat-until").prop('checked', true) }); + $('#edit-recurrence-repeat-times').change(function(e){ $('#edit-recurrence-repeat-count').prop('checked', true); }); + + // init attendees autocompletion + var ac_props; + // parallel autocompletion + if (rcmail.env.autocomplete_threads > 0) { + ac_props = { + threads: rcmail.env.autocomplete_threads, + sources: rcmail.env.autocomplete_sources + }; + } + rcmail.init_address_input_events($('#edit-attendee-name'), ac_props); + rcmail.addEventListener('autocomplete_insert', function(e){ $('#edit-attendee-add').click(); }); + + $('#edit-attendee-add').click(function(){ + var input = $('#edit-attendee-name'); + rcmail.ksearch_blur(); + if (add_attendees(input.val())) { + input.val(''); + } + }); + + // keep these two checkboxes in sync + $('#edit-attendees-donotify, #edit-attendees-invite').click(function(){ + $('#edit-attendees-donotify, #edit-attendees-invite').prop('checked', this.checked); + }); + + $('#edit-attendee-schedule').click(function(){ + event_freebusy_dialog(); + }); + + $('#shedule-freebusy-prev').html(bw.ie6 ? '<<' : '◄').button().click(function(){ render_freebusy_grid(-1); }); + $('#shedule-freebusy-next').html(bw.ie6 ? '>>' : '►').button().click(function(){ render_freebusy_grid(1); }).parent().buttonset(); + + $('#shedule-find-prev').button().click(function(){ freebusy_find_slot(-1); }); + $('#shedule-find-next').button().click(function(){ freebusy_find_slot(1); }); + + $('#schedule-freebusy-workinghours').click(function(){ + freebusy_ui.workinhoursonly = this.checked; + $('#workinghourscss').remove(); + if (this.checked) + $('').appendTo('head'); + }); + + $('#event-rsvp input.button').click(function(){ + event_rsvp($(this).attr('rel')) + }); + + $('#agenda-listrange').change(function(e){ + settings['agenda_range'] = parseInt($(this).val()); + fc.fullCalendar('option', 'listRange', settings['agenda_range']).fullCalendar('render'); + // TODO: save new settings in prefs + }).val(settings['agenda_range']); + + $('#agenda-listsections').change(function(e){ + settings['agenda_sections'] = $(this).val(); + fc.fullCalendar('option', 'listSections', settings['agenda_sections']).fullCalendar('render'); + // TODO: save new settings in prefs + }).val(fc.fullCalendar('option', 'listSections')); + + // hide event dialog when clicking somewhere into document + $(document).bind('mousedown', dialog_check); + + rcmail.set_busy(false, 'loading', ui_loading); + } + + // initialize more UI elements (deferred) + window.setTimeout(init_calendar_ui, exec_deferred); + + // add proprietary css styles if not IE + if (!bw.ie) + $('div.fc-content').addClass('rcube-fc-content'); + + // IE supresses 2nd click event when double-clicking + if (bw.ie && bw.vendver < 9) { + $('div.fc-content').bind('dblclick', function(e){ + if (!$(this).hasClass('fc-widget-header') && fc.fullCalendar('getView').name != 'table') { + var date = fc.fullCalendar('getDate'); + var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); + event_edit_dialog('new', { start:date, end:enddate, allDay:true, calendar:me.selected_calendar }); + } + }); + } +} // end rcube_calendar class + + +/* calendar plugin initialization */ +window.rcmail && rcmail.addEventListener('init', function(evt) { + // configure toolbar buttons + rcmail.register_command('addevent', function(){ cal.add_event(); }, true); + rcmail.register_command('print', function(){ cal.print_calendars(); }, true); + + // configure list operations + rcmail.register_command('calendar-create', function(){ cal.calendar_edit_dialog(null); }, true); + rcmail.register_command('calendar-edit', function(){ cal.calendar_edit_dialog(cal.calendars[cal.selected_calendar]); }, false); + rcmail.register_command('calendar-remove', function(){ cal.calendar_remove(cal.calendars[cal.selected_calendar]); }, false); + rcmail.register_command('events-import', function(){ cal.import_events(cal.calendars[cal.selected_calendar]); }, false); + rcmail.register_command('calendar-showurl', function(){ cal.showurl(cal.calendars[cal.selected_calendar]); }, false); + + // search and export events + rcmail.register_command('export', function(){ rcmail.goto_url('export_events', { source:cal.selected_calendar }); }, true); + rcmail.register_command('search', function(){ cal.quicksearch(); }, true); + rcmail.register_command('reset-search', function(){ cal.reset_quicksearch(); }, true); + + // register callback commands + rcmail.addEventListener('plugin.destroy_source', function(p){ cal.calendar_destroy_source(p.id); }); + rcmail.addEventListener('plugin.unlock_saving', function(p){ cal.unlock_saving(); }); + rcmail.addEventListener('plugin.refresh_calendar', function(p){ cal.refresh(p); }); + rcmail.addEventListener('plugin.import_success', function(p){ cal.import_success(p); }); + + // let's go + var cal = new rcube_calendar_ui($.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings)); + + $(window).resize(function(e) { + // check target due to bugs in jquery + // http://bugs.jqueryui.com/ticket/7514 + // http://bugs.jquery.com/ticket/9841 + if (e.target == window) { + cal.view_resize(); + } + }).resize(); + + // show calendars list when ready + $('#calendars').css('visibility', 'inherit'); + + // show toolbar + $('#toolbar').show(); + +}); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..25c8011 --- /dev/null +++ b/composer.json @@ -0,0 +1,31 @@ +{ + "name": "kolab/calendar", + "type": "roundcube-plugin", + "description": "Calendar module for Roundcube", + "keywords": ["apps","calendar"], + "homepage": "http://git.kolab.org/roundcubemail-plugins-kolab/", + "license": "GPL-3.0+", + "authors": [ + { + "name": "Thomas Bruederli", + "email": "bruederli@kolabsys.com", + "role": "Developer" + } + ], + "repositories": [ + { + "type": "composer", + "url": "http://33.33.108.2" + } + ], + "require": { + "php": ">=5.3.0", + "roundcube/plugin-installer": "dev-master" + }, + "extra": { + "roundcube": { + "min-version": "0.9.2", + "sql-dir": "drivers/database/SQL" + } + } +} \ No newline at end of file diff --git a/config.inc.php.dist b/config.inc.php.dist new file mode 100644 index 0000000..a8d5da8 --- /dev/null +++ b/config.inc.php.dist @@ -0,0 +1,123 @@ +. | + | | + +-------------------------------------------------------------------------+ + | Author: Lazlo Westerhof | + | Thomas Bruederli | + +-------------------------------------------------------------------------+ +*/ + +// backend type (database, google, kolab) +$rcmail_config['calendar_driver'] = "database"; + +// default calendar view (agendaDay, agendaWeek, month) +$rcmail_config['calendar_default_view'] = "agendaWeek"; + +// mapping of Roundcube date formats to calendar formats (long/short/agenda) +// should be in sync with 'date_formats' in main config +$rcmail_config['calendar_date_format_sets'] = array( + 'yyyy-MM-dd' => array('MMM d yyyy', 'M-d', 'ddd MM-dd'), + 'dd-MM-yyyy' => array('d MMM yyyy', 'd-M', 'ddd dd-MM'), + 'yyyy/MM/dd' => array('MMM d yyyy', 'M/d', 'ddd MM/dd'), + 'MM/dd/yyyy' => array('MMM d yyyy', 'M/d', 'ddd MM/dd'), + 'dd/MM/yyyy' => array('d MMM yyyy', 'd/M', 'ddd dd/MM'), + 'dd.MM.yyyy' => array('dd. MMM yyyy', 'd.M', 'ddd dd.MM.'), + 'd.M.yyyy' => array('d. MMM yyyy', 'd.M', 'ddd d.MM.'), +); + +// general date format (only set if different from default date format and not user configurable) +// $rcmail_config['calendar_date_format'] = "yyyy-MM-dd"; + +// time format (only set if different from default date format) +// $rcmail_config['calendar_time_format'] = "HH:mm"; + +// short date format (used for column titles) +// $rcmail_config['calendar_date_short'] = 'M-d'; + +// long date format (used for calendar title) +// $rcmail_config['calendar_date_long'] = 'MMM d yyyy'; + +// date format used for agenda view +// $rcmail_config['calendar_date_agenda'] = 'ddd MM-dd'; + +// timeslots per hour (1, 2, 3, 4, 6) +$rcmail_config['calendar_timeslots'] = 2; + +// show this number of days in agenda view +$rcmail_config['calendar_agenda_range'] = 60; + +// first day of the week (0-6) +$rcmail_config['calendar_first_day'] = 1; + +// first hour of the calendar (0-23) +$rcmail_config['calendar_first_hour'] = 6; + +// working hours begin +$rcmail_config['calendar_work_start'] = 6; + +// working hours end +$rcmail_config['calendar_work_end'] = 18; + +// show line at current time of the day +$rcmail_config['calendar_time_indicator'] = true; + +// default alarm settings for new events. +// this is only a preset when a new event dialog opens +// possible values are , DISPLAY, EMAIL +$rcmail_config['calendar_default_alarm_type'] = ''; + +// default alarm offset for new events. +// use ical-style offset values like "-1H" (one hour before) or "+30M" (30 minutes after) +$rcmail_config['calendar_default_alarm_offset'] = '-15M'; + +// how to colorize events: +// 0: according to calendar color +// 1: according to category color +// 2: calendar for outer, category for inner color +// 3: category for outer, calendar for inner color +$rcmail_config['calendar_event_coloring'] = 0; + +// event categories +$rcmail_config['calendar_categories'] = array( + 'Personal' => 'c0c0c0', + 'Work' => 'ff0000', + 'Family' => '00ff00', + 'Holiday' => 'ff6600', +); + +// enable users to invite/edit attendees for shared events organized by others +$rcmail_config['calendar_allow_invite_shared'] = false; + +// enable asynchronous free-busy triggering after data changed +$rcmail_config['calendar_freebusy_trigger'] = false; + +// SMTP username used to send (anonymous) itip messages +$rcmail_config['calendar_itip_smtp_server'] = null; + +// SMTP username used to send (anonymous) itip messages +$rcmail_config['calendar_itip_smtp_user'] = 'smtpauth'; + +// SMTP password used to send (anonymous) itip messages +$rcmail_config['calendar_itip_smtp_pass'] = '123456'; + + +?> \ No newline at end of file diff --git a/drivers/calendar_driver.php b/drivers/calendar_driver.php new file mode 100644 index 0000000..52de901 --- /dev/null +++ b/drivers/calendar_driver.php @@ -0,0 +1,402 @@ + + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +/** + * Struct of an internal event object how it is passed from/to the driver classes: + * + * $event = array( + * 'id' => 'Event ID used for editing', + * 'uid' => 'Unique identifier of this event', + * 'calendar' => 'Calendar identifier to add event to or where the event is stored', + * 'start' => DateTime, // Event start date/time as DateTime object + * 'end' => DateTime, // Event end date/time as DateTime object + * 'allday' => true|false, // Boolean flag if this is an all-day event + * 'changed' => DateTime, // Last modification date of event + * 'title' => 'Event title/summary', + * 'location' => 'Location string', + * 'description' => 'Event description', + * 'url' => 'URL to more information', + * 'recurrence' => array( // Recurrence definition according to iCalendar (RFC 2445) specification as list of key-value pairs + * 'FREQ' => 'DAILY|WEEKLY|MONTHLY|YEARLY', + * 'INTERVAL' => 1...n, + * 'UNTIL' => DateTime, + * 'COUNT' => 1..n, // number of times + * // + more properties (see http://www.kanzaki.com/docs/ical/recur.html) + * 'EXDATE' => array(), // list of DateTime objects of exception Dates/Times + * 'EXCEPTIONS' => array(), list of event objects which denote exceptions in the recurrence chain + * ), + * 'recurrence_id' => 'ID of the recurrence group', // usually the ID of the starting event + * 'categories' => 'Event category', + * 'free_busy' => 'free|busy|outofoffice|tentative', // Show time as + * 'priority' => 0-9, // Event priority (0=undefined, 1=highest, 9=lowest) + * 'sensitivity' => 'public|private|confidential', // Event sensitivity + * 'alarms' => '-15M:DISPLAY', // Reminder settings inspired by valarm definition (e.g. display alert 15 minutes before event) + * 'attachments' => array( // List of attachments + * 'name' => 'File name', + * 'mimetype' => 'Content type', + * 'size' => 1..n, // in bytes + * 'id' => 'Attachment identifier' + * ), + * 'deleted_attachments' => array(), // array of attachment identifiers to delete when event is updated + * 'attendees' => array( // List of event participants + * 'name' => 'Participant name', + * 'email' => 'Participant e-mail address', // used as identifier + * 'role' => 'ORGANIZER|REQ-PARTICIPANT|OPT-PARTICIPANT|CHAIR', + * 'status' => 'NEEDS-ACTION|UNKNOWN|ACCEPTED|TENTATIVE|DECLINED' + * 'rsvp' => true|false, + * ), + * + * '_savemode' => 'all|future|current|new', // How changes on recurring event should be handled + * '_notify' => true|false, // whether to notify event attendees about changes + * '_fromcalendar' => 'Calendar identifier where the event was stored before', + * ); + */ + +/** + * Interface definition for calendar driver classes + */ +abstract class calendar_driver +{ + // features supported by backend + public $alarms = false; + public $attendees = false; + public $freebusy = false; + public $attachments = false; + public $undelete = false; // event undelete action + public $categoriesimmutable = false; + public $alarm_types = array('DISPLAY'); + public $alarm_absolute = true; + public $last_error; + + protected $default_categories = array( + 'Personal' => 'c0c0c0', + 'Work' => 'ff0000', + 'Family' => '00ff00', + 'Holiday' => 'ff6600', + ); + + /** + * Get a list of available calendars from this source + * + * @param bool $active Return only active calendars + * @param bool $personal Return only personal calendars + * + * @return array List of calendars + */ + abstract function list_calendars($active = false, $personal = false); + + /** + * Create a new calendar assigned to the current user + * + * @param array Hash array with calendar properties + * name: Calendar name + * color: The color of the calendar + * showalarms: True if alarms are enabled + * @return mixed ID of the calendar on success, False on error + */ + abstract function create_calendar($prop); + + /** + * Update properties of an existing calendar + * + * @param array Hash array with calendar properties + * id: Calendar Identifier + * name: Calendar name + * color: The color of the calendar + * showalarms: True if alarms are enabled (if supported) + * @return boolean True on success, Fales on failure + */ + abstract function edit_calendar($prop); + + /** + * Set active/subscribed state of a calendar + * + * @param array Hash array with calendar properties + * id: Calendar Identifier + * active: True if calendar is active, false if not + * @return boolean True on success, Fales on failure + */ + abstract function subscribe_calendar($prop); + + /** + * Delete the given calendar with all its contents + * + * @param array Hash array with calendar properties + * id: Calendar Identifier + * @return boolean True on success, Fales on failure + */ + abstract function remove_calendar($prop); + + /** + * Add a single event to the database + * + * @param array Hash array with event properties (see header of this file) + * @return mixed New event ID on success, False on error + */ + abstract function new_event($event); + + /** + * Update an event entry with the given data + * + * @param array Hash array with event properties (see header of this file) + * @return boolean True on success, False on error + */ + abstract function edit_event($event); + + /** + * Move a single event + * + * @param array Hash array with event properties: + * id: Event identifier + * start: Event start date/time as DateTime object + * end: Event end date/time as DateTime object + * allday: Boolean flag if this is an all-day event + * @return boolean True on success, False on error + */ + abstract function move_event($event); + + /** + * Resize a single event + * + * @param array Hash array with event properties: + * id: Event identifier + * start: Event start date/time as DateTime object with timezone + * end: Event end date/time as DateTime object with timezone + * @return boolean True on success, False on error + */ + abstract function resize_event($event); + + /** + * Remove a single event from the database + * + * @param array Hash array with event properties: + * id: Event identifier + * @param boolean Remove event irreversible (mark as deleted otherwise, + * if supported by the backend) + * + * @return boolean True on success, False on error + */ + abstract function remove_event($event, $force = true); + + /** + * Restores a single deleted event (if supported) + * + * @param array Hash array with event properties: + * id: Event identifier + * + * @return boolean True on success, False on error + */ + public function restore_event($event) + { + return false; + } + + /** + * Return data of a single event + * + * @param mixed UID string or hash array with event properties: + * id: Event identifier + * calendar: Calendar identifier (optional) + * @param boolean If true, only writeable calendars shall be searched + * @param boolean If true, only active calendars shall be searched + * @param boolean If true, only personal calendars shall be searched + * + * @return array Event object as hash array + */ + abstract function get_event($event, $writeable = false, $active = false, $personal = false); + + /** + * Get events from source. + * + * @param integer Event's new start (unix timestamp) + * @param integer Event's new end (unix timestamp) + * @param string Search query (optional) + * @param mixed List of calendar IDs to load events from (either as array or comma-separated string) + * @return array A list of event objects (see header of this file for struct of an event) + */ + abstract function load_events($start, $end, $query = null, $calendars = null); + + /** + * Get a list of pending alarms to be displayed to the user + * + * @param integer Current time (unix timestamp) + * @param mixed List of calendar IDs to show alarms for (either as array or comma-separated string) + * @return array A list of alarms, each encoded as hash array: + * id: Event identifier + * uid: Unique identifier of this event + * start: Event start date/time as DateTime object + * end: Event end date/time as DateTime object + * allday: Boolean flag if this is an all-day event + * title: Event title/summary + * location: Location string + */ + abstract function pending_alarms($time, $calendars = null); + + /** + * (User) feedback after showing an alarm notification + * This should mark the alarm as 'shown' or snooze it for the given amount of time + * + * @param string Event identifier + * @param integer Suspend the alarm for this number of seconds + */ + abstract function dismiss_alarm($event_id, $snooze = 0); + + /** + * Check the given event object for validity + * + * @param array Event object as hash array + * @return boolean True if valid, false if not + */ + public function validate($event) + { + $valid = true; + + if (!is_object($event['start']) || !is_a($event['start'], 'DateTime')) + $valid = false; + if (!is_object($event['end']) || !is_a($event['end'], 'DateTime')) + $valid = false; + + return $valid; + } + + + /** + * Get list of event's attachments. + * Drivers can return list of attachments as event property. + * If they will do not do this list_attachments() method will be used. + * + * @param array $event Hash array with event properties: + * id: Event identifier + * calendar: Calendar identifier + * + * @return array List of attachments, each as hash array: + * id: Attachment identifier + * name: Attachment name + * mimetype: MIME content type of the attachment + * size: Attachment size + */ + public function list_attachments($event) { } + + /** + * Get attachment properties + * + * @param string $id Attachment identifier + * @param array $event Hash array with event properties: + * id: Event identifier + * calendar: Calendar identifier + * + * @return array Hash array with attachment properties: + * id: Attachment identifier + * name: Attachment name + * mimetype: MIME content type of the attachment + * size: Attachment size + */ + public function get_attachment($id, $event) { } + + /** + * Get attachment body + * + * @param string $id Attachment identifier + * @param array $event Hash array with event properties: + * id: Event identifier + * calendar: Calendar identifier + * + * @return string Attachment body + */ + public function get_attachment_body($id, $event) { } + + /** + * List availabale categories + * The default implementation reads them from config/user prefs + */ + public function list_categories() + { + $rcmail = rcube::get_instance(); + return $rcmail->config->get('calendar_categories', $this->default_categories); + } + + /** + * Create a new category + */ + public function add_category($name, $color) { } + + /** + * Remove the given category + */ + public function remove_category($name) { } + + /** + * Update/replace a category + */ + public function replace_category($oldname, $name, $color) { } + + /** + * Fetch free/busy information from a person within the given range + * + * @param string E-mail address of attendee + * @param integer Requested period start date/time as unix timestamp + * @param integer Requested period end date/time as unix timestamp + * + * @return array List of busy timeslots within the requested range + */ + public function get_freebusy_list($email, $start, $end) + { + return false; + } + + /** + * Callback function to produce driver-specific calendar create/edit form + * + * @param string Request action 'form-edit|form-new' + * @param array Calendar properties (e.g. id, color) + * @param array Edit form fields + * + * @return string HTML content of the form + */ + public function calendar_form($action, $calendar, $formfields) + { + $html = ''; + foreach ($formfields as $field) { + $html .= html::div('form-section', + html::label($field['id'], $field['label']) . + $field['value']); + } + + return $html; + } + + /** + * Return a (limited) list of color values to be used for calendar and category coloring + * + * @return mixed List for colors as hex values or false if no presets should be shown + */ + public function get_color_values() + { + return false; + } + +} diff --git a/drivers/database/SQL/mysql.initial.sql b/drivers/database/SQL/mysql.initial.sql new file mode 100644 index 0000000..945d429 --- /dev/null +++ b/drivers/database/SQL/mysql.initial.sql @@ -0,0 +1,83 @@ +/** + * Roundcube Calendar + * + * Plugin to add a calendar to Roundcube. + * + * @version @package_version@ + * @author Lazlo Westerhof + * @author Thomas Bruederli + * @url http://rc-calendar.lazlo.me + * @licence GNU AGPL + * @copyright (c) 2010 Lazlo Westerhof - Netherlands + * + **/ + +CREATE TABLE IF NOT EXISTS `calendars` ( + `calendar_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0', + `name` varchar(255) NOT NULL, + `color` varchar(8) NOT NULL, + `showalarms` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY(`calendar_id`), + INDEX `user_name_idx` (`user_id`, `name`), + CONSTRAINT `fk_calendars_user_id` FOREIGN KEY (`user_id`) + REFERENCES `users`(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */ /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; + +CREATE TABLE IF NOT EXISTS `events` ( + `event_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `calendar_id` int(11) UNSIGNED NOT NULL DEFAULT '0', + `recurrence_id` int(11) UNSIGNED NOT NULL DEFAULT '0', + `uid` varchar(255) NOT NULL DEFAULT '', + `created` datetime NOT NULL DEFAULT '1000-01-01 00:00:00', + `changed` datetime NOT NULL DEFAULT '1000-01-01 00:00:00', + `sequence` int(1) UNSIGNED NOT NULL DEFAULT '0', + `start` datetime NOT NULL DEFAULT '1000-01-01 00:00:00', + `end` datetime NOT NULL DEFAULT '1000-01-01 00:00:00', + `recurrence` varchar(255) DEFAULT NULL, + `title` varchar(255) NOT NULL, + `description` text NOT NULL, + `location` varchar(255) NOT NULL DEFAULT '', + `categories` varchar(255) NOT NULL DEFAULT '', + `url` varchar(255) NOT NULL DEFAULT '', + `all_day` tinyint(1) NOT NULL DEFAULT '0', + `free_busy` tinyint(1) NOT NULL DEFAULT '0', + `priority` tinyint(1) NOT NULL DEFAULT '0', + `sensitivity` tinyint(1) NOT NULL DEFAULT '0', + `alarms` varchar(255) DEFAULT NULL, + `attendees` text DEFAULT NULL, + `notifyat` datetime DEFAULT NULL, + PRIMARY KEY(`event_id`), + INDEX `uid_idx` (`uid`), + INDEX `recurrence_idx` (`recurrence_id`), + INDEX `calendar_notify_idx` (`calendar_id`,`notifyat`), + CONSTRAINT `fk_events_calendar_id` FOREIGN KEY (`calendar_id`) + REFERENCES `calendars`(`calendar_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */ /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; + +CREATE TABLE IF NOT EXISTS `attachments` ( + `attachment_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `event_id` int(11) UNSIGNED NOT NULL DEFAULT '0', + `filename` varchar(255) NOT NULL DEFAULT '', + `mimetype` varchar(255) NOT NULL DEFAULT '', + `size` int(11) NOT NULL DEFAULT '0', + `data` longtext NOT NULL DEFAULT '', + PRIMARY KEY(`attachment_id`), + CONSTRAINT `fk_attachments_event_id` FOREIGN KEY (`event_id`) + REFERENCES `events`(`event_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */ /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; + +CREATE TABLE IF NOT EXISTS `itipinvitations` ( + `token` VARCHAR(64) NOT NULL, + `event_uid` VARCHAR(255) NOT NULL, + `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0', + `event` TEXT NOT NULL, + `expires` DATETIME DEFAULT NULL, + `cancelled` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`token`), + INDEX `uid_idx` (`user_id`,`event_uid`), + CONSTRAINT `fk_itipinvitations_user_id` FOREIGN KEY (`user_id`) + REFERENCES `users`(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */ /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; + +REPLACE INTO system (name, value) VALUES ('calendar-database-version', '2013051600'); diff --git a/drivers/database/SQL/mysql/2012080600.sql b/drivers/database/SQL/mysql/2012080600.sql new file mode 100644 index 0000000..f38e1cf --- /dev/null +++ b/drivers/database/SQL/mysql/2012080600.sql @@ -0,0 +1,3 @@ +-- MySQL database updates since version 0.7/0.8 + +ALTER TABLE `events` ADD `sequence` int(1) UNSIGNED NOT NULL DEFAULT '0' AFTER `changed`; diff --git a/drivers/database/SQL/mysql/2013011000.sql b/drivers/database/SQL/mysql/2013011000.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/database/SQL/mysql/2013011000.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/database/SQL/mysql/2013042700.sql b/drivers/database/SQL/mysql/2013042700.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/database/SQL/mysql/2013042700.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/database/SQL/mysql/2013051600.sql b/drivers/database/SQL/mysql/2013051600.sql new file mode 100644 index 0000000..4de44d6 --- /dev/null +++ b/drivers/database/SQL/mysql/2013051600.sql @@ -0,0 +1,3 @@ +-- MySQL database updates since version 0.9-beta + +ALTER TABLE `events` ADD `url` VARCHAR(255) NOT NULL AFTER `categories`; \ No newline at end of file diff --git a/drivers/database/SQL/mysql/2013071800.sql b/drivers/database/SQL/mysql/2013071800.sql new file mode 100644 index 0000000..a051c6a --- /dev/null +++ b/drivers/database/SQL/mysql/2013071800.sql @@ -0,0 +1,3 @@ +-- MySQL database updates since version 0.9.1 + +ALTER TABLE `events` ADD `custom` TEXT NULL AFTER `attendees`; diff --git a/drivers/database/SQL/postgres.initial.sql b/drivers/database/SQL/postgres.initial.sql new file mode 100644 index 0000000..00a91c2 --- /dev/null +++ b/drivers/database/SQL/postgres.initial.sql @@ -0,0 +1,107 @@ +/** + * RoundCube Calendar + * + * Plugin to add a calendar to RoundCube. + * + * @version @package_version@ + * @author Lazlo Westerhof + * @author Albert Lee + * @author Aleksander Machniak + * @url http://rc-calendar.lazlo.me + * @licence GNU AGPL + * @copyright (c) 2010 Lazlo Westerhof - Netherlands + * + **/ + + +CREATE SEQUENCE calendars_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +CREATE TABLE calendars ( + calendar_id integer DEFAULT nextval('calendars_seq'::regclass) NOT NULL, + user_id integer NOT NULL + REFERENCES users (user_id) ON UPDATE CASCADE ON DELETE CASCADE, + name varchar(255) NOT NULL, + color varchar(8) NOT NULL, + showalarms smallint NOT NULL DEFAULT 1, + PRIMARY KEY (calendar_id) +); + +CREATE INDEX calendars_user_id_idx ON calendars (user_id, name); + + +CREATE SEQUENCE events_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +CREATE TABLE events ( + event_id integer DEFAULT nextval('events_seq'::regclass) NOT NULL, + calendar_id integer NOT NULL + REFERENCES calendars (calendar_id) ON UPDATE CASCADE ON DELETE CASCADE, + recurrence_id integer NOT NULL DEFAULT 0, + uid varchar(255) NOT NULL DEFAULT '', + created timestamp without time zone DEFAULT now() NOT NULL, + changed timestamp without time zone DEFAULT now(), + sequence integer NOT NULL DEFAULT 0, + "start" timestamp without time zone DEFAULT now() NOT NULL, + "end" timestamp without time zone DEFAULT now() NOT NULL, + recurrence varchar(255) DEFAULT NULL, + title character varying(255) NOT NULL, + description text NOT NULL, + location character varying(255) NOT NULL, + categories character varying(255) NOT NULL, + url character varying(255) NOT NULL, + all_day smallint NOT NULL DEFAULT 0, + free_busy smallint NOT NULL DEFAULT 0, + priority smallint NOT NULL DEFAULT 0, + sensitivity smallint NOT NULL DEFAULT 0, + alarms varchar(255) DEFAULT NULL, + attendees text DEFAULT NULL, + notifyat timestamp without time zone DEFAULT NULL, + PRIMARY KEY (event_id) +); + +CREATE INDEX events_calendar_id_notifyat_idx ON events (calendar_id, notifyat); +CREATE INDEX events_uid_idx ON events (uid); +CREATE INDEX events_recurrence_id_idx ON events (recurrence_id); + + +CREATE SEQUENCE attachments_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +CREATE TABLE attachments ( + attachment_id integer DEFAULT nextval('attachments_seq'::regclass) NOT NULL, + event_id integer NOT NULL + REFERENCES events (event_id) ON DELETE CASCADE ON UPDATE CASCADE, + filename varchar(255) NOT NULL DEFAULT '', + mimetype varchar(255) NOT NULL DEFAULT '', + size integer NOT NULL DEFAULT 0, + data text NOT NULL DEFAULT '', + PRIMARY KEY (attachment_id) +); + +CREATE INDEX attachments_user_id_idx ON attachments (event_id); + + +CREATE TABLE itipinvitations ( + token varchar(64) NOT NULL, + event_uid varchar(255) NOT NULL, + user_id integer NOT NULL + REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE, + event TEXT NOT NULL, + expires timestamp without time zone DEFAULT NULL, + cancelled smallint NOT NULL DEFAULT 0, + PRIMARY KEY (token) +); + +CREATE INDEX itipinvitations_user_id_event_uid_idx ON itipinvitations (user_id, event_uid); + +INSERT INTO system (name, value) VALUES ('calendar-database-version', '2013051600'); diff --git a/drivers/database/SQL/postgres/2012080600.sql b/drivers/database/SQL/postgres/2012080600.sql new file mode 100644 index 0000000..9a273e6 --- /dev/null +++ b/drivers/database/SQL/postgres/2012080600.sql @@ -0,0 +1,3 @@ +-- Postgres database updates since version 0.7/0.8 + +ALTER TABLE events ADD sequence integer NOT NULL DEFAULT 0; diff --git a/drivers/database/SQL/postgres/2013011000.sql b/drivers/database/SQL/postgres/2013011000.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/database/SQL/postgres/2013011000.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/database/SQL/postgres/2013042700.sql b/drivers/database/SQL/postgres/2013042700.sql new file mode 100644 index 0000000..d644c39 --- /dev/null +++ b/drivers/database/SQL/postgres/2013042700.sql @@ -0,0 +1,8 @@ +ALTER SEQUENCE calendar_ids RENAME TO calendars_seq; +ALTER TABLE calendars ALTER COLUMN calendar_id SET DEFAULT nextval('calendars_seq'::text); + +ALTER SEQUENCE event_ids RENAME TO events_seq; +ALTER TABLE events ALTER COLUMN event_id SET DEFAULT nextval('events_seq'::text); + +ALTER SEQUENCE attachment_ids RENAME TO attachments_seq; +ALTER TABLE attachments ALTER COLUMN attachment_id SET DEFAULT nextval('attachments_seq'::text); diff --git a/drivers/database/SQL/postgres/2013051600.sql b/drivers/database/SQL/postgres/2013051600.sql new file mode 100644 index 0000000..3c1da43 --- /dev/null +++ b/drivers/database/SQL/postgres/2013051600.sql @@ -0,0 +1,3 @@ +-- Postgres database updates since version 0.9-beta + +ALTER TABLE events ADD url character varying(255) NOT NULL; diff --git a/drivers/database/SQL/postgres/2013071800.sql b/drivers/database/SQL/postgres/2013071800.sql new file mode 100644 index 0000000..e286daa --- /dev/null +++ b/drivers/database/SQL/postgres/2013071800.sql @@ -0,0 +1,3 @@ +-- Postgres database updates since version 0.9.1 + +ALTER TABLE events ADD custom text DEFAULT NULL; diff --git a/drivers/database/SQL/sqlite.initial.sql b/drivers/database/SQL/sqlite.initial.sql new file mode 100644 index 0000000..6e0643b --- /dev/null +++ b/drivers/database/SQL/sqlite.initial.sql @@ -0,0 +1,77 @@ +/** + * Roundcube Calendar + * + * Plugin to add a calendar to Roundcube. + * + * @version @package_version@ + * @author Lazlo Westerhof + * @author Thomas Bruederli + * @author Albert Lee + * @url http://rc-calendar.lazlo.me + * @licence GNU AGPL + * @copyright (c) 2010 Lazlo Westerhof - Netherlands + * + **/ + +CREATE TABLE calendars ( + calendar_id integer NOT NULL PRIMARY KEY, + user_id integer NOT NULL default '0', + name varchar(255) NOT NULL default '', + color varchar(255) NOT NULL default '', + showalarms tinyint(1) NOT NULL default '1', + CONSTRAINT fk_calendars_user_id FOREIGN KEY (user_id) + REFERENCES users(user_id) +); + +CREATE TABLE events ( + event_id integer NOT NULL PRIMARY KEY, + calendar_id integer NOT NULL default '0', + recurrence_id integer NOT NULL default '0', + uid varchar(255) NOT NULL default '', + created datetime NOT NULL default '1000-01-01 00:00:00', + changed datetime NOT NULL default '1000-01-01 00:00:00', + sequence integer NOT NULL default '0', + start datetime NOT NULL default '1000-01-01 00:00:00', + end datetime NOT NULL default '1000-01-01 00:00:00', + recurrence varchar(255) default NULL, + title varchar(255) NOT NULL, + description text NOT NULL, + location varchar(255) NOT NULL default '', + categories varchar(255) NOT NULL default '', + url varchar(255) NOT NULL default '', + all_day tinyint(1) NOT NULL default '0', + free_busy tinyint(1) NOT NULL default '0', + priority tinyint(1) NOT NULL default '0', + sensitivity tinyint(1) NOT NULL default '0', + alarms varchar(255) default NULL, + attendees text default NULL, + notifyat datetime default NULL, + CONSTRAINT fk_events_calendar_id FOREIGN KEY (calendar_id) + REFERENCES calendars(calendar_id) +); + +CREATE TABLE attachments ( + attachment_id integer NOT NULL PRIMARY KEY, + event_id integer NOT NULL default '0', + filename varchar(255) NOT NULL default '', + mimetype varchar(255) NOT NULL default '', + size integer NOT NULL default '0', + data text NOT NULL default '', + CONSTRAINT fk_attachment_event_id FOREIGN KEY (event_id) + REFERENCES events(event_id) +); + +CREATE TABLE itipinvitations ( + token varchar(64) NOT NULL PRIMARY KEY, + event_uid varchar(255) NOT NULL, + user_id integer NOT NULL default '0', + event text NOT NULL, + expires datetime NOT NULL default '1000-01-01 00:00:00', + cancelled tinyint(1) NOT NULL default '0', + CONSTRAINT fk_itipinvitations_user_id FOREIGN KEY (user_id) + REFERENCES users(user_id) +); + +CREATE INDEX ix_itipinvitations_uid ON itipinvitations(user_id, event_uid); + +INSERT INTO system (name, value) VALUES ('calendar-database-version', '2013051600'); diff --git a/drivers/database/SQL/sqlite/2013011000.sql b/drivers/database/SQL/sqlite/2013011000.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/database/SQL/sqlite/2013011000.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/database/SQL/sqlite/2013042700.sql b/drivers/database/SQL/sqlite/2013042700.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/database/SQL/sqlite/2013042700.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/database/SQL/sqlite/2013051600.sql b/drivers/database/SQL/sqlite/2013051600.sql new file mode 100644 index 0000000..850fae3 --- /dev/null +++ b/drivers/database/SQL/sqlite/2013051600.sql @@ -0,0 +1,63 @@ +-- SQLite database updates since version 0.9-beta + +-- ALTER TABLE events ADD url varchar(255) NOT NULL AFTER categories; + +CREATE TABLE temp_events ( + event_id integer NOT NULL PRIMARY KEY, + calendar_id integer NOT NULL default '0', + recurrence_id integer NOT NULL default '0', + uid varchar(255) NOT NULL default '', + created datetime NOT NULL default '1000-01-01 00:00:00', + changed datetime NOT NULL default '1000-01-01 00:00:00', + sequence integer NOT NULL default '0', + start datetime NOT NULL default '1000-01-01 00:00:00', + end datetime NOT NULL default '1000-01-01 00:00:00', + recurrence varchar(255) default NULL, + title varchar(255) NOT NULL, + description text NOT NULL, + location varchar(255) NOT NULL default '', + categories varchar(255) NOT NULL default '', + all_day tinyint(1) NOT NULL default '0', + free_busy tinyint(1) NOT NULL default '0', + priority tinyint(1) NOT NULL default '0', + sensitivity tinyint(1) NOT NULL default '0', + alarms varchar(255) default NULL, + attendees text default NULL, + notifyat datetime default NULL +); + +INSERT INTO temp_events (event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat) + SELECT event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat FROM events; + +DROP TABLE events; + +CREATE TABLE events ( + event_id integer NOT NULL PRIMARY KEY, + calendar_id integer NOT NULL default '0', + recurrence_id integer NOT NULL default '0', + uid varchar(255) NOT NULL default '', + created datetime NOT NULL default '1000-01-01 00:00:00', + changed datetime NOT NULL default '1000-01-01 00:00:00', + sequence integer NOT NULL default '0', + start datetime NOT NULL default '1000-01-01 00:00:00', + end datetime NOT NULL default '1000-01-01 00:00:00', + recurrence varchar(255) default NULL, + title varchar(255) NOT NULL, + description text NOT NULL, + location varchar(255) NOT NULL default '', + categories varchar(255) NOT NULL default '', + url varchar(255) NOT NULL default '', + all_day tinyint(1) NOT NULL default '0', + free_busy tinyint(1) NOT NULL default '0', + priority tinyint(1) NOT NULL default '0', + sensitivity tinyint(1) NOT NULL default '0', + alarms varchar(255) default NULL, + attendees text default NULL, + notifyat datetime default NULL, + CONSTRAINT fk_events_calendar_id FOREIGN KEY (calendar_id) + REFERENCES calendars(calendar_id) +); + +INSERT INTO events (event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat) + SELECT event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat FROM temp_events; + diff --git a/drivers/database/SQL/sqlite/2013071800.sql b/drivers/database/SQL/sqlite/2013071800.sql new file mode 100644 index 0000000..317b955 --- /dev/null +++ b/drivers/database/SQL/sqlite/2013071800.sql @@ -0,0 +1,64 @@ +-- SQLite database updates since version 0.9.1 + +-- ALTER TABLE events ADD custom text DEFAULT NULL AFTER attendees; + +CREATE TABLE temp_events ( + event_id integer NOT NULL PRIMARY KEY, + calendar_id integer NOT NULL default '0', + recurrence_id integer NOT NULL default '0', + uid varchar(255) NOT NULL default '', + created datetime NOT NULL default '1000-01-01 00:00:00', + changed datetime NOT NULL default '1000-01-01 00:00:00', + sequence integer NOT NULL default '0', + start datetime NOT NULL default '1000-01-01 00:00:00', + end datetime NOT NULL default '1000-01-01 00:00:00', + recurrence varchar(255) default NULL, + title varchar(255) NOT NULL, + description text NOT NULL, + location varchar(255) NOT NULL default '', + categories varchar(255) NOT NULL default '', + all_day tinyint(1) NOT NULL default '0', + free_busy tinyint(1) NOT NULL default '0', + priority tinyint(1) NOT NULL default '0', + sensitivity tinyint(1) NOT NULL default '0', + alarms varchar(255) default NULL, + attendees text default NULL, + notifyat datetime default NULL +); + +INSERT INTO temp_events (event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat) + SELECT event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat FROM events; + +DROP TABLE events; + +CREATE TABLE events ( + event_id integer NOT NULL PRIMARY KEY, + calendar_id integer NOT NULL default '0', + recurrence_id integer NOT NULL default '0', + uid varchar(255) NOT NULL default '', + created datetime NOT NULL default '1000-01-01 00:00:00', + changed datetime NOT NULL default '1000-01-01 00:00:00', + sequence integer NOT NULL default '0', + start datetime NOT NULL default '1000-01-01 00:00:00', + end datetime NOT NULL default '1000-01-01 00:00:00', + recurrence varchar(255) default NULL, + title varchar(255) NOT NULL, + description text NOT NULL, + location varchar(255) NOT NULL default '', + categories varchar(255) NOT NULL default '', + url varchar(255) NOT NULL default '', + all_day tinyint(1) NOT NULL default '0', + free_busy tinyint(1) NOT NULL default '0', + priority tinyint(1) NOT NULL default '0', + sensitivity tinyint(1) NOT NULL default '0', + alarms varchar(255) default NULL, + attendees text default NULL, + custom text default NULL, + notifyat datetime default NULL, + CONSTRAINT fk_events_calendar_id FOREIGN KEY (calendar_id) + REFERENCES calendars(calendar_id) +); + +INSERT INTO events (event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat) + SELECT event_id, calendar_id, recurrence_id, uid, created, changed, sequence, start, end, recurrence, title, description, location, categories, all_day, free_busy, priority, sensitivity, alarms, attendees, notifyat FROM temp_events; + diff --git a/drivers/database/database_driver.php b/drivers/database/database_driver.php new file mode 100644 index 0000000..e20b9f0 --- /dev/null +++ b/drivers/database/database_driver.php @@ -0,0 +1,1028 @@ + + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +class database_driver extends calendar_driver +{ + const DB_DATE_FORMAT = 'Y-m-d H:i:s'; + + // features this backend supports + public $alarms = true; + public $attendees = true; + public $freebusy = false; + public $attachments = true; + public $alarm_types = array('DISPLAY'); + + private $rc; + private $cal; + private $cache = array(); + private $calendars = array(); + private $calendar_ids = ''; + private $free_busy_map = array('free' => 0, 'busy' => 1, 'out-of-office' => 2, 'outofoffice' => 2, 'tentative' => 3); + private $sensitivity_map = array('public' => 0, 'private' => 1, 'confidential' => 2); + private $server_timezone; + + private $db_events = 'events'; + private $db_calendars = 'calendars'; + private $db_attachments = 'attachments'; + + + /** + * Default constructor + */ + public function __construct($cal) + { + $this->cal = $cal; + $this->rc = $cal->rc; + $this->server_timezone = new DateTimeZone(date_default_timezone_get()); + + // load library classes + require_once($this->cal->home . '/lib/Horde_Date_Recurrence.php'); + + // read database config + $db = $this->rc->get_dbh(); + $this->db_events = $this->rc->config->get('db_table_events', $db->table_name($this->db_events)); + $this->db_calendars = $this->rc->config->get('db_table_calendars', $db->table_name($this->db_calendars)); + $this->db_attachments = $this->rc->config->get('db_table_attachments', $db->table_name($this->db_attachments)); + + $this->_read_calendars(); + } + + /** + * Read available calendars for the current user and store them internally + */ + private function _read_calendars() + { + $hidden = array_filter(explode(',', $this->rc->config->get('hidden_calendars', ''))); + + if (!empty($this->rc->user->ID)) { + $calendar_ids = array(); + $result = $this->rc->db->query( + "SELECT *, calendar_id AS id FROM " . $this->db_calendars . " + WHERE user_id=? + ORDER BY name", + $this->rc->user->ID + ); + while ($result && ($arr = $this->rc->db->fetch_assoc($result))) { + $arr['showalarms'] = intval($arr['showalarms']); + $arr['active'] = !in_array($arr['id'], $hidden); + $arr['name'] = html::quote($arr['name']); + $this->calendars[$arr['calendar_id']] = $arr; + $calendar_ids[] = $this->rc->db->quote($arr['calendar_id']); + } + $this->calendar_ids = join(',', $calendar_ids); + } + } + + /** + * Get a list of available calendars from this source + * + * @param bool $active Return only active calendars + * @param bool $personal Return only personal calendars + * + * @return array List of calendars + */ + public function list_calendars($active = false, $personal = false) + { + // attempt to create a default calendar for this user + if (empty($this->calendars)) { + if ($this->create_calendar(array('name' => 'Default', 'color' => 'cc0000'))) + $this->_read_calendars(); + } + + $calendars = $this->calendars; + + // filter active calendars + if ($active) { + foreach ($calendars as $idx => $cal) { + if (!$cal['active']) { + unset($calendars[$idx]); + } + } + } + + // 'personal' is unsupported in this driver + + return $calendars; + } + + /** + * Create a new calendar assigned to the current user + * + * @param array Hash array with calendar properties + * name: Calendar name + * color: The color of the calendar + * @return mixed ID of the calendar on success, False on error + */ + public function create_calendar($prop) + { + $result = $this->rc->db->query( + "INSERT INTO " . $this->db_calendars . " + (user_id, name, color, showalarms) + VALUES (?, ?, ?, ?)", + $this->rc->user->ID, + $prop['name'], + $prop['color'], + $prop['showalarms']?1:0 + ); + + if ($result) + return $this->rc->db->insert_id($this->db_calendars); + + return false; + } + + /** + * Update properties of an existing calendar + * + * @see calendar_driver::edit_calendar() + */ + public function edit_calendar($prop) + { + $query = $this->rc->db->query( + "UPDATE " . $this->db_calendars . " + SET name=?, color=?, showalarms=? + WHERE calendar_id=? + AND user_id=?", + $prop['name'], + $prop['color'], + $prop['showalarms']?1:0, + $prop['id'], + $this->rc->user->ID + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * Set active/subscribed state of a calendar + * Save a list of hidden calendars in user prefs + * + * @see calendar_driver::subscribe_calendar() + */ + public function subscribe_calendar($prop) + { + $hidden = array_flip(explode(',', $this->rc->config->get('hidden_calendars', ''))); + + if ($prop['active']) + unset($hidden[$prop['id']]); + else + $hidden[$prop['id']] = 1; + + return $this->rc->user->save_prefs(array('hidden_calendars' => join(',', array_keys($hidden)))); + } + + /** + * Delete the given calendar with all its contents + * + * @see calendar_driver::remove_calendar() + */ + public function remove_calendar($prop) + { + if (!$this->calendars[$prop['id']]) + return false; + + // events and attachments will be deleted by foreign key cascade + + $query = $this->rc->db->query( + "DELETE FROM " . $this->db_calendars . " + WHERE calendar_id=?", + $prop['id'] + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * Add a single event to the database + * + * @param array Hash array with event properties + * @see calendar_driver::new_event() + */ + public function new_event($event) + { + if (!$this->validate($event)) + return false; + + if (!empty($this->calendars)) { + if ($event['calendar'] && !$this->calendars[$event['calendar']]) + return false; + if (!$event['calendar']) + $event['calendar'] = reset(array_keys($this->calendars)); + + $event = $this->_save_preprocess($event); + + $this->rc->db->query(sprintf( + "INSERT INTO " . $this->db_events . " + (calendar_id, created, changed, uid, %s, %s, all_day, recurrence, title, description, location, categories, url, free_busy, priority, sensitivity, attendees, alarms, notifyat) + VALUES (?, %s, %s, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + $this->rc->db->quote_identifier('start'), + $this->rc->db->quote_identifier('end'), + $this->rc->db->now(), + $this->rc->db->now() + ), + $event['calendar'], + strval($event['uid']), + $event['start']->format(self::DB_DATE_FORMAT), + $event['end']->format(self::DB_DATE_FORMAT), + intval($event['all_day']), + $event['_recurrence'], + strval($event['title']), + strval($event['description']), + strval($event['location']), + strval($event['categories']), + strval($event['url']), + intval($event['free_busy']), + intval($event['priority']), + intval($event['sensitivity']), + $event['attendees'], + $event['alarms'], + $event['notifyat'] + ); + + $event_id = $this->rc->db->insert_id($this->db_events); + + if ($event_id) { + $event['id'] = $event_id; + + // add attachments + if (!empty($event['attachments'])) { + foreach ($event['attachments'] as $attachment) { + $this->add_attachment($attachment, $event_id); + unset($attachment); + } + } + + $this->_update_recurring($event); + } + + return $event_id; + } + + return false; + } + + /** + * Update an event entry with the given data + * + * @param array Hash array with event properties + * @see calendar_driver::edit_event() + */ + public function edit_event($event) + { + if (!empty($this->calendars)) { + $update_master = false; + $update_recurring = true; + $old = $this->get_event($event); + + // increment sequence number + if ($old['sequence'] && empty($event['sequence'])) + $event['sequence'] = max($event['sequence'], $old['sequence']+1); + + // modify a recurring event, check submitted savemode to do the right things + if ($old['recurrence'] || $old['recurrence_id']) { + $master = $old['recurrence_id'] ? $this->get_event(array('id' => $old['recurrence_id'])) : $old; + + // keep saved exceptions (not submitted by the client) + if ($old['recurrence']['EXDATE']) + $event['recurrence']['EXDATE'] = $old['recurrence']['EXDATE']; + + switch ($event['_savemode']) { + case 'new': + $event['uid'] = $this->cal->generate_uid(); + return $this->new_event($event); + + case 'current': + // add exception to master event + $master['recurrence']['EXDATE'][] = $old['start']; + $update_master = true; + + // just update this occurence (decouple from master) + $update_recurring = false; + $event['recurrence_id'] = 0; + $event['recurrence'] = array(); + break; + + case 'future': + if ($master['id'] != $event['id']) { + // set until-date on master event, then save this instance as new recurring event + $master['recurrence']['UNTIL'] = clone $event['start']; + $master['recurrence']['UNTIL']->sub(new DateInterval('P1D')); + unset($master['recurrence']['COUNT']); + $update_master = true; + + // if recurrence COUNT, update value to the correct number of future occurences + if ($event['recurrence']['COUNT']) { + $fromdate = clone $event['start']; + $fromdate->setTimezone($this->server_timezone); + $sqlresult = $this->rc->db->query(sprintf( + "SELECT event_id FROM " . $this->db_events . " + WHERE calendar_id IN (%s) + AND %s >= ? + AND recurrence_id=?", + $this->calendar_ids, + $this->rc->db->quote_identifier('start') + ), + $fromdate->format(self::DB_DATE_FORMAT), + $master['id']); + if ($count = $this->rc->db->num_rows($sqlresult)) + $event['recurrence']['COUNT'] = $count; + } + + $update_recurring = true; + $event['recurrence_id'] = 0; + break; + } + // else: 'future' == 'all' if modifying the master event + + default: // 'all' is default + $event['id'] = $master['id']; + $event['recurrence_id'] = 0; + + // use start date from master but try to be smart on time or duration changes + $old_start_date = $old['start']->format('Y-m-d'); + $old_start_time = $old['allday'] ? '' : $old['start']->format('H:i'); + $old_duration = $old['end']->format('U') - $old['start']->format('U'); + + $new_start_date = $event['start']->format('Y-m-d'); + $new_start_time = $event['allday'] ? '' : $event['start']->format('H:i'); + $new_duration = $event['end']->format('U') - $event['start']->format('U'); + + $diff = $old_start_date != $new_start_date || $old_start_time != $new_start_time || $old_duration != $new_duration; + + // shifted or resized + if ($diff && ($old_start_date == $new_start_date || $old_duration == $new_duration)) { + $event['start'] = $master['start']->add($old['start']->diff($event['start'])); + $event['end'] = clone $event['start']; + $event['end']->add(new DateInterval('PT'.$new_duration.'S')); + } + break; + } + } + + $success = $this->_update_event($event, $update_recurring); + if ($success && $update_master) + $this->_update_event($master, true); + + return $success; + } + + return false; + } + + /** + * Convert save data to be used in SQL statements + */ + private function _save_preprocess($event) + { + // shift dates to server's timezone + $event['start'] = clone $event['start']; + $event['start']->setTimezone($this->server_timezone); + $event['end'] = clone $event['end']; + $event['end']->setTimezone($this->server_timezone); + + // compose vcalendar-style recurrencue rule from structured data + $rrule = $event['recurrence'] ? libcalendaring::to_rrule($event['recurrence']) : ''; + $event['_recurrence'] = rtrim($rrule, ';'); + $event['free_busy'] = intval($this->free_busy_map[strtolower($event['free_busy'])]); + $event['sensitivity'] = intval($this->sensitivity_map[strtolower($event['sensitivity'])]); + + if (isset($event['allday'])) { + $event['all_day'] = $event['allday'] ? 1 : 0; + } + + // compute absolute time to notify the user + $event['notifyat'] = $this->_get_notification($event); + + // process event attendees + $_attendees = ''; + foreach ((array)$event['attendees'] as $attendee) { + if (!$attendee['name'] && !$attendee['email']) + continue; + $_attendees .= 'NAME="'.addcslashes($attendee['name'], '"') . '"' . + ';STATUS=' . $attendee['status']. + ';ROLE=' . $attendee['role'] . + ';EMAIL=' . $attendee['email'] . + "\n"; + } + $event['attendees'] = rtrim($_attendees); + + return $event; + } + + /** + * Compute absolute time to notify the user + */ + private function _get_notification($event) + { + if ($event['alarms'] && $event['start'] > new DateTime()) { + $alarm = libcalendaring::get_next_alarm($event); + + if ($alarm['time'] && $alarm['action'] == 'DISPLAY') + return date('Y-m-d H:i:s', $alarm['time']); + } + + return null; + } + + /** + * Save the given event record to database + * + * @param array Event data, already passed through self::_save_preprocess() + * @param boolean True if recurring events instances should be updated, too + */ + private function _update_event($event, $update_recurring = true) + { + $event = $this->_save_preprocess($event); + $sql_set = array(); + $set_cols = array('start', 'end', 'all_day', 'recurrence_id', 'sequence', 'title', 'description', 'location', 'categories', 'url', 'free_busy', 'priority', 'sensitivity', 'attendees', 'alarms', 'notifyat'); + foreach ($set_cols as $col) { + if (is_object($event[$col]) && is_a($event[$col], 'DateTime')) + $sql_set[] = $this->rc->db->quote_identifier($col) . '=' . $this->rc->db->quote($event[$col]->format(self::DB_DATE_FORMAT)); + else if (isset($event[$col])) + $sql_set[] = $this->rc->db->quote_identifier($col) . '=' . $this->rc->db->quote($event[$col]); + } + + if ($event['_recurrence']) + $sql_set[] = $this->rc->db->quote_identifier('recurrence') . '=' . $this->rc->db->quote($event['_recurrence']); + + if ($event['_fromcalendar'] && $event['_fromcalendar'] != $event['calendar']) + $sql_set[] = 'calendar_id=' . $this->rc->db->quote($event['calendar']); + + $query = $this->rc->db->query(sprintf( + "UPDATE " . $this->db_events . " + SET changed=%s %s + WHERE event_id=? + AND calendar_id IN (" . $this->calendar_ids . ")", + $this->rc->db->now(), + ($sql_set ? ', ' . join(', ', $sql_set) : '') + ), + $event['id'] + ); + + $success = $this->rc->db->affected_rows($query); + + // add attachments + if ($success && !empty($event['attachments'])) { + foreach ($event['attachments'] as $attachment) { + $this->add_attachment($attachment, $event['id']); + unset($attachment); + } + } + + // remove attachments + if ($success && !empty($event['deleted_attachments'])) { + foreach ($event['deleted_attachments'] as $attachment) { + $this->remove_attachment($attachment, $event['id']); + } + } + + if ($success) { + unset($this->cache[$event['id']]); + if ($update_recurring) + $this->_update_recurring($event); + } + + return $success; + } + + /** + * Insert "fake" entries for recurring occurences of this event + */ + private function _update_recurring($event) + { + if (empty($this->calendars)) + return; + + // clear existing recurrence copies + $this->rc->db->query( + "DELETE FROM " . $this->db_events . " + WHERE recurrence_id=? + AND calendar_id IN (" . $this->calendar_ids . ")", + $event['id'] + ); + + // create new fake entries + if ($event['recurrence']) { + // include library class + require_once($this->cal->home . '/lib/calendar_recurrence.php'); + + $recurrence = new calendar_recurrence($this->cal, $event); + + $count = 0; + $duration = $event['start']->diff($event['end']); + while ($next_start = $recurrence->next_start()) { + $next_start->setTimezone($this->server_timezone); + $next_end = clone $next_start; + $next_end->add($duration); + $notify_at = $this->_get_notification(array('alarms' => $event['alarms'], 'start' => $next_start, 'end' => $next_end)); + $query = $this->rc->db->query(sprintf( + "INSERT INTO " . $this->db_events . " + (calendar_id, recurrence_id, created, changed, uid, %s, %s, all_day, recurrence, title, description, location, categories, url, free_busy, priority, sensitivity, alarms, notifyat) + SELECT calendar_id, ?, %s, %s, uid, ?, ?, all_day, recurrence, title, description, location, categories, url, free_busy, priority, sensitivity, alarms, ? + FROM " . $this->db_events . " WHERE event_id=? AND calendar_id IN (" . $this->calendar_ids . ")", + $this->rc->db->quote_identifier('start'), + $this->rc->db->quote_identifier('end'), + $this->rc->db->now(), + $this->rc->db->now() + ), + $event['id'], + $next_start->format(self::DB_DATE_FORMAT), + $next_end->format(self::DB_DATE_FORMAT), + $notify_at, + $event['id'] + ); + + if (!$this->rc->db->affected_rows($query)) + break; + + // stop adding events for inifinite recurrence after 20 years + if (++$count > 999 || (!$recurrence->recurEnd && !$recurrence->recurCount && $next_start->format('Y') > date('Y') + 20)) + break; + } + } + } + + /** + * Move a single event + * + * @param array Hash array with event properties + * @see calendar_driver::move_event() + */ + public function move_event($event) + { + // let edit_event() do all the magic + return $this->edit_event($event + (array)$this->get_event($event)); + } + + /** + * Resize a single event + * + * @param array Hash array with event properties + * @see calendar_driver::resize_event() + */ + public function resize_event($event) + { + // let edit_event() do all the magic + return $this->edit_event($event + (array)$this->get_event($event)); + } + + /** + * Remove a single event from the database + * + * @param array Hash array with event properties + * @param boolean Remove record irreversible (@TODO) + * + * @see calendar_driver::remove_event() + */ + public function remove_event($event, $force = true) + { + if (!empty($this->calendars)) { + $event += (array)$this->get_event($event); + $master = $event; + $update_master = false; + $savemode = 'all'; + + // read master if deleting a recurring event + if ($event['recurrence'] || $event['recurrence_id']) { + $master = $event['recurrence_id'] ? $this->get_event(array('id' => $event['recurrence_id'])) : $event; + $savemode = $event['_savemode']; + } + + switch ($savemode) { + case 'current': + // add exception to master event + $master['recurrence']['EXDATE'][] = $event['start']; + $update_master = true; + + // just delete this single occurence + $query = $this->rc->db->query( + "DELETE FROM " . $this->db_events . " + WHERE calendar_id IN (" . $this->calendar_ids . ") + AND event_id=?", + $event['id'] + ); + break; + + case 'future': + if ($master['id'] != $event['id']) { + // set until-date on master event + $master['recurrence']['UNTIL'] = clone $event['start']; + $master['recurrence']['UNTIL']->sub(new DateInterval('P1D')); + unset($master['recurrence']['COUNT']); + $update_master = true; + + // delete this and all future instances + $fromdate = clone $event['start']; + $fromdate->setTimezone($this->server_timezone); + $query = $this->rc->db->query( + "DELETE FROM " . $this->db_events . " + WHERE calendar_id IN (" . $this->calendar_ids . ") + AND " . $this->rc->db->quote_identifier('start') . " >= ? + AND recurrence_id=?", + $fromdate->format(self::DB_DATE_FORMAT), + $master['id'] + ); + break; + } + // else: future == all if modifying the master event + + default: // 'all' is default + $query = $this->rc->db->query( + "DELETE FROM " . $this->db_events . " + WHERE (event_id=? OR recurrence_id=?) + AND calendar_id IN (" . $this->calendar_ids . ")", + $master['id'], + $master['id'] + ); + break; + } + + $success = $this->rc->db->affected_rows($query); + if ($success && $update_master) + $this->_update_event($master, true); + + return $success; + } + + return false; + } + + /** + * Return data of a specific event + * @param mixed Hash array with event properties or event UID + * @param boolean Only search in writeable calendars (ignored) + * @param boolean Only search in active calendars + * @param boolean Only search in personal calendars (ignored) + * @return array Hash array with event properties + */ + public function get_event($event, $writeable = false, $active = false, $personal = false) + { + $id = is_array($event) ? ($event['id'] ? $event['id'] : $event['uid']) : $event; + $col = is_array($event) && is_numeric($id) ? 'event_id' : 'uid'; + + if ($this->cache[$id]) + return $this->cache[$id]; + + if ($active) { + $calendars = $this->calendars; + foreach ($calendars as $idx => $cal) { + if (!$cal['active']) { + unset($calendars[$idx]); + } + } + $cals = join(',', $calendars); + } + else { + $cals = $this->calendar_ids; + } + + $result = $this->rc->db->query(sprintf( + "SELECT e.*, (SELECT COUNT(attachment_id) FROM " . $this->db_attachments . " + WHERE event_id = e.event_id OR event_id = e.recurrence_id) AS _attachments + FROM " . $this->db_events . " AS e + WHERE e.calendar_id IN (%s) + AND e.$col=?", + $cals + ), + $id); + + if ($result && ($event = $this->rc->db->fetch_assoc($result)) && $event['event_id']) { + $this->cache[$id] = $this->_read_postprocess($event); + return $this->cache[$id]; + } + + return false; + } + + /** + * Get event data + * + * @see calendar_driver::load_events() + */ + public function load_events($start, $end, $query = null, $calendars = null) + { + if (empty($calendars)) + $calendars = array_keys($this->calendars); + else if (is_string($calendars)) + $calendars = explode(',', $calendars); + + // only allow to select from calendars of this use + $calendar_ids = array_map(array($this->rc->db, 'quote'), array_intersect($calendars, array_keys($this->calendars))); + + // compose (slow) SQL query for searching + // FIXME: improve searching using a dedicated col and normalized values + if ($query) { + foreach (array('title','location','description','categories','attendees') as $col) + $sql_query[] = $this->rc->db->ilike($col, '%'.$query.'%'); + $sql_add = 'AND (' . join(' OR ', $sql_query) . ')'; + } + + $events = array(); + if (!empty($calendar_ids)) { + $result = $this->rc->db->query(sprintf( + "SELECT e.*, (SELECT COUNT(attachment_id) FROM " . $this->db_attachments . " + WHERE event_id = e.event_id OR event_id = e.recurrence_id) AS _attachments + FROM " . $this->db_events . " AS e + WHERE e.calendar_id IN (%s) + AND e.start <= %s AND e.end >= %s + %s + GROUP BY e.event_id", + join(',', $calendar_ids), + $this->rc->db->fromunixtime($end), + $this->rc->db->fromunixtime($start), + $sql_add + )); + + while ($result && ($event = $this->rc->db->fetch_assoc($result))) { + $events[] = $this->_read_postprocess($event); + } + } + + return $events; + } + + /** + * Convert sql record into a rcube style event object + */ + private function _read_postprocess($event) + { + $free_busy_map = array_flip($this->free_busy_map); + $sensitivity_map = array_flip($this->sensitivity_map); + + $event['id'] = $event['event_id']; + $event['start'] = new DateTime($event['start']); + $event['end'] = new DateTime($event['end']); + $event['allday'] = intval($event['all_day']); + $event['created'] = new DateTime($event['created']); + $event['changed'] = new DateTime($event['changed']); + $event['free_busy'] = $free_busy_map[$event['free_busy']]; + $event['sensitivity'] = $sensitivity_map[$event['sensitivity']]; + $event['calendar'] = $event['calendar_id']; + $event['recurrence_id'] = intval($event['recurrence_id']); + + // parse recurrence rule + if ($event['recurrence'] && preg_match_all('/([A-Z]+)=([^;]+);?/', $event['recurrence'], $m, PREG_SET_ORDER)) { + $event['recurrence'] = array(); + foreach ($m as $rr) { + if (is_numeric($rr[2])) + $rr[2] = intval($rr[2]); + else if ($rr[1] == 'UNTIL') + $rr[2] = date_create($rr[2]); + else if ($rr[1] == 'EXDATE') + $rr[2] = array_map('date_create', explode(',', $rr[2])); + $event['recurrence'][$rr[1]] = $rr[2]; + } + } + + if ($event['_attachments'] > 0) + $event['attachments'] = (array)$this->list_attachments($event); + + // decode serialized event attendees + if ($event['attendees']) { + $attendees = array(); + foreach (explode("\n", $event['attendees']) as $line) { + $att = array(); + foreach (rcube_utils::explode_quoted_string(';', $line) as $prop) { + list($key, $value) = explode("=", $prop); + $att[strtolower($key)] = stripslashes(trim($value, '""')); + } + $attendees[] = $att; + } + $event['attendees'] = $attendees; + } + + unset($event['event_id'], $event['calendar_id'], $event['notifyat'], $event['all_day'], $event['_attachments']); + return $event; + } + + /** + * Get a list of pending alarms to be displayed to the user + * + * @see calendar_driver::pending_alarms() + */ + public function pending_alarms($time, $calendars = null) + { + if (empty($calendars)) + $calendars = array_keys($this->calendars); + else if (is_string($calendars)) + $calendars = explode(',', $calendars); + + // only allow to select from calendars with activated alarms + $calendar_ids = array(); + foreach ($calendars as $cid) { + if ($this->calendars[$cid] && $this->calendars[$cid]['showalarms']) + $calendar_ids[] = $cid; + } + $calendar_ids = array_map(array($this->rc->db, 'quote'), $calendar_ids); + + $alarms = array(); + if (!empty($calendar_ids)) { + $result = $this->rc->db->query(sprintf( + "SELECT * FROM " . $this->db_events . " + WHERE calendar_id IN (%s) + AND notifyat <= %s AND %s > %s", + join(',', $calendar_ids), + $this->rc->db->fromunixtime($time), + $this->rc->db->quote_identifier('end'), + $this->rc->db->fromunixtime($time) + )); + + while ($result && ($event = $this->rc->db->fetch_assoc($result))) + $alarms[] = $this->_read_postprocess($event); + } + + return $alarms; + } + + /** + * Feedback after showing/sending an alarm notification + * + * @see calendar_driver::dismiss_alarm() + */ + public function dismiss_alarm($event_id, $snooze = 0) + { + // set new notifyat time or unset if not snoozed + $notify_at = $snooze > 0 ? date(self::DB_DATE_FORMAT, time() + $snooze) : null; + + $query = $this->rc->db->query(sprintf( + "UPDATE " . $this->db_events . " + SET changed=%s, notifyat=? + WHERE event_id=? + AND calendar_id IN (" . $this->calendar_ids . ")", + $this->rc->db->now()), + $notify_at, + $event_id + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * Save an attachment related to the given event + */ + private function add_attachment($attachment, $event_id) + { + $data = $attachment['data'] ? $attachment['data'] : file_get_contents($attachment['path']); + + $query = $this->rc->db->query( + "INSERT INTO " . $this->db_attachments . + " (event_id, filename, mimetype, size, data)" . + " VALUES (?, ?, ?, ?, ?)", + $event_id, + $attachment['name'], + $attachment['mimetype'], + strlen($data), + base64_encode($data) + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * Remove a specific attachment from the given event + */ + private function remove_attachment($attachment_id, $event_id) + { + $query = $this->rc->db->query( + "DELETE FROM " . $this->db_attachments . + " WHERE attachment_id = ?" . + " AND event_id IN (SELECT event_id FROM " . $this->db_events . + " WHERE event_id = ?" . + " AND calendar_id IN (" . $this->calendar_ids . "))", + $attachment_id, + $event_id + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * List attachments of specified event + */ + public function list_attachments($event) + { + $attachments = array(); + + if (!empty($this->calendar_ids)) { + $result = $this->rc->db->query( + "SELECT attachment_id AS id, filename AS name, mimetype, size " . + " FROM " . $this->db_attachments . + " WHERE event_id IN (SELECT event_id FROM " . $this->db_events . + " WHERE event_id=?" . + " AND calendar_id IN (" . $this->calendar_ids . "))". + " ORDER BY filename", + $event['recurrence_id'] ? $event['recurrence_id'] : $event['event_id'] + ); + + while ($result && ($arr = $this->rc->db->fetch_assoc($result))) { + $attachments[] = $arr; + } + } + + return $attachments; + } + + /** + * Get attachment properties + */ + public function get_attachment($id, $event) + { + if (!empty($this->calendar_ids)) { + $result = $this->rc->db->query( + "SELECT attachment_id AS id, filename AS name, mimetype, size " . + " FROM " . $this->db_attachments . + " WHERE attachment_id=?". + " AND event_id=?", + $id, + $event['recurrence_id'] ? $event['recurrence_id'] : $event['id'] + ); + + if ($result && ($arr = $this->rc->db->fetch_assoc($result))) { + return $arr; + } + } + + return null; + } + + /** + * Get attachment body + */ + public function get_attachment_body($id, $event) + { + if (!empty($this->calendar_ids)) { + $result = $this->rc->db->query( + "SELECT data " . + " FROM " . $this->db_attachments . + " WHERE attachment_id=?". + " AND event_id=?", + $id, + $event['id'] + ); + + if ($result && ($arr = $this->rc->db->fetch_assoc($result))) { + return base64_decode($arr['data']); + } + } + + return null; + } + + /** + * Remove the given category + */ + public function remove_category($name) + { + $query = $this->rc->db->query( + "UPDATE " . $this->db_events . " + SET categories='' + WHERE categories=? + AND calendar_id IN (" . $this->calendar_ids . ")", + $name + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * Update/replace a category + */ + public function replace_category($oldname, $name, $color) + { + $query = $this->rc->db->query( + "UPDATE " . $this->db_events . " + SET categories=? + WHERE categories=? + AND calendar_id IN (" . $this->calendar_ids . ")", + $name, + $oldname + ); + + return $this->rc->db->affected_rows($query); + } + +} diff --git a/drivers/kolab/SQL/mysql.initial.sql b/drivers/kolab/SQL/mysql.initial.sql new file mode 100644 index 0000000..f10d902 --- /dev/null +++ b/drivers/kolab/SQL/mysql.initial.sql @@ -0,0 +1,32 @@ +/** + * Roundcube Calendar Kolab backend + * + * @version @package_version@ + * @author Thomas Bruederli + * @licence GNU AGPL + **/ + +CREATE TABLE IF NOT EXISTS `kolab_alarms` ( + `event_id` VARCHAR(255) NOT NULL, + `user_id` int(10) UNSIGNED NOT NULL, + `notifyat` DATETIME DEFAULT NULL, + `dismissed` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`event_id`), + CONSTRAINT `fk_kolab_alarms_user_id` FOREIGN KEY (`user_id`) + REFERENCES `users`(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */; + +CREATE TABLE IF NOT EXISTS `itipinvitations` ( + `token` VARCHAR(64) NOT NULL, + `event_uid` VARCHAR(255) NOT NULL, + `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0', + `event` TEXT NOT NULL, + `expires` DATETIME DEFAULT NULL, + `cancelled` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`token`), + INDEX `uid_idx` (`event_uid`,`user_id`), + CONSTRAINT `fk_itipinvitations_user_id` FOREIGN KEY (`user_id`) + REFERENCES `users`(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */ /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; + +REPLACE INTO system (name, value) VALUES ('calendar-kolab-version', '2013011000'); diff --git a/drivers/kolab/SQL/mysql/2012080600.sql b/drivers/kolab/SQL/mysql/2012080600.sql new file mode 100644 index 0000000..5c9f1ae --- /dev/null +++ b/drivers/kolab/SQL/mysql/2012080600.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS `kolab_alarms`; + +CREATE TABLE `kolab_alarms` ( + `event_id` VARCHAR(255) NOT NULL, + `user_id` int(10) UNSIGNED NOT NULL, + `notifyat` DATETIME DEFAULT NULL, + `dismissed` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0', + PRIMARY KEY(`event_id`), + CONSTRAINT `fk_kolab_alarms_user_id` FOREIGN KEY (`user_id`) + REFERENCES `users`(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) /*!40000 ENGINE=INNODB */; diff --git a/drivers/kolab/SQL/mysql/2013011000.sql b/drivers/kolab/SQL/mysql/2013011000.sql new file mode 100644 index 0000000..fe6741a --- /dev/null +++ b/drivers/kolab/SQL/mysql/2013011000.sql @@ -0,0 +1 @@ +-- empty \ No newline at end of file diff --git a/drivers/kolab/SQL/postgres.initial.sql b/drivers/kolab/SQL/postgres.initial.sql new file mode 100644 index 0000000..b869240 --- /dev/null +++ b/drivers/kolab/SQL/postgres.initial.sql @@ -0,0 +1,30 @@ +/** + * Roundcube Calendar Kolab backend + * + * @author Sergey Sidlyarenko + * @licence GNU AGPL + **/ + +CREATE TABLE IF NOT EXISTS kolab_alarms ( + event_id character varying(255) NOT NULL, + user_id integer NOT NULL + REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE, + notifyat timestamp without time zone DEFAULT NULL, + dismissed smallint NOT NULL DEFAULT 0, + PRIMARY KEY(event_id) +); + +CREATE TABLE IF NOT EXISTS itipinvitations ( + token character varying(64) NOT NULL, + event_uid character varying(255) NOT NULL, + user_id integer NOT NULL + REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE, + event text NOT NULL, + expires timestamp without time zone DEFAULT NULL, + cancelled smallint NOT NULL DEFAULT 0, + PRIMARY KEY(token) +); + +CREATE INDEX itipinvitations_event_uid_user_id_idx ON itipinvitations (event_uid, user_id); + +INSERT INTO system (name, value) VALUES ('calendar-kolab-version', '2013011000'); diff --git a/drivers/kolab/kolab_calendar.php b/drivers/kolab/kolab_calendar.php new file mode 100644 index 0000000..1cf7107 --- /dev/null +++ b/drivers/kolab/kolab_calendar.php @@ -0,0 +1,656 @@ + + * @author Aleksander Machniak + * + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +class kolab_calendar +{ + public $id; + public $ready = false; + public $readonly = true; + public $attachments = true; + public $alarms = false; + public $categories = array(); + public $storage; + + private $cal; + private $events = array(); + private $imap_folder = 'INBOX/Calendar'; + private $search_fields = array('title', 'description', 'location', 'attendees'); + + + /** + * Default constructor + */ + public function __construct($imap_folder, $calendar) + { + $this->cal = $calendar; + + if (strlen($imap_folder)) + $this->imap_folder = $imap_folder; + + // ID is derrived from folder name + $this->id = kolab_storage::folder_id($this->imap_folder); + + // fetch objects from the given IMAP folder + $this->storage = kolab_storage::get_folder($this->imap_folder); + $this->ready = $this->storage && !PEAR::isError($this->storage); + + // Set readonly and alarms flags according to folder permissions + if ($this->ready) { + if ($this->storage->get_namespace() == 'personal') { + $this->readonly = false; + $this->alarms = true; + } + else { + $rights = $this->storage->get_myrights(); + if ($rights && !PEAR::isError($rights)) { + if (strpos($rights, 'i') !== false) + $this->readonly = false; + } + } + + // user-specific alarms settings win + $prefs = $this->cal->rc->config->get('kolab_calendars', array()); + if (isset($prefs[$this->id]['showalarms'])) + $this->alarms = $prefs[$this->id]['showalarms']; + } + } + + + /** + * Getter for a nice and human readable name for this calendar + * See http://wiki.kolab.org/UI-Concepts/Folder-Listing for reference + * + * @return string Name of this calendar + */ + public function get_name() + { + $folder = kolab_storage::object_name($this->imap_folder, $this->namespace); + return $folder; + } + + + /** + * Getter for the IMAP folder name + * + * @return string Name of the IMAP folder + */ + public function get_realname() + { + return $this->imap_folder; + } + + + /** + * Getter for the IMAP folder owner + * + * @return string Name of the folder owner + */ + public function get_owner() + { + return $this->storage->get_owner(); + } + + + /** + * Getter for the name of the namespace to which the IMAP folder belongs + * + * @return string Name of the namespace (personal, other, shared) + */ + public function get_namespace() + { + return $this->storage->get_namespace(); + } + + + /** + * Getter for the top-end calendar folder name (not the entire path) + * + * @return string Name of this calendar + */ + public function get_foldername() + { + $parts = explode('/', $this->imap_folder); + return rcube_charset::convert(end($parts), 'UTF7-IMAP'); + } + + /** + * Return color to display this calendar + */ + public function get_color() + { + // color is defined in folder METADATA + if ($color = $this->storage->get_color()) { + return $color; + } + + // calendar color is stored in user prefs (temporary solution) + $prefs = $this->cal->rc->config->get('kolab_calendars', array()); + + if (!empty($prefs[$this->id]) && !empty($prefs[$this->id]['color'])) + return $prefs[$this->id]['color']; + + return 'cc0000'; + } + + /** + * Return the corresponding kolab_storage_folder instance + */ + public function get_folder() + { + return $this->storage; + } + + + /** + * Getter for a single event object + */ + public function get_event($id) + { + // directly access storage object + if (!$this->events[$id] && ($record = $this->storage->get_object($id))) + $this->events[$id] = $this->_to_rcube_event($record); + + // event not found, maybe a recurring instance is requested + if (!$this->events[$id]) { + $master_id = preg_replace('/-\d+$/', '', $id); + if ($master_id != $id && ($record = $this->storage->get_object($master_id))) + $this->events[$master_id] = $this->_to_rcube_event($record); + + if (($master = $this->events[$master_id]) && $master['recurrence']) { + $this->_get_recurring_events($record, $master['start'], null, $id); + } + } + + return $this->events[$id]; + } + + + /** + * @param integer Event's new start (unix timestamp) + * @param integer Event's new end (unix timestamp) + * @param string Search query (optional) + * @param boolean Include virtual events (optional) + * @param array Additional parameters to query storage + * @return array A list of event records + */ + public function list_events($start, $end, $search = null, $virtual = 1, $query = array()) + { + // convert to DateTime for comparisons + $start = new DateTime('@'.$start); + $end = new DateTime('@'.$end); + + // query Kolab storage + $query[] = array('dtstart', '<=', $end); + $query[] = array('dtend', '>=', $start); + + if (!empty($search)) { + $search = mb_strtolower($search); + foreach (rcube_utils::normalize_string($search, true) as $word) { + $query[] = array('words', 'LIKE', $word); + } + } + + $events = array(); + foreach ((array)$this->storage->select($query) as $record) { + $event = $this->_to_rcube_event($record); + $this->events[$event['id']] = $event; + + // remember seen categories + if ($event['categories']) + $this->categories[$event['categories']]++; + + // filter events by search query + if (!empty($search)) { + $hit = false; + foreach ($this->search_fields as $col) { + $sval = is_array($event[$col]) ? self::_complex2string($event[$col]) : $event[$col]; + if (empty($sval)) + continue; + + // do a simple substring matching (to be improved) + $val = mb_strtolower($sval); + if (strpos($val, $search) !== false) { + $hit = true; + break; + } + } + + if (!$hit) // skip this event if not match with search term + continue; + } + + // list events in requested time window + if ($event['start'] <= $end && $event['end'] >= $start) { + unset($event['_attendees']); + $add = true; + + // skip the first instance of a recurring event if listed in exdate + if ($virtual && !empty($event['recurrence']['EXDATE'])) { + $event_date = $event['start']->format('Ymd'); + foreach ($event['recurrence']['EXDATE'] as $exdate) { + if ($exdate->format('Ymd') == $event_date) { + $add = false; + break; + } + } + } + + if ($add) + $events[] = $event; + } + + // resolve recurring events + if ($record['recurrence'] && $virtual == 1) { + $events = array_merge($events, $this->_get_recurring_events($record, $start, $end)); + } + } + + return $events; + } + + + /** + * Create a new event record + * + * @see calendar_driver::new_event() + * + * @return mixed The created record ID on success, False on error + */ + public function insert_event($event) + { + if (!is_array($event)) + return false; + + //generate new event from RC input + $object = $this->_from_rcube_event($event); + $saved = $this->storage->save($object, 'event'); + + if (!$saved) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Error saving event object to Kolab server"), + true, false); + $saved = false; + } + else { + $event['id'] = $event['uid']; + $this->events[$event['uid']] = $this->_to_rcube_event($object); + } + + return $saved; + } + + /** + * Update a specific event record + * + * @see calendar_driver::new_event() + * @return boolean True on success, False on error + */ + + public function update_event($event, $exception_id = null) + { + $updated = false; + $old = $this->storage->get_object($event['id']); + if (!$old || PEAR::isError($old)) + return false; + + $old['recurrence'] = ''; # clear old field, could have been removed in new, too + $object = $this->_from_rcube_event($event, $old); + $saved = $this->storage->save($object, 'event', $event['id']); + + if (!$saved) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Error saving event object to Kolab server"), + true, false); + } + else { + $updated = true; + $this->events[$event['id']] = $this->_to_rcube_event($object); + + // refresh local cache with recurring instances + if ($exception_id) { + $this->_get_recurring_events($object, $event['start'], $event['end'], $exception_id); + } + } + + return $updated; + } + + /** + * Delete an event record + * + * @see calendar_driver::remove_event() + * @return boolean True on success, False on error + */ + public function delete_event($event, $force = true) + { + $deleted = $this->storage->delete($event['id'], $force); + + if (!$deleted) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Error deleting event object from Kolab server"), + true, false); + } + + return $deleted; + } + + /** + * Restore deleted event record + * + * @see calendar_driver::undelete_event() + * @return boolean True on success, False on error + */ + public function restore_event($event) + { + if ($this->storage->undelete($event['id'])) { + return true; + } + else { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Error undeleting the event object $event[id] from the Kolab server"), + true, false); + } + + return false; + } + + + /** + * Create instances of a recurring event + * + * @param array Hash array with event properties + * @param object DateTime Start date of the recurrence window + * @param object DateTime End date of the recurrence window + * @param string ID of a specific recurring event instance + * @return array List of recurring event instances + */ + public function _get_recurring_events($event, $start, $end = null, $event_id = null) + { + $object = $event['_formatobj']; + if (!$object) { + $rec = $this->storage->get_object($event['id']); + $object = $rec['_formatobj']; + } + if (!is_object($object)) + return array(); + + // determine a reasonable end date if none given + if (!$end) { + switch ($event['recurrence']['FREQ']) { + case 'YEARLY': $intvl = 'P100Y'; break; + case 'MONTHLY': $intvl = 'P20Y'; break; + default: $intvl = 'P10Y'; break; + } + + $end = clone $event['start']; + $end->add(new DateInterval($intvl)); + } + + // add recurrence exceptions to output + $i = 0; + $events = array(); + $exdates = array(); + $futuredata = array(); + if (is_array($event['recurrence']['EXCEPTIONS'])) { + // copy the recurrence rule from the master event (to be used in the UI) + $recurrence_rule = $event['recurrence']; + unset($recurrence_rule['EXCEPTIONS'], $recurrence_rule['EXDATE']); + + foreach ($event['recurrence']['EXCEPTIONS'] as $exception) { + $rec_event = $this->_to_rcube_event($exception); + $rec_event['id'] = $event['uid'] . '-' . ++$i; + $rec_event['recurrence_id'] = $event['uid']; + $rec_event['recurrence'] = $recurrence_rule; + $rec_event['_instance'] = $i; + $rec_event['isexception'] = 1; + $events[] = $rec_event; + + // found the specifically requested instance, exiting... + if ($rec_event['id'] == $event_id) { + $this->events[$rec_event['id']] = $rec_event; + return $events; + } + + // remember this exception's date + $exdate = $rec_event['start']->format('Y-m-d'); + $exdates[$exdate] = $rec_event['id']; + if ($rec_event['thisandfuture']) { + $futuredata[$exdate] = $rec_event; + } + } + } + + // use libkolab to compute recurring events + if (class_exists('kolabcalendaring')) { + $recurrence = new kolab_date_recurrence($object); + } + else { + // fallback to local recurrence implementation + require_once($this->cal->home . '/lib/calendar_recurrence.php'); + $recurrence = new calendar_recurrence($this->cal, $event); + } + + while ($next_event = $recurrence->next_instance()) { + // skip if there's an exception at this date + $datestr = $next_event['start']->format('Y-m-d'); + if ($exdates[$datestr]) { + // use this event data for future recurring instances + if ($futuredata[$datestr]) + $overlay_data = $futuredata[$datestr]; + continue; + } + + // add to output if in range + $rec_id = $event['uid'] . '-' . ++$i; + if (($next_event['start'] <= $end && $next_event['end'] >= $start) || ($event_id && $rec_id == $event_id)) { + $rec_event = $this->_to_rcube_event($next_event); + + if ($overlay_data) // copy data from a 'this-and-future' exception + $this->_merge_event_data($rec_event, $overlay_data); + + $rec_event['id'] = $rec_id; + $rec_event['recurrence_id'] = $event['uid']; + $rec_event['_instance'] = $i; + unset($rec_event['_attendees']); + $events[] = $rec_event; + + if ($rec_id == $event_id) { + $this->events[$rec_id] = $rec_event; + break; + } + } + else if ($next_event['start'] > $end) // stop loop if out of range + break; + + // avoid endless recursion loops + if ($i > 1000) + break; + } + + return $events; + } + + /** + * Merge certain properties from the overlay event to the base event object + * + * @param array The event object to be altered + * @param array The overlay event object to be merged over $event + */ + private function _merge_event_data(&$event, $overlay) + { + static $forbidden = array('id','uid','created','changed','recurrence','organizer','attendees','sequence'); + + foreach ($overlay as $prop => $value) { + // adjust time of the recurring event instance + if ($prop == 'start' || $prop == 'end') { + if (is_object($event[$prop]) && is_a($event[$prop], 'DateTime')) + $event[$prop]->setTime($value->format('G'), intval($value->format('i')), intval($value->format('s'))); + } + else if ($prop[0] != '_' && !in_array($prop, $forbidden)) + $event[$prop] = $value; + } + } + + /** + * Convert from Kolab_Format to internal representation + */ + private function _to_rcube_event($record) + { + $record['id'] = $record['uid']; + $record['calendar'] = $this->id; +/* + // convert from DateTime to unix timestamp + if (is_a($record['start'], 'DateTime')) + $record['start'] = $record['start']->format('U'); + if (is_a($record['end'], 'DateTime')) + $record['end'] = $record['end']->format('U'); +*/ + // all-day events go from 12:00 - 13:00 + if ($record['end'] <= $record['start'] && $record['allday']) { + $record['end'] = clone $record['start']; + $record['end']->add(new DateInterval('PT1H')); + } + + if (!empty($record['_attachments'])) { + foreach ($record['_attachments'] as $key => $attachment) { + if ($attachment !== false) { + if (!$attachment['name']) + $attachment['name'] = $key; + + unset($attachment['path'], $attachment['content']); + $attachments[] = $attachment; + } + } + + $record['attachments'] = $attachments; + } + + // Roundcube only supports one category assignment + if (is_array($record['categories'])) + $record['categories'] = $record['categories'][0]; + + // remove empty recurrence array + if (empty($record['recurrence'])) + unset($record['recurrence']); + + // remove internals + unset($record['_mailbox'], $record['_msguid'], $record['_formatobj'], $record['_attachments']); + + return $record; + } + + /** + * Convert the given event record into a data structure that can be passed to Kolab_Storage backend for saving + * (opposite of self::_to_rcube_event()) + */ + private function _from_rcube_event($event, $old = array()) + { + // in kolab_storage attachments are indexed by content-id + $event['_attachments'] = array(); + if (is_array($event['attachments'])) { + foreach ($event['attachments'] as $attachment) { + $key = null; + // Roundcube ID has nothing to do with the storage ID, remove it + if ($attachment['content']) { + unset($attachment['id']); + } + else { + foreach ((array)$old['_attachments'] as $cid => $oldatt) { + if ($attachment['id'] == $oldatt['id']) + $key = $cid; + } + } + + // flagged for deletion => set to false + if ($attachment['_deleted']) { + $event['_attachments'][$key] = false; + } + // replace existing entry + else if ($key) { + $event['_attachments'][$key] = $attachment; + } + // append as new attachment + else { + $event['_attachments'][] = $attachment; + } + } + + unset($event['attachments']); + } + + // set current user as ORGANIZER + $identity = $this->cal->rc->user->get_identity(); + if (empty($event['attendees']) && $identity['email']) + $event['attendees'] = array(array('role' => 'ORGANIZER', 'name' => $identity['name'], 'email' => $identity['email'])); + + $event['_owner'] = $identity['email']; + + // remove some internal properties which should not be saved + unset($event['_savemode'], $event['_fromcalendar'], $event['_identity']); + + // copy meta data (starting with _) from old object + foreach ((array)$old as $key => $val) { + if (!isset($event[$key]) && $key[0] == '_') + $event[$key] = $val; + } + + return $event; + } + + /** + * Convert a complex event attribute to a string value + */ + private static function _complex2string($prop) + { + static $ignorekeys = array('role','status','rsvp'); + + $out = ''; + if (is_array($prop)) { + foreach ($prop as $key => $val) { + if (is_numeric($key)) { + $out .= self::_complex2string($val); + } + else if (!in_array($key, $ignorekeys)) { + $out .= $val . ' '; + } + } + } + else if (is_string($prop) || is_numeric($prop)) { + $out .= $prop . ' '; + } + + return rtrim($out); + } + +} diff --git a/drivers/kolab/kolab_driver.php b/drivers/kolab/kolab_driver.php new file mode 100644 index 0000000..516452f --- /dev/null +++ b/drivers/kolab/kolab_driver.php @@ -0,0 +1,1229 @@ + + * @author Aleksander Machniak + * + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +require_once(dirname(__FILE__) . '/kolab_calendar.php'); + +class kolab_driver extends calendar_driver +{ + // features this backend supports + public $alarms = true; + public $attendees = true; + public $freebusy = true; + public $attachments = true; + public $undelete = true; + public $alarm_types = array('DISPLAY'); + public $categoriesimmutable = true; + + private $rc; + private $cal; + private $calendars; + private $has_writeable = false; + private $freebusy_trigger = false; + + /** + * Default constructor + */ + public function __construct($cal) + { + $this->cal = $cal; + $this->rc = $cal->rc; + $this->_read_calendars(); + + $this->cal->register_action('push-freebusy', array($this, 'push_freebusy')); + $this->cal->register_action('calendar-acl', array($this, 'calendar_acl')); + + $this->freebusy_trigger = $this->rc->config->get('calendar_freebusy_trigger', false); + + if (kolab_storage::$version == '2.0') { + $this->alarm_types = array('DISPLAY'); + $this->alarm_absolute = false; + } + } + + + /** + * Read available calendars from server + */ + private function _read_calendars() + { + // already read sources + if (isset($this->calendars)) + return $this->calendars; + + // get all folders that have "event" type, sorted by namespace/name + $folders = kolab_storage::sort_folders(kolab_storage::get_folders('event')); + $this->calendars = array(); + + foreach ($folders as $folder) { + $calendar = new kolab_calendar($folder->name, $this->cal); + $this->calendars[$calendar->id] = $calendar; + if (!$calendar->readonly) + $this->has_writeable = true; + } + + return $this->calendars; + } + + + /** + * Get a list of available calendars from this source + * + * @param bool $active Return only active calendars + * @param bool $personal Return only personal calendars + * + * @return array List of calendars + */ + public function list_calendars($active = false, $personal = false) + { + // attempt to create a default calendar for this user + if (!$this->has_writeable) { + if ($this->create_calendar(array('name' => 'Calendar', 'color' => 'cc0000'))) { + unset($this->calendars); + $this->_read_calendars(); + } + } + + $calendars = $this->filter_calendars(false, $active, $personal); + $names = array(); + + foreach ($calendars as $id => $cal) { + $name = kolab_storage::folder_displayname($cal->get_name(), $names); + + $calendars[$id] = array( + 'id' => $cal->id, + 'name' => $name, + 'editname' => $cal->get_foldername(), + 'color' => $cal->get_color(), + 'readonly' => $cal->readonly, + 'showalarms' => $cal->alarms, + 'class_name' => $cal->get_namespace(), + 'default' => $cal->storage->default, + 'active' => $cal->storage->is_active(), + 'owner' => $cal->get_owner(), + ); + } + + return $calendars; + } + + + /** + * Get list of calendars according to specified filters + * + * @param bool $writeable Return only writeable calendars + * @param bool $active Return only active calendars + * @param bool $personal Return only personal calendars + * + * @return array List of calendars + */ + protected function filter_calendars($writeable = false, $active = false, $personal = false) + { + $calendars = array(); + + $plugin = $this->rc->plugins->exec_hook('calendar_list_filter', array( + 'list' => $this->calendars, 'calendars' => $calendars, + 'writeable' => $writeable, 'active' => $active, 'personal' => $personal, + )); + + if ($plugin['abort']) { + return $plugin['calendars']; + } + + foreach ($this->calendars as $cal) { + if (!$cal->ready) { + continue; + } + if ($writeable && $cal->readonly) { + continue; + } + if ($active && !$cal->storage->is_active()) { + continue; + } + if ($personal && $cal->get_namespace() != 'personal') { + continue; + } + $calendars[$cal->id] = $cal; + } + + return $calendars; + } + + /** + * Create a new calendar assigned to the current user + * + * @param array Hash array with calendar properties + * name: Calendar name + * color: The color of the calendar + * @return mixed ID of the calendar on success, False on error + */ + public function create_calendar($prop) + { + $prop['type'] = 'event'; + $prop['active'] = true; + $prop['subscribed'] = true; + $folder = kolab_storage::folder_update($prop); + + if ($folder === false) { + $this->last_error = $this->cal->gettext(kolab_storage::$last_error); + return false; + } + + // create ID + $id = kolab_storage::folder_id($folder); + + // save color in user prefs (temp. solution) + $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', array()); + + if (isset($prop['color'])) + $prefs['kolab_calendars'][$id]['color'] = $prop['color']; + if (isset($prop['showalarms'])) + $prefs['kolab_calendars'][$id]['showalarms'] = $prop['showalarms'] ? true : false; + + if ($prefs['kolab_calendars'][$id]) + $this->rc->user->save_prefs($prefs); + + return $id; + } + + + /** + * Update properties of an existing calendar + * + * @see calendar_driver::edit_calendar() + */ + public function edit_calendar($prop) + { + if ($prop['id'] && ($cal = $this->calendars[$prop['id']])) { + $prop['oldname'] = $cal->get_realname(); + $newfolder = kolab_storage::folder_update($prop); + + if ($newfolder === false) { + $this->last_error = $this->cal->gettext(kolab_storage::$last_error); + return false; + } + + // create ID + $id = kolab_storage::folder_id($newfolder); + + // fallback to local prefs + $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', array()); + unset($prefs['kolab_calendars'][$prop['id']]); + + if (isset($prop['color'])) + $prefs['kolab_calendars'][$id]['color'] = $prop['color']; + if (isset($prop['showalarms'])) + $prefs['kolab_calendars'][$id]['showalarms'] = $prop['showalarms'] ? true : false; + + if ($prefs['kolab_calendars'][$id]) + $this->rc->user->save_prefs($prefs); + + return true; + } + + return false; + } + + + /** + * Set active/subscribed state of a calendar + * + * @see calendar_driver::subscribe_calendar() + */ + public function subscribe_calendar($prop) + { + if ($prop['id'] && ($cal = $this->calendars[$prop['id']])) { + return $cal->storage->activate($prop['active']); + } + + return false; + } + + + /** + * Delete the given calendar with all its contents + * + * @see calendar_driver::remove_calendar() + */ + public function remove_calendar($prop) + { + if ($prop['id'] && ($cal = $this->calendars[$prop['id']])) { + $folder = $cal->get_realname(); + if (kolab_storage::folder_delete($folder)) { + // remove color in user prefs (temp. solution) + $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', array()); + unset($prefs['kolab_calendars'][$prop['id']]); + + $this->rc->user->save_prefs($prefs); + return true; + } + else + $this->last_error = kolab_storage::$last_error; + } + + return false; + } + + + /** + * Fetch a single event + * + * @see calendar_driver::get_event() + * @return array Hash array with event properties, false if not found + */ + public function get_event($event, $writeable = false, $active = false, $personal = false) + { + if (is_array($event)) { + $id = $event['id'] ? $event['id'] : $event['uid']; + $cal = $event['calendar']; + } + else { + $id = $event; + } + + if ($cal) { + if ($storage = $this->calendars[$cal]) { + return $storage->get_event($id); + } + } + // iterate over all calendar folders and search for the event ID + else { + foreach ($this->filter_calendars($writeable, $active, $personal) as $calendar) { + if ($result = $calendar->get_event($id)) { + return $result; + } + } + } + + return false; + } + + /** + * Add a single event to the database + * + * @see calendar_driver::new_event() + */ + public function new_event($event) + { + if (!$this->validate($event)) + return false; + + $cid = $event['calendar'] ? $event['calendar'] : reset(array_keys($this->calendars)); + if ($storage = $this->calendars[$cid]) { + // handle attachments to add + if (!empty($event['attachments'])) { + foreach ($event['attachments'] as $idx => $attachment) { + // we'll read file contacts into memory, Horde/Kolab classes does the same + // So we cannot save memory, rcube_imap class can do this better + $event['attachments'][$idx]['content'] = $attachment['data'] ? $attachment['data'] : file_get_contents($attachment['path']); + } + } + + $success = $storage->insert_event($event); + + if ($success && $this->freebusy_trigger) + $this->rc->output->command('plugin.ping_url', array('action' => 'calendar/push-freebusy', 'source' => $storage->id)); + + return $success; + } + + return false; + } + + /** + * Update an event entry with the given data + * + * @see calendar_driver::new_event() + * @return boolean True on success, False on error + */ + public function edit_event($event) + { + return $this->update_event($event); + } + + /** + * Move a single event + * + * @see calendar_driver::move_event() + * @return boolean True on success, False on error + */ + public function move_event($event) + { + if (($storage = $this->calendars[$event['calendar']]) && ($ev = $storage->get_event($event['id']))) { + unset($ev['sequence']); + return $this->update_event($event + $ev); + } + + return false; + } + + /** + * Resize a single event + * + * @see calendar_driver::resize_event() + * @return boolean True on success, False on error + */ + public function resize_event($event) + { + if (($storage = $this->calendars[$event['calendar']]) && ($ev = $storage->get_event($event['id']))) { + unset($ev['sequence']); + return $this->update_event($event + $ev); + } + + return false; + } + + /** + * Remove a single event + * + * @param array Hash array with event properties: + * id: Event identifier + * @param boolean Remove record(s) irreversible (mark as deleted otherwise) + * + * @return boolean True on success, False on error + */ + public function remove_event($event, $force = true) + { + $success = false; + $savemode = $event['_savemode']; + + if (($storage = $this->calendars[$event['calendar']]) && ($event = $storage->get_event($event['id']))) { + $event['_savemode'] = $savemode; + $savemode = 'all'; + $master = $event; + + $this->rc->session->remove('calendar_restore_event_data'); + + // read master if deleting a recurring event + if ($event['recurrence'] || $event['recurrence_id']) { + $master = $event['recurrence_id'] ? $storage->get_event($event['recurrence_id']) : $event; + $savemode = $event['_savemode']; + } + + // removing an exception instance + if ($event['recurrence_id']) { + $i = $event['_instance'] - 1; + if (!empty($master['recurrence']['EXCEPTIONS'][$i])) { + unset($master['recurrence']['EXCEPTIONS'][$i]); + } + } + + switch ($savemode) { + case 'current': + $_SESSION['calendar_restore_event_data'] = $master; + + // removing the first instance => just move to next occurence + if ($master['id'] == $event['id']) { + $recurring = reset($storage->_get_recurring_events($event, $event['start'], null, $event['id'].'-1')); + + // no future instances found: delete the master event (bug #1677) + if (!$recurring['start']) { + $success = $storage->delete_event($master, $force); + break; + } + + $master['start'] = $recurring['start']; + $master['end'] = $recurring['end']; + if ($master['recurrence']['COUNT']) + $master['recurrence']['COUNT']--; + } + else { // add exception to master event + $master['recurrence']['EXDATE'][] = $event['start']; + } + $success = $storage->update_event($master); + break; + + case 'future': + if ($master['id'] != $event['id']) { + $_SESSION['calendar_restore_event_data'] = $master; + + // set until-date on master event + $master['recurrence']['UNTIL'] = clone $event['start']; + $master['recurrence']['UNTIL']->sub(new DateInterval('P1D')); + unset($master['recurrence']['COUNT']); + + // if all future instances are deleted, remove recurrence rule entirely (bug #1677) + if ($master['recurrence']['UNTIL']->format('Ymd') == $master['start']->format('Ymd')) + $master['recurrence'] = array(); + + $success = $storage->update_event($master); + break; + } + + default: // 'all' is default + $success = $storage->delete_event($master, $force); + break; + } + } + + if ($success && $this->freebusy_trigger) + $this->rc->output->command('plugin.ping_url', array('action' => 'calendar/push-freebusy', 'source' => $storage->id)); + + return $success; + } + + /** + * Restore a single deleted event + * + * @param array Hash array with event properties: + * id: Event identifier + * @return boolean True on success, False on error + */ + public function restore_event($event) + { + if ($storage = $this->calendars[$event['calendar']]) { + if (!empty($_SESSION['calendar_restore_event_data'])) + $success = $storage->update_event($_SESSION['calendar_restore_event_data']); + else + $success = $storage->restore_event($event); + + if ($success && $this->freebusy_trigger) + $this->rc->output->command('plugin.ping_url', array('action' => 'calendar/push-freebusy', 'source' => $storage->id)); + + return $success; + } + + return false; + } + + /** + * Wrapper to update an event object depending on the given savemode + */ + private function update_event($event) + { + if (!($storage = $this->calendars[$event['calendar']])) + return false; + + // move event to another folder/calendar + if ($event['_fromcalendar'] && $event['_fromcalendar'] != $event['calendar']) { + if (!($fromcalendar = $this->calendars[$event['_fromcalendar']])) + return false; + + if ($event['_savemode'] != 'new') { + if (!$fromcalendar->storage->move($event['id'], $storage->get_realname())) + return false; + + $fromcalendar = $storage; + } + } + else + $fromcalendar = $storage; + + $success = false; + $savemode = 'all'; + $attachments = array(); + $old = $master = $fromcalendar->get_event($event['id']); + + if (!$old || !$old['start']) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Failed to load event object to update: id=" . $event['id']), + true, false); + return false; + } + + // delete existing attachment(s) + if (!empty($event['deleted_attachments'])) { + foreach ($event['deleted_attachments'] as $attachment) { + if (!empty($old['attachments'])) { + foreach ($old['attachments'] as $idx => $att) { + if ($att['id'] == $attachment) { + $old['attachments'][$idx]['_deleted'] = true; + } + } + } + } + unset($event['deleted_attachments']); + } + + // handle attachments to add + if (!empty($event['attachments'])) { + foreach ($event['attachments'] as $attachment) { + // skip entries without content (could be existing ones) + if (!$attachment['data'] && !$attachment['path']) + continue; + + $attachments[] = array( + 'name' => $attachment['name'], + 'mimetype' => $attachment['mimetype'], + 'content' => $attachment['data'], + 'path' => $attachment['path'], + ); + } + } + + $event['attachments'] = array_merge((array)$old['attachments'], $attachments); + + // modify a recurring event, check submitted savemode to do the right things + if ($old['recurrence'] || $old['recurrence_id']) { + $master = $old['recurrence_id'] ? $fromcalendar->get_event($old['recurrence_id']) : $old; + $savemode = $event['_savemode']; + } + + // keep saved exceptions (not submitted by the client) + if ($old['recurrence']['EXDATE']) + $event['recurrence']['EXDATE'] = $old['recurrence']['EXDATE']; + if ($old['recurrence']['EXCEPTIONS']) + $event['recurrence']['EXCEPTIONS'] = $old['recurrence']['EXCEPTIONS']; + + switch ($savemode) { + case 'new': + // save submitted data as new (non-recurring) event + $event['recurrence'] = array(); + $event['uid'] = $this->cal->generate_uid(); + + // copy attachment data to new event + foreach ((array)$event['attachments'] as $idx => $attachment) { + if (!$attachment['data']) + $attachment['data'] = $fromcalendar->get_attachment_body($attachment['id'], $event); + } + + $success = $storage->insert_event($event); + break; + + case 'future': + case 'current': + // recurring instances shall not store recurrence rules + $event['recurrence'] = array(); + $event['thisandfuture'] = $savemode == 'future'; + + // remove some internal properties which should not be saved + unset($event['_savemode'], $event['_fromcalendar'], $event['_identity']); + + // save properties to a recurrence exception instance + if ($old['recurrence_id']) { + $i = $old['_instance'] - 1; + if (!empty($master['recurrence']['EXCEPTIONS'][$i])) { + $master['recurrence']['EXCEPTIONS'][$i] = $event; + $success = $storage->update_event($master, $old['id']); + break; + } + } + + // save as new exception to master event + $master['recurrence']['EXCEPTIONS'][] = $event; + $success = $storage->update_event($master); + break; + + default: // 'all' is default + $event['id'] = $master['id']; + $event['uid'] = $master['uid']; + + // use start date from master but try to be smart on time or duration changes + $old_start_date = $old['start']->format('Y-m-d'); + $old_start_time = $old['allday'] ? '' : $old['start']->format('H:i'); + $old_duration = $old['end']->format('U') - $old['start']->format('U'); + + $new_start_date = $event['start']->format('Y-m-d'); + $new_start_time = $event['allday'] ? '' : $event['start']->format('H:i'); + $new_duration = $event['end']->format('U') - $event['start']->format('U'); + + $diff = $old_start_date != $new_start_date || $old_start_time != $new_start_time || $old_duration != $new_duration; + + // shifted or resized + if ($diff && ($old_start_date == $new_start_date || $old_duration == $new_duration)) { + $event['start'] = $master['start']->add($old['start']->diff($event['start'])); + $event['end'] = clone $event['start']; + $event['end']->add(new DateInterval('PT'.$new_duration.'S')); + + // remove fixed weekday, will be re-set to the new weekday in kolab_calendar::update_event() + if ($old_start_date != $new_start_date) { + if (strlen($event['recurrence']['BYDAY']) == 2) + unset($event['recurrence']['BYDAY']); + if ($old['recurrence']['BYMONTH'] == $old['start']->format('n')) + unset($event['recurrence']['BYMONTH']); + } + } + // dates did not change, use the ones from master + else if ($event['start'] == $old['start'] && $event['end'] == $old['end']) { + $event['start'] = $master['start']; + $event['end'] = $master['end']; + } + + $success = $storage->update_event($event); + break; + } + + if ($success && $this->freebusy_trigger) + $this->rc->output->command('plugin.ping_url', array('action' => 'calendar/push-freebusy', 'source' => $storage->id)); + + return $success; + } + + /** + * Get events from source. + * + * @param integer Event's new start (unix timestamp) + * @param integer Event's new end (unix timestamp) + * @param string Search query (optional) + * @param mixed List of calendar IDs to load events from (either as array or comma-separated string) + * @param boolean Strip virtual events (optional) + * @return array A list of event records + */ + public function load_events($start, $end, $search = null, $calendars = null, $virtual = 1) + { + if ($calendars && is_string($calendars)) + $calendars = explode(',', $calendars); + + $events = $categories = array(); + foreach (array_keys($this->calendars) as $cid) { + if ($calendars && !in_array($cid, $calendars)) + continue; + + $events = array_merge($events, $this->calendars[$cid]->list_events($start, $end, $search, $virtual)); + $categories += $this->calendars[$cid]->categories; + } + + // add new categories to user prefs + $old_categories = $this->rc->config->get('calendar_categories', $this->default_categories); + if ($newcats = array_diff(array_map('strtolower', array_keys($categories)), array_map('strtolower', array_keys($old_categories)))) { + foreach ($newcats as $category) + $old_categories[$category] = ''; // no color set yet + $this->rc->user->save_prefs(array('calendar_categories' => $old_categories)); + } + + return $events; + } + + /** + * Get a list of pending alarms to be displayed to the user + * + * @see calendar_driver::pending_alarms() + */ + public function pending_alarms($time, $calendars = null) + { + $interval = 300; + $time -= $time % 60; + + $slot = $time; + $slot -= $slot % $interval; + + $last = $time - max(60, $this->rc->config->get('refresh_interval', 0)); + $last -= $last % $interval; + + // only check for alerts once in 5 minutes + if ($last == $slot) + return array(); + + if ($calendars && is_string($calendars)) + $calendars = explode(',', $calendars); + + $time = $slot + $interval; + + $events = array(); + $query = array(array('tags', '=', 'x-has-alarms')); + foreach ($this->calendars as $cid => $calendar) { + // skip calendars with alarms disabled + if (!$calendar->alarms || ($calendars && !in_array($cid, $calendars))) + continue; + + foreach ($calendar->list_events($time, $time + 86400 * 365, null, 1, $query) as $e) { + // add to list if alarm is set + $alarm = libcalendaring::get_next_alarm($e); + if ($alarm && $alarm['time'] && $alarm['time'] <= $time && $alarm['action'] == 'DISPLAY') { + $id = $e['id']; + $events[$id] = $e; + $events[$id]['notifyat'] = $alarm['time']; + } + } + } + + // get alarm information stored in local database + if (!empty($events)) { + $event_ids = array_map(array($this->rc->db, 'quote'), array_keys($events)); + $result = $this->rc->db->query(sprintf( + "SELECT * FROM kolab_alarms + WHERE event_id IN (%s) AND user_id=?", + join(',', $event_ids), + $this->rc->db->now() + ), + $this->rc->user->ID + ); + + while ($result && ($e = $this->rc->db->fetch_assoc($result))) { + $dbdata[$e['event_id']] = $e; + } + } + + $alarms = array(); + foreach ($events as $id => $e) { + // skip dismissed + if ($dbdata[$id]['dismissed']) + continue; + + // snooze function may have shifted alarm time + $notifyat = $dbdata[$id]['notifyat'] ? strtotime($dbdata[$id]['notifyat']) : $e['notifyat']; + if ($notifyat <= $time) + $alarms[] = $e; + } + + return $alarms; + } + + /** + * Feedback after showing/sending an alarm notification + * + * @see calendar_driver::dismiss_alarm() + */ + public function dismiss_alarm($event_id, $snooze = 0) + { + // delete old alarm entry + $this->rc->db->query( + "DELETE FROM kolab_alarms + WHERE event_id=? AND user_id=?", + $event_id, + $this->rc->user->ID + ); + + // set new notifyat time or unset if not snoozed + $notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null; + + $query = $this->rc->db->query( + "INSERT INTO kolab_alarms + (event_id, user_id, dismissed, notifyat) + VALUES(?, ?, ?, ?)", + $event_id, + $this->rc->user->ID, + $snooze > 0 ? 0 : 1, + $notifyat + ); + + return $this->rc->db->affected_rows($query); + } + + /** + * List attachments from the given event + */ + public function list_attachments($event) + { + if (!($storage = $this->calendars[$event['calendar']])) + return false; + + $event = $storage->get_event($event['id']); + + return $event['attachments']; + } + + /** + * Get attachment properties + */ + public function get_attachment($id, $event) + { + if (!($storage = $this->calendars[$event['calendar']])) + return false; + + $event = $storage->get_event($event['id']); + + if ($event && !empty($event['attachments'])) { + foreach ($event['attachments'] as $att) { + if ($att['id'] == $id) { + return $att; + } + } + } + + return null; + } + + /** + * Get attachment body + * @see calendar_driver::get_attachment_body() + */ + public function get_attachment_body($id, $event) + { + if (!($cal = $this->calendars[$event['calendar']])) + return false; + + return $cal->storage->get_attachment($event['id'], $id); + } + + /** + * List availabale categories + * The default implementation reads them from config/user prefs + */ + public function list_categories() + { + // FIXME: complete list with categories saved in config objects (KEP:12) + return $this->rc->config->get('calendar_categories', $this->default_categories); + } + + /** + * Fetch free/busy information from a person within the given range + */ + public function get_freebusy_list($email, $start, $end) + { + require_once('HTTP/Request2.php'); + + if (empty($email)/* || $end < time()*/) + return false; + + // map vcalendar fbtypes to internal values + $fbtypemap = array( + 'FREE' => calendar::FREEBUSY_FREE, + 'BUSY-TENTATIVE' => calendar::FREEBUSY_TENTATIVE, + 'X-OUT-OF-OFFICE' => calendar::FREEBUSY_OOF, + 'OOF' => calendar::FREEBUSY_OOF); + + // ask kolab server first + try { + $rcmail = rcube::get_instance(); + $request = new HTTP_Request2(kolab_storage::get_freebusy_url($email)); + $request->setConfig(array( + 'store_body' => true, + 'follow_redirects' => true, + 'ssl_verify_peer' => $rcmail->config->get('kolab_ssl_verify_peer', true), + )); + + $response = $request->send(); + + // authentication required + if ($response->getStatus() == 401) { + $request->setAuth($this->rc->user->get_username(), $this->rc->decrypt($_SESSION['password'])); + $response = $request->send(); + } + + if ($response->getStatus() == 200) + $fbdata = $response->getBody(); + + unset($request, $response); + } + catch (Exception $e) { + PEAR::raiseError("Error fetching free/busy information: " . $e->getMessage()); + } + + // get free-busy url from contacts + if (!$fbdata) { + $fburl = null; + foreach ((array)$this->rc->config->get('autocomplete_addressbooks', 'sql') as $book) { + $abook = $this->rc->get_address_book($book); + + if ($result = $abook->search(array('email'), $email, true, true, true/*, 'freebusyurl'*/)) { + while ($contact = $result->iterate()) { + if ($fburl = $contact['freebusyurl']) { + $fbdata = @file_get_contents($fburl); + break; + } + } + } + + if ($fbdata) + break; + } + } + + // parse free-busy information using Horde classes + if ($fbdata) { + $fbcal = $this->cal->get_ical()->get_parser(); + $fbcal->parsevCalendar($fbdata); + if ($fb = $fbcal->findComponent('vfreebusy')) { + $result = array(); + $params = $fb->getExtraParams(); + foreach ($fb->getBusyPeriods() as $from => $to) { + if ($to == null) // no information, assume free + break; + $type = $params[$from]['FBTYPE']; + $result[] = array($from, $to, isset($fbtypemap[$type]) ? $fbtypemap[$type] : calendar::FREEBUSY_BUSY); + } + + // we take 'dummy' free-busy lists as "unknown" + if (empty($result) && ($comment = $fb->getAttribute('COMMENT')) && stripos($comment, 'dummy')) + return false; + + // set period from $start till the begin of the free-busy information as 'unknown' + if (($fbstart = $fb->getStart()) && $start < $fbstart) { + array_unshift($result, array($start, $fbstart, calendar::FREEBUSY_UNKNOWN)); + } + // pad period till $end with status 'unknown' + if (($fbend = $fb->getEnd()) && $fbend < $end) { + $result[] = array($fbend, $end, calendar::FREEBUSY_UNKNOWN); + } + + return $result; + } + } + + return false; + } + + /** + * Handler to push folder triggers when sent from client. + * Used to push free-busy changes asynchronously after updating an event + */ + public function push_freebusy() + { + // make shure triggering completes + set_time_limit(0); + ignore_user_abort(true); + + $cal = get_input_value('source', RCUBE_INPUT_GPC); + if (!($cal = $this->calendars[$cal])) + return false; + + // trigger updates on folder + $trigger = $cal->storage->trigger(); + if (is_object($trigger) && is_a($trigger, 'PEAR_Error')) { + rcube::raise_error(array( + 'code' => 900, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Failed triggering folder. Error was " . $trigger->getMessage()), + true, false); + } + + exit; + } + + /** + * Callback function to produce driver-specific calendar create/edit form + * + * @param string Request action 'form-edit|form-new' + * @param array Calendar properties (e.g. id, color) + * @param array Edit form fields + * + * @return string HTML content of the form + */ + public function calendar_form($action, $calendar, $formfields) + { + if ($calendar['id'] && ($cal = $this->calendars[$calendar['id']])) { + $folder = $cal->get_realname(); // UTF7 + $color = $cal->get_color(); + } + else { + $folder = ''; + $color = ''; + } + + $hidden_fields[] = array('name' => 'oldname', 'value' => $folder); + + $storage = $this->rc->get_storage(); + $delim = $storage->get_hierarchy_delimiter(); + $form = array(); + + if (strlen($folder)) { + $path_imap = explode($delim, $folder); + array_pop($path_imap); // pop off name part + $path_imap = implode($path_imap, $delim); + + $options = $storage->folder_info($folder); + } + else { + $path_imap = ''; + } + + // General tab + $form['props'] = array( + 'name' => $this->rc->gettext('properties'), + ); + + // Disable folder name input + if (!empty($options) && ($options['norename'] || $options['protected'])) { + $input_name = new html_hiddenfield(array('name' => 'name', 'id' => 'calendar-name')); + $formfields['name']['value'] = Q(str_replace($delim, ' » ', kolab_storage::object_name($folder))) + . $input_name->show($folder); + } + + // calendar name (default field) + $form['props']['fieldsets']['location'] = array( + 'name' => $this->rc->gettext('location'), + 'content' => array( + 'name' => $formfields['name'] + ), + ); + + if (!empty($options) && ($options['norename'] || $options['protected'])) { + // prevent user from moving folder + $hidden_fields[] = array('name' => 'parent', 'value' => $path_imap); + } + else { + $select = kolab_storage::folder_selector('event', array('name' => 'parent'), $folder); + $form['props']['fieldsets']['location']['content']['path'] = array( + 'label' => $this->cal->gettext('parentcalendar'), + 'value' => $select->show(strlen($folder) ? $path_imap : ''), + ); + } + + // calendar color (default field) + $form['props']['fieldsets']['settings'] = array( + 'name' => $this->rc->gettext('settings'), + 'content' => array( + 'color' => $formfields['color'], + 'showalarms' => $formfields['showalarms'], + ), + ); + + + if ($action != 'form-new') { + $form['sharing'] = array( + 'name' => Q($this->cal->gettext('tabsharing')), + 'content' => html::tag('iframe', array( + 'src' => $this->cal->rc->url(array('_action' => 'calendar-acl', 'id' => $calendar['id'], 'framed' => 1)), + 'width' => '100%', + 'height' => 350, + 'border' => 0, + 'style' => 'border:0'), + ''), + ); + } + + $this->form_html = ''; + if (is_array($hidden_fields)) { + foreach ($hidden_fields as $field) { + $hiddenfield = new html_hiddenfield($field); + $this->form_html .= $hiddenfield->show() . "\n"; + } + } + + // Create form output + foreach ($form as $tab) { + if (!empty($tab['fieldsets']) && is_array($tab['fieldsets'])) { + $content = ''; + foreach ($tab['fieldsets'] as $fieldset) { + $subcontent = $this->get_form_part($fieldset); + if ($subcontent) { + $content .= html::tag('fieldset', null, html::tag('legend', null, Q($fieldset['name'])) . $subcontent) ."\n"; + } + } + } + else { + $content = $this->get_form_part($tab); + } + + if ($content) { + $this->form_html .= html::tag('fieldset', null, html::tag('legend', null, Q($tab['name'])) . $content) ."\n"; + } + } + + // Parse form template for skin-dependent stuff + $this->rc->output->add_handler('calendarform', array($this, 'calendar_form_html')); + return $this->rc->output->parse('calendar.kolabform', false, false); + } + + /** + * Handler for template object + */ + public function calendar_form_html() + { + return $this->form_html; + } + + /** + * Helper function used in calendar_form_content(). Creates a part of the form. + */ + private function get_form_part($form) + { + $content = ''; + + if (is_array($form['content']) && !empty($form['content'])) { + $table = new html_table(array('cols' => 2)); + foreach ($form['content'] as $col => $colprop) { + $colprop['id'] = '_'.$col; + $label = !empty($colprop['label']) ? $colprop['label'] : rcube_label($col); + + $table->add('title', sprintf('', $colprop['id'], Q($label))); + $table->add(null, $colprop['value']); + } + $content = $table->show(); + } + else { + $content = $form['content']; + } + + return $content; + } + + + /** + * Handler to render ACL form for a calendar folder + */ + public function calendar_acl() + { + $this->rc->output->add_handler('folderacl', array($this, 'calendar_acl_form')); + $this->rc->output->send('calendar.kolabacl'); + } + + /** + * Handler for ACL form template object + */ + public function calendar_acl_form() + { + $calid = get_input_value('_id', RCUBE_INPUT_GPC); + if ($calid && ($cal = $this->calendars[$calid])) { + $folder = $cal->get_realname(); // UTF7 + $color = $cal->get_color(); + } + else { + $folder = ''; + $color = ''; + } + + $storage = $this->rc->get_storage(); + $delim = $storage->get_hierarchy_delimiter(); + $form = array(); + + if (strlen($folder)) { + $path_imap = explode($delim, $folder); + array_pop($path_imap); // pop off name part + $path_imap = implode($path_imap, $delim); + + $options = $storage->folder_info($folder); + + // Allow plugins to modify the form content (e.g. with ACL form) + $plugin = $this->rc->plugins->exec_hook('calendar_form_kolab', + array('form' => $form, 'options' => $options, 'name' => $folder)); + } + + if (!$plugin['form']['sharing']['content']) + $plugin['form']['sharing']['content'] = html::div('hint', $this->cal->gettext('aclnorights')); + + return $plugin['form']['sharing']['content']; + } + + + /** + * Return a (limited) list of color values to be used for calendar and category coloring + * + * @return mixed List for colors as hex values or false if no presets should be shown + */ + public function get_color_values() + { + // selection from http://msdn.microsoft.com/en-us/library/aa358802%28v=VS.85%29.aspx + return array('000000','006400','2F4F4F','800000','808000','008000', + '008080','000080','800080','4B0082','191970','8B0000','008B8B', + '00008B','8B008B','556B2F','8B4513','228B22','6B8E23','2E8B57', + 'B8860B','483D8B','A0522D','0000CD','A52A2A','00CED1','696969', + '20B2AA','9400D3','B22222','C71585','3CB371','D2691E','DC143C', + 'DAA520','00FA9A','4682B4','7CFC00','9932CC','FF0000','FF4500', + 'FF8C00','FFA500','FFD700','FFFF00','9ACD32','32CD32','00FF00', + '00FF7F','00FFFF','5F9EA0','00BFFF','0000FF','FF00FF','808080', + '708090','CD853F','8A2BE2','778899','FF1493','48D1CC','1E90FF', + '40E0D0','4169E1','6A5ACD','BDB76B','BA55D3','CD5C5C','ADFF2F', + '66CDAA','FF6347','8FBC8B','DA70D6','BC8F8F','9370DB','DB7093', + 'FF7F50','6495ED','A9A9A9','F4A460','7B68EE','D2B48C','E9967A', + 'DEB887','FF69B4','FA8072','F08080','EE82EE','87CEEB','FFA07A', + 'F0E68C','DDA0DD','90EE90','7FFFD4','C0C0C0','87CEFA','B0C4DE', + '98FB98','ADD8E6','B0E0E6','D8BFD8','EEE8AA','AFEEEE','D3D3D3', + 'FFDEAD'); + } + +} diff --git a/lib/Horde_Date.php b/lib/Horde_Date.php new file mode 100644 index 0000000..9197f84 --- /dev/null +++ b/lib/Horde_Date.php @@ -0,0 +1,1304 @@ + self::MASK_YEAR, + 'month' => self::MASK_MONTH, + 'mday' => self::MASK_DAY, + 'hour' => self::MASK_HOUR, + 'min' => self::MASK_MINUTE, + 'sec' => self::MASK_SECOND, + ); + + protected $_formatCache = array(); + + /** + * Builds a new date object. If $date contains date parts, use them to + * initialize the object. + * + * Recognized formats: + * - arrays with keys 'year', 'month', 'mday', 'day' + * 'hour', 'min', 'minute', 'sec' + * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec' + * - yyyy-mm-dd hh:mm:ss + * - yyyymmddhhmmss + * - yyyymmddThhmmssZ + * - yyyymmdd (might conflict with unix timestamps between 31 Oct 1966 and + * 03 Mar 1973) + * - unix timestamps + * - anything parsed by strtotime()/DateTime. + * + * @throws Horde_Date_Exception + */ + public function __construct($date = null, $timezone = null) + { + if (!self::$_supportedSpecs) { + self::$_supportedSpecs = self::$_defaultSpecs; + if (function_exists('nl_langinfo')) { + self::$_supportedSpecs .= 'bBpxX'; + } + } + + if (func_num_args() > 2) { + // Handle args in order: year month day hour min sec tz + $this->_initializeFromArgs(func_get_args()); + return; + } + + $this->_initializeTimezone($timezone); + + if (is_null($date)) { + return; + } + + if (is_string($date)) { + $date = trim($date, '"'); + } + + if (is_object($date)) { + $this->_initializeFromObject($date); + } elseif (is_array($date)) { + $this->_initializeFromArray($date); + } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})(?:\.\d+)?(Z?)$/', $date, $parts)) { + $this->_year = (int)$parts[1]; + $this->_month = (int)$parts[2]; + $this->_mday = (int)$parts[3]; + $this->_hour = (int)$parts[4]; + $this->_min = (int)$parts[5]; + $this->_sec = (int)$parts[6]; + if ($parts[7]) { + $this->_initializeTimezone('UTC'); + } + } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $date, $parts) && + $parts[2] > 0 && $parts[2] <= 12 && + $parts[3] > 0 && $parts[3] <= 31) { + $this->_year = (int)$parts[1]; + $this->_month = (int)$parts[2]; + $this->_mday = (int)$parts[3]; + $this->_hour = $this->_min = $this->_sec = 0; + } elseif ((string)(int)$date == $date) { + // Try as a timestamp. + $parts = @getdate($date); + if ($parts) { + $this->_year = $parts['year']; + $this->_month = $parts['mon']; + $this->_mday = $parts['mday']; + $this->_hour = $parts['hours']; + $this->_min = $parts['minutes']; + $this->_sec = $parts['seconds']; + } + } else { + // Use date_create() so we can catch errors with PHP 5.2. Use + // "new DateTime() once we require 5.3. + $parsed = date_create($date); + if (!$parsed) { + throw new Horde_Date_Exception(sprintf(Horde_Date_Translation::t("Failed to parse time string (%s)"), $date)); + } + $parsed->setTimezone(new DateTimeZone(date_default_timezone_get())); + $this->_year = (int)$parsed->format('Y'); + $this->_month = (int)$parsed->format('m'); + $this->_mday = (int)$parsed->format('d'); + $this->_hour = (int)$parsed->format('H'); + $this->_min = (int)$parsed->format('i'); + $this->_sec = (int)$parsed->format('s'); + $this->_initializeTimezone(date_default_timezone_get()); + } + } + + /** + * Returns a simple string representation of the date object + * + * @return string This object converted to a string. + */ + public function __toString() + { + try { + return $this->format($this->_defaultFormat); + } catch (Exception $e) { + return ''; + } + } + + /** + * Returns a DateTime object representing this object. + * + * @return DateTime + */ + public function toDateTime() + { + $date = new DateTime(null, new DateTimeZone($this->_timezone)); + $date->setDate($this->_year, $this->_month, $this->_mday); + $date->setTime($this->_hour, $this->_min, $this->_sec); + return $date; + } + + /** + * Converts a date in the proleptic Gregorian calendar to the no of days + * since 24th November, 4714 B.C. + * + * Returns the no of days since Monday, 24th November, 4714 B.C. in the + * proleptic Gregorian calendar (which is 24th November, -4713 using + * 'Astronomical' year numbering, and 1st January, 4713 B.C. in the + * proleptic Julian calendar). This is also the first day of the 'Julian + * Period' proposed by Joseph Scaliger in 1583, and the number of days + * since this date is known as the 'Julian Day'. (It is not directly + * to do with the Julian calendar, although this is where the name + * is derived from.) + * + * The algorithm is valid for all years (positive and negative), and + * also for years preceding 4714 B.C. + * + * Algorithm is from PEAR::Date_Calc + * + * @author Monte Ohrt + * @author Pierre-Alain Joye + * @author Daniel Convissor + * @author C.A. Woodcock + * + * @return integer The number of days since 24th November, 4714 B.C. + */ + public function toDays() + { + if (function_exists('GregorianToJD')) { + return gregoriantojd($this->_month, $this->_mday, $this->_year); + } + + $day = $this->_mday; + $month = $this->_month; + $year = $this->_year; + + if ($month > 2) { + // March = 0, April = 1, ..., December = 9, + // January = 10, February = 11 + $month -= 3; + } else { + $month += 9; + --$year; + } + + $hb_negativeyear = $year < 0; + $century = intval($year / 100); + $year = $year % 100; + + if ($hb_negativeyear) { + // Subtract 1 because year 0 is a leap year; + // And N.B. that we must treat the leap years as occurring + // one year earlier than they do, because for the purposes + // of calculation, the year starts on 1st March: + // + return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) + + intval((1461 * $year + 1) / 4) + + intval((153 * $month + 2) / 5) + + $day + 1721118; + } else { + return intval(146097 * $century / 4) + + intval(1461 * $year / 4) + + intval((153 * $month + 2) / 5) + + $day + 1721119; + } + } + + /** + * Converts number of days since 24th November, 4714 B.C. (in the proleptic + * Gregorian calendar, which is year -4713 using 'Astronomical' year + * numbering) to Gregorian calendar date. + * + * Returned date belongs to the proleptic Gregorian calendar, using + * 'Astronomical' year numbering. + * + * The algorithm is valid for all years (positive and negative), and + * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'), + * and so the only limitation is platform-dependent (for 32-bit systems + * the maximum year would be something like about 1,465,190 A.D.). + * + * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'. + * + * Algorithm is from PEAR::Date_Calc + * + * @author Monte Ohrt + * @author Pierre-Alain Joye + * @author Daniel Convissor + * @author C.A. Woodcock + * + * @param int $days the number of days since 24th November, 4714 B.C. + * @param string $format the string indicating how to format the output + * + * @return Horde_Date A Horde_Date object representing the date. + */ + public static function fromDays($days) + { + if (function_exists('JDToGregorian')) { + list($month, $day, $year) = explode('/', JDToGregorian($days)); + } else { + $days = intval($days); + + $days -= 1721119; + $century = floor((4 * $days - 1) / 146097); + $days = floor(4 * $days - 1 - 146097 * $century); + $day = floor($days / 4); + + $year = floor((4 * $day + 3) / 1461); + $day = floor(4 * $day + 3 - 1461 * $year); + $day = floor(($day + 4) / 4); + + $month = floor((5 * $day - 3) / 153); + $day = floor(5 * $day - 3 - 153 * $month); + $day = floor(($day + 5) / 5); + + $year = $century * 100 + $year; + if ($month < 10) { + $month +=3; + } else { + $month -=9; + ++$year; + } + } + + return new Horde_Date($year, $month, $day); + } + + /** + * Getter for the date and time properties. + * + * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or + * 'sec'. + * + * @return integer The property value, or null if not set. + */ + public function __get($name) + { + if ($name == 'day') { + $name = 'mday'; + } + + return $this->{'_' . $name}; + } + + /** + * Setter for the date and time properties. + * + * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or + * 'sec'. + * @param integer $value The property value. + */ + public function __set($name, $value) + { + if ($name == 'timezone') { + $this->_initializeTimezone($value); + return; + } + if ($name == 'day') { + $name = 'mday'; + } + + if ($name != 'year' && $name != 'month' && $name != 'mday' && + $name != 'hour' && $name != 'min' && $name != 'sec') { + throw new InvalidArgumentException('Undefined property ' . $name); + } + + $down = $value < $this->{'_' . $name}; + $this->{'_' . $name} = $value; + $this->_correct(self::$_corrections[$name], $down); + $this->_formatCache = array(); + } + + /** + * Returns whether a date or time property exists. + * + * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or + * 'sec'. + * + * @return boolen True if the property exists and is set. + */ + public function __isset($name) + { + if ($name == 'day') { + $name = 'mday'; + } + return ($name == 'year' || $name == 'month' || $name == 'mday' || + $name == 'hour' || $name == 'min' || $name == 'sec') && + isset($this->{'_' . $name}); + } + + /** + * Adds a number of seconds or units to this date, returning a new Date + * object. + */ + public function add($factor) + { + $d = clone($this); + if (is_array($factor) || is_object($factor)) { + foreach ($factor as $property => $value) { + $d->$property += $value; + } + } else { + $d->sec += $factor; + } + + return $d; + } + + /** + * Subtracts a number of seconds or units from this date, returning a new + * Horde_Date object. + */ + public function sub($factor) + { + if (is_array($factor)) { + foreach ($factor as &$value) { + $value *= -1; + } + } else { + $factor *= -1; + } + + return $this->add($factor); + } + + /** + * Converts this object to a different timezone. + * + * @param string $timezone The new timezone. + * + * @return Horde_Date This object. + */ + public function setTimezone($timezone) + { + $date = $this->toDateTime(); + $date->setTimezone(new DateTimeZone($timezone)); + $this->_timezone = $timezone; + $this->_year = (int)$date->format('Y'); + $this->_month = (int)$date->format('m'); + $this->_mday = (int)$date->format('d'); + $this->_hour = (int)$date->format('H'); + $this->_min = (int)$date->format('i'); + $this->_sec = (int)$date->format('s'); + $this->_formatCache = array(); + return $this; + } + + /** + * Sets the default date format used in __toString() + * + * @param string $format + */ + public function setDefaultFormat($format) + { + $this->_defaultFormat = $format; + } + + /** + * Returns the day of the week (0 = Sunday, 6 = Saturday) of this date. + * + * @return integer The day of the week. + */ + public function dayOfWeek() + { + if ($this->_month > 2) { + $month = $this->_month - 2; + $year = $this->_year; + } else { + $month = $this->_month + 10; + $year = $this->_year - 1; + } + + $day = (floor((13 * $month - 1) / 5) + + $this->_mday + ($year % 100) + + floor(($year % 100) / 4) + + floor(($year / 100) / 4) - 2 * + floor($year / 100) + 77); + + return (int)($day - 7 * floor($day / 7)); + } + + /** + * Returns the day number of the year (1 to 365/366). + * + * @return integer The day of the year. + */ + public function dayOfYear() + { + return $this->format('z') + 1; + } + + /** + * Returns the week of the month. + * + * @return integer The week number. + */ + public function weekOfMonth() + { + return ceil($this->_mday / 7); + } + + /** + * Returns the week of the year, first Monday is first day of first week. + * + * @return integer The week number. + */ + public function weekOfYear() + { + return $this->format('W'); + } + + /** + * Returns the number of weeks in the given year (52 or 53). + * + * @param integer $year The year to count the number of weeks in. + * + * @return integer $numWeeks The number of weeks in $year. + */ + public static function weeksInYear($year) + { + // Find the last Thursday of the year. + $date = new Horde_Date($year . '-12-31'); + while ($date->dayOfWeek() != self::DATE_THURSDAY) { + --$date->mday; + } + return $date->weekOfYear(); + } + + /** + * Sets the date of this object to the $nth weekday of $weekday. + * + * @param integer $weekday The day of the week (0 = Sunday, etc). + * @param integer $nth The $nth $weekday to set to (defaults to 1). + */ + public function setNthWeekday($weekday, $nth = 1) + { + if ($weekday < self::DATE_SUNDAY || $weekday > self::DATE_SATURDAY) { + return; + } + + if ($nth < 0) { // last $weekday of month + $this->_mday = $lastday = Horde_Date_Utils::daysInMonth($this->_month, $this->_year); + $last = $this->dayOfWeek(); + $this->_mday += ($weekday - $last); + if ($this->_mday > $lastday) + $this->_mday -= 7; + } + else { + $this->_mday = 1; + $first = $this->dayOfWeek(); + if ($weekday < $first) { + $this->_mday = 8 + $weekday - $first; + } else { + $this->_mday = $weekday - $first + 1; + } + $diff = 7 * $nth - 7; + $this->_mday += $diff; + $this->_correct(self::MASK_DAY, $diff < 0); + } + } + + /** + * Is the date currently represented by this object a valid date? + * + * @return boolean Validity, counting leap years, etc. + */ + public function isValid() + { + return ($this->_year >= 0 && $this->_year <= 9999); + } + + /** + * Compares this date to another date object to see which one is + * greater (later). Assumes that the dates are in the same + * timezone. + * + * @param mixed $other The date to compare to. + * + * @return integer == 0 if they are on the same date + * >= 1 if $this is greater (later) + * <= -1 if $other is greater (later) + */ + public function compareDate($other) + { + if (!($other instanceof Horde_Date)) { + $other = new Horde_Date($other); + } + + if ($this->_year != $other->year) { + return $this->_year - $other->year; + } + if ($this->_month != $other->month) { + return $this->_month - $other->month; + } + + return $this->_mday - $other->mday; + } + + /** + * Returns whether this date is after the other. + * + * @param mixed $other The date to compare to. + * + * @return boolean True if this date is after the other. + */ + public function after($other) + { + return $this->compareDate($other) > 0; + } + + /** + * Returns whether this date is before the other. + * + * @param mixed $other The date to compare to. + * + * @return boolean True if this date is before the other. + */ + public function before($other) + { + return $this->compareDate($other) < 0; + } + + /** + * Returns whether this date is the same like the other. + * + * @param mixed $other The date to compare to. + * + * @return boolean True if this date is the same like the other. + */ + public function equals($other) + { + return $this->compareDate($other) == 0; + } + + /** + * Compares this to another date object by time, to see which one + * is greater (later). Assumes that the dates are in the same + * timezone. + * + * @param mixed $other The date to compare to. + * + * @return integer == 0 if they are at the same time + * >= 1 if $this is greater (later) + * <= -1 if $other is greater (later) + */ + public function compareTime($other) + { + if (!($other instanceof Horde_Date)) { + $other = new Horde_Date($other); + } + + if ($this->_hour != $other->hour) { + return $this->_hour - $other->hour; + } + if ($this->_min != $other->min) { + return $this->_min - $other->min; + } + + return $this->_sec - $other->sec; + } + + /** + * Compares this to another date object, including times, to see + * which one is greater (later). Assumes that the dates are in the + * same timezone. + * + * @param mixed $other The date to compare to. + * + * @return integer == 0 if they are equal + * >= 1 if $this is greater (later) + * <= -1 if $other is greater (later) + */ + public function compareDateTime($other) + { + if (!($other instanceof Horde_Date)) { + $other = new Horde_Date($other); + } + + if ($diff = $this->compareDate($other)) { + return $diff; + } + + return $this->compareTime($other); + } + + /** + * Returns number of days between this date and another. + * + * @param Horde_Date $other The other day to diff with. + * + * @return integer The absolute number of days between the two dates. + */ + public function diff($other) + { + return abs($this->toDays() - $other->toDays()); + } + + /** + * Returns the time offset for local time zone. + * + * @param boolean $colon Place a colon between hours and minutes? + * + * @return string Timezone offset as a string in the format +HH:MM. + */ + public function tzOffset($colon = true) + { + return $colon ? $this->format('P') : $this->format('O'); + } + + /** + * Returns the unix timestamp representation of this date. + * + * @return integer A unix timestamp. + */ + public function timestamp() + { + if ($this->_year >= 1970 && $this->_year < 2038) { + return mktime($this->_hour, $this->_min, $this->_sec, + $this->_month, $this->_mday, $this->_year); + } + return $this->format('U'); + } + + /** + * Returns the unix timestamp representation of this date, 12:00am. + * + * @return integer A unix timestamp. + */ + public function datestamp() + { + if ($this->_year >= 1970 && $this->_year < 2038) { + return mktime(0, 0, 0, $this->_month, $this->_mday, $this->_year); + } + $date = new DateTime($this->format('Y-m-d')); + return $date->format('U'); + } + + /** + * Formats date and time to be passed around as a short url parameter. + * + * @return string Date and time. + */ + public function dateString() + { + return sprintf('%04d%02d%02d', $this->_year, $this->_month, $this->_mday); + } + + /** + * Formats date and time to the ISO format used by JSON. + * + * @return string Date and time. + */ + public function toJson() + { + return $this->format(self::DATE_JSON); + } + + /** + * Formats date and time to the RFC 2445 iCalendar DATE-TIME format. + * + * @param boolean $floating Whether to return a floating date-time + * (without time zone information). + * + * @return string Date and time. + */ + public function toiCalendar($floating = false) + { + if ($floating) { + return $this->format('Ymd\THis'); + } + $dateTime = $this->toDateTime(); + $dateTime->setTimezone(new DateTimeZone('UTC')); + return $dateTime->format('Ymd\THis\Z'); + } + + /** + * Formats time using the specifiers available in date() or in the DateTime + * class' format() method. + * + * To format in languages other than English, use strftime() instead. + * + * @param string $format + * + * @return string Formatted time. + */ + public function format($format) + { + if (!isset($this->_formatCache[$format])) { + $this->_formatCache[$format] = $this->toDateTime()->format($format); + } + return $this->_formatCache[$format]; + } + + /** + * Formats date and time using strftime() format. + * + * @return string strftime() formatted date and time. + */ + public function strftime($format) + { + if (preg_match('/%[^' . self::$_supportedSpecs . ']/', $format)) { + return strftime($format, $this->timestamp()); + } else { + return $this->_strftime($format); + } + } + + /** + * Formats date and time using a limited set of the strftime() format. + * + * @return string strftime() formatted date and time. + */ + protected function _strftime($format) + { + return preg_replace( + array('/%b/e', + '/%B/e', + '/%C/e', + '/%d/e', + '/%D/e', + '/%e/e', + '/%H/e', + '/%I/e', + '/%m/e', + '/%M/e', + '/%n/', + '/%p/e', + '/%R/e', + '/%S/e', + '/%t/', + '/%T/e', + '/%x/e', + '/%X/e', + '/%y/e', + '/%Y/', + '/%%/'), + array('$this->_strftime(Horde_Nls::getLangInfo(constant(\'ABMON_\' . (int)$this->_month)))', + '$this->_strftime(Horde_Nls::getLangInfo(constant(\'MON_\' . (int)$this->_month)))', + '(int)($this->_year / 100)', + 'sprintf(\'%02d\', $this->_mday)', + '$this->_strftime(\'%m/%d/%y\')', + 'sprintf(\'%2d\', $this->_mday)', + 'sprintf(\'%02d\', $this->_hour)', + 'sprintf(\'%02d\', $this->_hour == 0 ? 12 : ($this->_hour > 12 ? $this->_hour - 12 : $this->_hour))', + 'sprintf(\'%02d\', $this->_month)', + 'sprintf(\'%02d\', $this->_min)', + "\n", + '$this->_strftime(Horde_Nls::getLangInfo($this->_hour < 12 ? AM_STR : PM_STR))', + '$this->_strftime(\'%H:%M\')', + 'sprintf(\'%02d\', $this->_sec)', + "\t", + '$this->_strftime(\'%H:%M:%S\')', + '$this->_strftime(Horde_Nls::getLangInfo(D_FMT))', + '$this->_strftime(Horde_Nls::getLangInfo(T_FMT))', + 'substr(sprintf(\'%04d\', $this->_year), -2)', + (int)$this->_year, + '%'), + $format); + } + + /** + * Corrects any over- or underflows in any of the date's members. + * + * @param integer $mask We may not want to correct some overflows. + * @param integer $down Whether to correct the date up or down. + */ + protected function _correct($mask = self::MASK_ALLPARTS, $down = false) + { + if ($mask & self::MASK_SECOND) { + if ($this->_sec < 0 || $this->_sec > 59) { + $mask |= self::MASK_MINUTE; + + $this->_min += (int)($this->_sec / 60); + $this->_sec %= 60; + if ($this->_sec < 0) { + $this->_min--; + $this->_sec += 60; + } + } + } + + if ($mask & self::MASK_MINUTE) { + if ($this->_min < 0 || $this->_min > 59) { + $mask |= self::MASK_HOUR; + + $this->_hour += (int)($this->_min / 60); + $this->_min %= 60; + if ($this->_min < 0) { + $this->_hour--; + $this->_min += 60; + } + } + } + + if ($mask & self::MASK_HOUR) { + if ($this->_hour < 0 || $this->_hour > 23) { + $mask |= self::MASK_DAY; + + $this->_mday += (int)($this->_hour / 24); + $this->_hour %= 24; + if ($this->_hour < 0) { + $this->_mday--; + $this->_hour += 24; + } + } + } + + if ($mask & self::MASK_MONTH) { + $this->_correctMonth($down); + /* When correcting the month, always correct the day too. Months + * have different numbers of days. */ + $mask |= self::MASK_DAY; + } + + if ($mask & self::MASK_DAY) { + while ($this->_mday > 28 && + $this->_mday > Horde_Date_Utils::daysInMonth($this->_month, $this->_year)) { + if ($down) { + $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month + 1, $this->_year) - Horde_Date_Utils::daysInMonth($this->_month, $this->_year); + } else { + $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month, $this->_year); + $this->_month++; + } + $this->_correctMonth($down); + } + while ($this->_mday < 1) { + --$this->_month; + $this->_correctMonth($down); + $this->_mday += Horde_Date_Utils::daysInMonth($this->_month, $this->_year); + } + } + } + + /** + * Corrects the current month. + * + * This cannot be done in _correct() because that would also trigger a + * correction of the day, which would result in an infinite loop. + * + * @param integer $down Whether to correct the date up or down. + */ + protected function _correctMonth($down = false) + { + $this->_year += (int)($this->_month / 12); + $this->_month %= 12; + if ($this->_month < 1) { + $this->_year--; + $this->_month += 12; + } + } + + /** + * Handles args in order: year month day hour min sec tz + */ + protected function _initializeFromArgs($args) + { + $tz = (isset($args[6])) ? array_pop($args) : null; + $this->_initializeTimezone($tz); + + $args = array_slice($args, 0, 6); + $keys = array('year' => 1, 'month' => 1, 'mday' => 1, 'hour' => 0, 'min' => 0, 'sec' => 0); + $date = array_combine(array_slice(array_keys($keys), 0, count($args)), $args); + $date = array_merge($keys, $date); + + $this->_initializeFromArray($date); + } + + protected function _initializeFromArray($date) + { + if (isset($date['year']) && is_string($date['year']) && strlen($date['year']) == 2) { + if ($date['year'] > 70) { + $date['year'] += 1900; + } else { + $date['year'] += 2000; + } + } + + foreach ($date as $key => $val) { + if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) { + $this->{'_'. $key} = (int)$val; + } + } + + // If $date['day'] is present and numeric we may have been passed + // a Horde_Form_datetime array. + if (isset($date['day']) && + (string)(int)$date['day'] == $date['day']) { + $this->_mday = (int)$date['day']; + } + // 'minute' key also from Horde_Form_datetime + if (isset($date['minute']) && + (string)(int)$date['minute'] == $date['minute']) { + $this->_min = (int)$date['minute']; + } + + $this->_correct(); + } + + protected function _initializeFromObject($date) + { + if ($date instanceof DateTime) { + $this->_year = (int)$date->format('Y'); + $this->_month = (int)$date->format('m'); + $this->_mday = (int)$date->format('d'); + $this->_hour = (int)$date->format('H'); + $this->_min = (int)$date->format('i'); + $this->_sec = (int)$date->format('s'); + $this->_initializeTimezone($date->getTimezone()->getName()); + } else { + $is_horde_date = $date instanceof Horde_Date; + foreach (array('year', 'month', 'mday', 'hour', 'min', 'sec') as $key) { + if ($is_horde_date || isset($date->$key)) { + $this->{'_' . $key} = (int)$date->$key; + } + } + if (!$is_horde_date) { + $this->_correct(); + } else { + $this->_initializeTimezone($date->timezone); + } + } + } + + protected function _initializeTimezone($timezone) + { + if (empty($timezone)) { + $timezone = date_default_timezone_get(); + } + $this->_timezone = $timezone; + } + +} + +/** + * @category Horde + * @package Date + */ + +/** + * Horde Date wrapper/logic class, including some calculation + * functions. + * + * @category Horde + * @package Date + */ +class Horde_Date_Utils +{ + /** + * Returns whether a year is a leap year. + * + * @param integer $year The year. + * + * @return boolean True if the year is a leap year. + */ + public static function isLeapYear($year) + { + if (strlen($year) != 4 || preg_match('/\D/', $year)) { + return false; + } + + return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0); + } + + /** + * Returns the date of the year that corresponds to the first day of the + * given week. + * + * @param integer $week The week of the year to find the first day of. + * @param integer $year The year to calculate for. + * + * @return Horde_Date The date of the first day of the given week. + */ + public static function firstDayOfWeek($week, $year) + { + return new Horde_Date(sprintf('%04dW%02d', $year, $week)); + } + + /** + * Returns the number of days in the specified month. + * + * @param integer $month The month + * @param integer $year The year. + * + * @return integer The number of days in the month. + */ + public static function daysInMonth($month, $year) + { + static $cache = array(); + if (!isset($cache[$year][$month])) { + $date = new DateTime(sprintf('%04d-%02d-01', $year, $month)); + $cache[$year][$month] = $date->format('t'); + } + return $cache[$year][$month]; + } + + /** + * Returns a relative, natural language representation of a timestamp + * + * @todo Wider range of values ... maybe future time as well? + * @todo Support minimum resolution parameter. + * + * @param mixed $time The time. Any format accepted by Horde_Date. + * @param string $date_format Format to display date if timestamp is + * more then 1 day old. + * @param string $time_format Format to display time if timestamp is 1 + * day old. + * + * @return string The relative time (i.e. 2 minutes ago) + */ + public static function relativeDateTime($time, $date_format = '%x', + $time_format = '%X') + { + $date = new Horde_Date($time); + + $delta = time() - $date->timestamp(); + if ($delta < 60) { + return sprintf(Horde_Date_Translation::ngettext("%d second ago", "%d seconds ago", $delta), $delta); + } + + $delta = round($delta / 60); + if ($delta < 60) { + return sprintf(Horde_Date_Translation::ngettext("%d minute ago", "%d minutes ago", $delta), $delta); + } + + $delta = round($delta / 60); + if ($delta < 24) { + return sprintf(Horde_Date_Translation::ngettext("%d hour ago", "%d hours ago", $delta), $delta); + } + + if ($delta > 24 && $delta < 48) { + $date = new Horde_Date($time); + return sprintf(Horde_Date_Translation::t("yesterday at %s"), $date->strftime($time_format)); + } + + $delta = round($delta / 24); + if ($delta < 7) { + return sprintf(Horde_Date_Translation::t("%d days ago"), $delta); + } + + if (round($delta / 7) < 5) { + $delta = round($delta / 7); + return sprintf(Horde_Date_Translation::ngettext("%d week ago", "%d weeks ago", $delta), $delta); + } + + // Default to the user specified date format. + return $date->strftime($date_format); + } + + /** + * Tries to convert strftime() formatters to date() formatters. + * + * Unsupported formatters will be removed. + * + * @param string $format A strftime() formatting string. + * + * @return string A date() formatting string. + */ + public static function strftime2date($format) + { + $replace = array( + '/%a/' => 'D', + '/%A/' => 'l', + '/%d/' => 'd', + '/%e/' => 'j', + '/%j/' => 'z', + '/%u/' => 'N', + '/%w/' => 'w', + '/%U/' => '', + '/%V/' => 'W', + '/%W/' => '', + '/%b/' => 'M', + '/%B/' => 'F', + '/%h/' => 'M', + '/%m/' => 'm', + '/%C/' => '', + '/%g/' => '', + '/%G/' => 'o', + '/%y/' => 'y', + '/%Y/' => 'Y', + '/%H/' => 'H', + '/%I/' => 'h', + '/%i/' => 'g', + '/%M/' => 'i', + '/%p/' => 'A', + '/%P/' => 'a', + '/%r/' => 'h:i:s A', + '/%R/' => 'H:i', + '/%S/' => 's', + '/%T/' => 'H:i:s', + '/%X/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(T_FMT))', + '/%z/' => 'O', + '/%Z/' => '', + '/%c/' => '', + '/%D/' => 'm/d/y', + '/%F/' => 'Y-m-d', + '/%s/' => 'U', + '/%x/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(D_FMT))', + '/%n/' => "\n", + '/%t/' => "\t", + '/%%/' => '%' + ); + + return preg_replace(array_keys($replace), array_values($replace), $format); + } + +} diff --git a/lib/Horde_Date_Recurrence.php b/lib/Horde_Date_Recurrence.php new file mode 100644 index 0000000..81f0857 --- /dev/null +++ b/lib/Horde_Date_Recurrence.php @@ -0,0 +1,1673 @@ + 1 ? $plur : $sing); } +} + + +/** + * This file contains the Horde_Date_Recurrence class and according constants. + * + * Copyright 2007-2012 Horde LLC (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you + * did not receive this file, see http://www.horde.org/licenses/lgpl21. + * + * @category Horde + * @package Date + */ + +/** + * The Horde_Date_Recurrence class implements algorithms for calculating + * recurrences of events, including several recurrence types, intervals, + * exceptions, and conversion from and to vCalendar and iCalendar recurrence + * rules. + * + * All methods expecting dates as parameters accept all values that the + * Horde_Date constructor accepts, i.e. a timestamp, another Horde_Date + * object, an ISO time string or a hash. + * + * @author Jan Schneider + * @category Horde + * @package Date + */ +class Horde_Date_Recurrence +{ + /** No Recurrence **/ + const RECUR_NONE = 0; + + /** Recurs daily. */ + const RECUR_DAILY = 1; + + /** Recurs weekly. */ + const RECUR_WEEKLY = 2; + + /** Recurs monthly on the same date. */ + const RECUR_MONTHLY_DATE = 3; + + /** Recurs monthly on the same week day. */ + const RECUR_MONTHLY_WEEKDAY = 4; + + /** Recurs yearly on the same date. */ + const RECUR_YEARLY_DATE = 5; + + /** Recurs yearly on the same day of the year. */ + const RECUR_YEARLY_DAY = 6; + + /** Recurs yearly on the same week day. */ + const RECUR_YEARLY_WEEKDAY = 7; + + /** + * The start time of the event. + * + * @var Horde_Date + */ + public $start; + + /** + * The end date of the recurrence interval. + * + * @var Horde_Date + */ + public $recurEnd = null; + + /** + * The number of recurrences. + * + * @var integer + */ + public $recurCount = null; + + /** + * The type of recurrence this event follows. RECUR_* constant. + * + * @var integer + */ + public $recurType = self::RECUR_NONE; + + /** + * The length of time between recurrences. The time unit depends on the + * recurrence type. + * + * @var integer + */ + public $recurInterval = 1; + + /** + * Any additional recurrence data. + * + * @var integer + */ + public $recurData = null; + + /** + * BYDAY recurrence number + * + * @var integer + */ + public $recurNthDay = null; + + /** + * BYMONTH recurrence data + * + * @var array + */ + public $recurMonths = array(); + + /** + * All the exceptions from recurrence for this event. + * + * @var array + */ + public $exceptions = array(); + + /** + * All the dates this recurrence has been marked as completed. + * + * @var array + */ + public $completions = array(); + + /** + * Constructor. + * + * @param Horde_Date $start Start of the recurring event. + */ + public function __construct($start) + { + $this->start = new Horde_Date($start); + } + + /** + * Resets the class properties. + */ + public function reset() + { + $this->recurEnd = null; + $this->recurCount = null; + $this->recurType = self::RECUR_NONE; + $this->recurInterval = 1; + $this->recurData = null; + $this->exceptions = array(); + $this->completions = array(); + } + + /** + * Checks if this event recurs on a given day of the week. + * + * @param integer $dayMask A mask consisting of Horde_Date::MASK_* + * constants specifying the day(s) to check. + * + * @return boolean True if this event recurs on the given day(s). + */ + public function recurOnDay($dayMask) + { + return ($this->recurData & $dayMask); + } + + /** + * Specifies the days this event recurs on. + * + * @param integer $dayMask A mask consisting of Horde_Date::MASK_* + * constants specifying the day(s) to recur on. + */ + public function setRecurOnDay($dayMask) + { + $this->recurData = $dayMask; + } + + /** + * + * @param integer $nthDay The nth weekday of month to repeat events on + */ + public function setRecurNthWeekday($nth) + { + $this->recurNthDay = (int)$nth; + } + + /** + * + * @return integer The nth weekday of month to repeat events. + */ + public function getRecurNthWeekday() + { + return isset($this->recurNthDay) ? $this->recurNthDay : ceil($this->start->mday / 7); + } + + /** + * Specifies the months for yearly (weekday) recurrence + * + * @param array $months List of months (integers) this event recurs on. + */ + function setRecurByMonth($months) + { + $this->recurMonths = (array)$months; + } + + /** + * Returns a list of months this yearly event recurs on + * + * @return array List of months (integers) this event recurs on. + */ + function getRecurByMonth() + { + return $this->recurMonths; + } + + /** + * Returns the days this event recurs on. + * + * @return integer A mask consisting of Horde_Date::MASK_* constants + * specifying the day(s) this event recurs on. + */ + public function getRecurOnDays() + { + return $this->recurData; + } + + /** + * Returns whether this event has a specific recurrence type. + * + * @param integer $recurrence RECUR_* constant of the + * recurrence type to check for. + * + * @return boolean True if the event has the specified recurrence type. + */ + public function hasRecurType($recurrence) + { + return ($recurrence == $this->recurType); + } + + /** + * Sets a recurrence type for this event. + * + * @param integer $recurrence A RECUR_* constant. + */ + public function setRecurType($recurrence) + { + $this->recurType = $recurrence; + } + + /** + * Returns recurrence type of this event. + * + * @return integer A RECUR_* constant. + */ + public function getRecurType() + { + return $this->recurType; + } + + /** + * Returns a description of this event's recurring type. + * + * @return string Human readable recurring type. + */ + public function getRecurName() + { + switch ($this->getRecurType()) { + case self::RECUR_NONE: return Horde_Date_Translation::t("No recurrence"); + case self::RECUR_DAILY: return Horde_Date_Translation::t("Daily"); + case self::RECUR_WEEKLY: return Horde_Date_Translation::t("Weekly"); + case self::RECUR_MONTHLY_DATE: + case self::RECUR_MONTHLY_WEEKDAY: return Horde_Date_Translation::t("Monthly"); + case self::RECUR_YEARLY_DATE: + case self::RECUR_YEARLY_DAY: + case self::RECUR_YEARLY_WEEKDAY: return Horde_Date_Translation::t("Yearly"); + } + } + + /** + * Sets the length of time between recurrences of this event. + * + * @param integer $interval The time between recurrences. + */ + public function setRecurInterval($interval) + { + if ($interval > 0) { + $this->recurInterval = $interval; + } + } + + /** + * Retrieves the length of time between recurrences of this event. + * + * @return integer The number of seconds between recurrences. + */ + public function getRecurInterval() + { + return $this->recurInterval; + } + + /** + * Sets the number of recurrences of this event. + * + * @param integer $count The number of recurrences. + */ + public function setRecurCount($count) + { + if ($count > 0) { + $this->recurCount = (int)$count; + // Recurrence counts and end dates are mutually exclusive. + $this->recurEnd = null; + } else { + $this->recurCount = null; + } + } + + /** + * Retrieves the number of recurrences of this event. + * + * @return integer The number recurrences. + */ + public function getRecurCount() + { + return $this->recurCount; + } + + /** + * Returns whether this event has a recurrence with a fixed count. + * + * @return boolean True if this recurrence has a fixed count. + */ + public function hasRecurCount() + { + return isset($this->recurCount); + } + + /** + * Sets the start date of the recurrence interval. + * + * @param Horde_Date $start The recurrence start. + */ + public function setRecurStart($start) + { + $this->start = clone $start; + } + + /** + * Retrieves the start date of the recurrence interval. + * + * @return Horde_Date The recurrence start. + */ + public function getRecurStart() + { + return $this->start; + } + + /** + * Sets the end date of the recurrence interval. + * + * @param Horde_Date $end The recurrence end. + */ + public function setRecurEnd($end) + { + if (!empty($end)) { + // Recurrence counts and end dates are mutually exclusive. + $this->recurCount = null; + $this->recurEnd = clone $end; + } else { + $this->recurEnd = $end; + } + } + + /** + * Retrieves the end date of the recurrence interval. + * + * @return Horde_Date The recurrence end. + */ + public function getRecurEnd() + { + return $this->recurEnd; + } + + /** + * Returns whether this event has a recurrence end. + * + * @return boolean True if this recurrence ends. + */ + public function hasRecurEnd() + { + return isset($this->recurEnd) && isset($this->recurEnd->year) && + $this->recurEnd->year != 9999; + } + + /** + * Finds the next recurrence of this event that's after $afterDate. + * + * @param Horde_Date|string $after Return events after this date. + * + * @return Horde_Date|boolean The date of the next recurrence or false + * if the event does not recur after + * $afterDate. + */ + public function nextRecurrence($after) + { + if (!($after instanceof Horde_Date)) { + $after = new Horde_Date($after); + } else { + $after = clone($after); + } + + // Make sure $after and $this->start are in the same TZ + $after->setTimezone($this->start->timezone); + if ($this->start->compareDateTime($after) >= 0) { + return clone $this->start; + } + + if ($this->recurInterval == 0) { + return false; + } + + switch ($this->getRecurType()) { + case self::RECUR_DAILY: + $diff = $this->start->diff($after); + $recur = ceil($diff / $this->recurInterval); + if ($this->recurCount && $recur >= $this->recurCount) { + return false; + } + + $recur *= $this->recurInterval; + $next = $this->start->add(array('day' => $recur)); + if ((!$this->hasRecurEnd() || + $next->compareDateTime($this->recurEnd) <= 0) && + $next->compareDateTime($after) >= 0) { + return $next; + } + break; + + case self::RECUR_WEEKLY: + if (empty($this->recurData)) { + return false; + } + + $start_week = Horde_Date_Utils::firstDayOfWeek($this->start->format('W'), + $this->start->year); + $start_week->timezone = $this->start->timezone; + $start_week->hour = $this->start->hour; + $start_week->min = $this->start->min; + $start_week->sec = $this->start->sec; + + // Make sure we are not at the ISO-8601 first week of year while + // still in month 12...OR in the ISO-8601 last week of year while + // in month 1 and adjust the year accordingly. + $week = $after->format('W'); + if ($week == 1 && $after->month == 12) { + $theYear = $after->year + 1; + } elseif ($week >= 52 && $after->month == 1) { + $theYear = $after->year - 1; + } else { + $theYear = $after->year; + } + + $after_week = Horde_Date_Utils::firstDayOfWeek($week, $theYear); + $after_week->timezone = $this->start->timezone; + $after_week_end = clone $after_week; + $after_week_end->mday += 7; + + $diff = $start_week->diff($after_week); + $interval = $this->recurInterval * 7; + $repeats = floor($diff / $interval); + if ($diff % $interval < 7) { + $recur = $diff; + } else { + /** + * If the after_week is not in the first week interval the + * search needs to skip ahead a complete interval. The way it is + * calculated here means that an event that occurs every second + * week on Monday and Wednesday with the event actually starting + * on Tuesday or Wednesday will only have one incidence in the + * first week. + */ + $recur = $interval * ($repeats + 1); + } + + if ($this->hasRecurCount()) { + $recurrences = 0; + /** + * Correct the number of recurrences by the number of events + * that lay between the start of the start week and the + * recurrence start. + */ + $next = clone $start_week; + while ($next->compareDateTime($this->start) < 0) { + if ($this->recurOnDay((int)pow(2, $next->dayOfWeek()))) { + $recurrences--; + } + ++$next->mday; + } + if ($repeats > 0) { + $weekdays = $this->recurData; + $total_recurrences_per_week = 0; + while ($weekdays > 0) { + if ($weekdays % 2) { + $total_recurrences_per_week++; + } + $weekdays = ($weekdays - ($weekdays % 2)) / 2; + } + $recurrences += $total_recurrences_per_week * $repeats; + } + } + + $next = clone $start_week; + $next->mday += $recur; + while ($next->compareDateTime($after) < 0 && + $next->compareDateTime($after_week_end) < 0) { + if ($this->hasRecurCount() + && $next->compareDateTime($after) < 0 + && $this->recurOnDay((int)pow(2, $next->dayOfWeek()))) { + $recurrences++; + } + ++$next->mday; + } + if ($this->hasRecurCount() && + $recurrences >= $this->recurCount) { + return false; + } + if (!$this->hasRecurEnd() || + $next->compareDateTime($this->recurEnd) <= 0) { + if ($next->compareDateTime($after_week_end) >= 0) { + return $this->nextRecurrence($after_week_end); + } + while (!$this->recurOnDay((int)pow(2, $next->dayOfWeek())) && + $next->compareDateTime($after_week_end) < 0) { + ++$next->mday; + } + if (!$this->hasRecurEnd() || + $next->compareDateTime($this->recurEnd) <= 0) { + if ($next->compareDateTime($after_week_end) >= 0) { + return $this->nextRecurrence($after_week_end); + } else { + return $next; + } + } + } + break; + + case self::RECUR_MONTHLY_DATE: + $start = clone $this->start; + if ($after->compareDateTime($start) < 0) { + $after = clone $start; + } else { + $after = clone $after; + } + + // If we're starting past this month's recurrence of the event, + // look in the next month on the day the event recurs. + if ($after->mday > $start->mday) { + ++$after->month; + $after->mday = $start->mday; + } + + // Adjust $start to be the first match. + $offset = ($after->month - $start->month) + ($after->year - $start->year) * 12; + $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; + + if ($this->recurCount && + ($offset / $this->recurInterval) >= $this->recurCount) { + return false; + } + $start->month += $offset; + $count = $offset / $this->recurInterval; + + do { + if ($this->recurCount && + $count++ >= $this->recurCount) { + return false; + } + + // Bail if we've gone past the end of recurrence. + if ($this->hasRecurEnd() && + $this->recurEnd->compareDateTime($start) < 0) { + return false; + } + if ($start->isValid()) { + return $start; + } + + // If the interval is 12, and the date isn't valid, then we + // need to see if February 29th is an option. If not, then the + // event will _never_ recur, and we need to stop checking to + // avoid an infinite loop. + if ($this->recurInterval == 12 && ($start->month != 2 || $start->mday > 29)) { + return false; + } + + // Add the recurrence interval. + $start->month += $this->recurInterval; + } while (true); + + break; + + case self::RECUR_MONTHLY_WEEKDAY: + // Start with the start date of the event. + $estart = clone $this->start; + + // What day of the week, and week of the month, do we recur on? + if (isset($this->recurNthDay)) { + $nth = $this->recurNthDay; + $weekday = log($this->recurData, 2); + } else { + $nth = ceil($this->start->mday / 7); + $weekday = $estart->dayOfWeek(); + } + + // Adjust $estart to be the first candidate. + $offset = ($after->month - $estart->month) + ($after->year - $estart->year) * 12; + $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; + + // Adjust our working date until it's after $after. + $estart->month += $offset - $this->recurInterval; + + $count = $offset / $this->recurInterval; + do { + if ($this->recurCount && + $count++ >= $this->recurCount) { + return false; + } + + $estart->month += $this->recurInterval; + + $next = clone $estart; + $next->setNthWeekday($weekday, $nth); + + if ($next->compareDateTime($after) < 0) { + // We haven't made it past $after yet, try again. + continue; + } + if ($this->hasRecurEnd() && + $next->compareDateTime($this->recurEnd) > 0) { + // We've gone past the end of recurrence; we can give up + // now. + return false; + } + + // We have a candidate to return. + break; + } while (true); + + return $next; + + case self::RECUR_YEARLY_DATE: + // Start with the start date of the event. + $estart = clone $this->start; + $after = clone $after; + + if ($after->month > $estart->month || + ($after->month == $estart->month && $after->mday > $estart->mday)) { + ++$after->year; + $after->month = $estart->month; + $after->mday = $estart->mday; + } + + // Seperate case here for February 29th + if ($estart->month == 2 && $estart->mday == 29) { + while (!Horde_Date_Utils::isLeapYear($after->year)) { + ++$after->year; + } + } + + // Adjust $estart to be the first candidate. + $offset = $after->year - $estart->year; + if ($offset > 0) { + $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; + $estart->year += $offset; + } + + // We've gone past the end of recurrence; give up. + if ($this->recurCount && + $offset >= $this->recurCount) { + return false; + } + if ($this->hasRecurEnd() && + $this->recurEnd->compareDateTime($estart) < 0) { + return false; + } + + return $estart; + + case self::RECUR_YEARLY_DAY: + // Check count first. + $dayofyear = $this->start->dayOfYear(); + $count = ($after->year - $this->start->year) / $this->recurInterval + 1; + if ($this->recurCount && + ($count > $this->recurCount || + ($count == $this->recurCount && + $after->dayOfYear() > $dayofyear))) { + return false; + } + + // Start with a rough interval. + $estart = clone $this->start; + $estart->year += floor($count - 1) * $this->recurInterval; + + // Now add the difference to the required day of year. + $estart->mday += $dayofyear - $estart->dayOfYear(); + + // Add an interval if the estimation was wrong. + if ($estart->compareDate($after) < 0) { + $estart->year += $this->recurInterval; + $estart->mday += $dayofyear - $estart->dayOfYear(); + } + + // We've gone past the end of recurrence; give up. + if ($this->hasRecurEnd() && + $this->recurEnd->compareDateTime($estart) < 0) { + return false; + } + + return $estart; + + case self::RECUR_YEARLY_WEEKDAY: + // Start with the start date of the event. + $estart = clone $this->start; + + // What day of the week, and week of the month, do we recur on? + if (isset($this->recurNthDay)) { + $nth = $this->recurNthDay; + $weekday = log($this->recurData, 2); + } else { + $nth = ceil($this->start->mday / 7); + $weekday = $estart->dayOfWeek(); + } + + // Adjust $estart to be the first candidate. + $offset = floor(($after->year - $estart->year + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; + + // Adjust our working date until it's after $after. + $estart->year += $offset - $this->recurInterval; + + $count = $offset / $this->recurInterval; + do { + if ($this->recurCount && + $count++ >= $this->recurCount) { + return false; + } + + $estart->year += $this->recurInterval; + + $next = clone $estart; + $next->setNthWeekday($weekday, $nth); + + if ($next->compareDateTime($after) < 0) { + // We haven't made it past $after yet, try again. + continue; + } + if ($this->hasRecurEnd() && + $next->compareDateTime($this->recurEnd) > 0) { + // We've gone past the end of recurrence; we can give up + // now. + return false; + } + + // We have a candidate to return. + break; + } while (true); + + return $next; + } + + // We didn't find anything, the recurType was bad, or something else + // went wrong - return false. + return false; + } + + /** + * Returns whether this event has any date that matches the recurrence + * rules and is not an exception. + * + * @return boolean True if an active recurrence exists. + */ + public function hasActiveRecurrence() + { + if (!$this->hasRecurEnd()) { + return true; + } + + $next = $this->nextRecurrence(new Horde_Date($this->start)); + while (is_object($next)) { + if (!$this->hasException($next->year, $next->month, $next->mday) && + !$this->hasCompletion($next->year, $next->month, $next->mday)) { + return true; + } + + $next = $this->nextRecurrence($next->add(array('day' => 1))); + } + + return false; + } + + /** + * Returns the next active recurrence. + * + * @param Horde_Date $afterDate Return events after this date. + * + * @return Horde_Date|boolean The date of the next active + * recurrence or false if the event + * has no active recurrence after + * $afterDate. + */ + public function nextActiveRecurrence($afterDate) + { + $next = $this->nextRecurrence($afterDate); + while (is_object($next)) { + if (!$this->hasException($next->year, $next->month, $next->mday) && + !$this->hasCompletion($next->year, $next->month, $next->mday)) { + return $next; + } + $next->mday++; + $next = $this->nextRecurrence($next); + } + + return false; + } + + /** + * Adds an exception to a recurring event. + * + * @param integer $year The year of the execption. + * @param integer $month The month of the execption. + * @param integer $mday The day of the month of the exception. + */ + public function addException($year, $month, $mday) + { + $this->exceptions[] = sprintf('%04d%02d%02d', $year, $month, $mday); + } + + /** + * Deletes an exception from a recurring event. + * + * @param integer $year The year of the execption. + * @param integer $month The month of the execption. + * @param integer $mday The day of the month of the exception. + */ + public function deleteException($year, $month, $mday) + { + $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->exceptions); + if ($key !== false) { + unset($this->exceptions[$key]); + } + } + + /** + * Checks if an exception exists for a given reccurence of an event. + * + * @param integer $year The year of the reucrance. + * @param integer $month The month of the reucrance. + * @param integer $mday The day of the month of the reucrance. + * + * @return boolean True if an exception exists for the given date. + */ + public function hasException($year, $month, $mday) + { + return in_array(sprintf('%04d%02d%02d', $year, $month, $mday), + $this->getExceptions()); + } + + /** + * Retrieves all the exceptions for this event. + * + * @return array Array containing the dates of all the exceptions in + * YYYYMMDD form. + */ + public function getExceptions() + { + return $this->exceptions; + } + + /** + * Adds a completion to a recurring event. + * + * @param integer $year The year of the execption. + * @param integer $month The month of the execption. + * @param integer $mday The day of the month of the completion. + */ + public function addCompletion($year, $month, $mday) + { + $this->completions[] = sprintf('%04d%02d%02d', $year, $month, $mday); + } + + /** + * Deletes a completion from a recurring event. + * + * @param integer $year The year of the execption. + * @param integer $month The month of the execption. + * @param integer $mday The day of the month of the completion. + */ + public function deleteCompletion($year, $month, $mday) + { + $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->completions); + if ($key !== false) { + unset($this->completions[$key]); + } + } + + /** + * Checks if a completion exists for a given reccurence of an event. + * + * @param integer $year The year of the reucrance. + * @param integer $month The month of the recurrance. + * @param integer $mday The day of the month of the recurrance. + * + * @return boolean True if a completion exists for the given date. + */ + public function hasCompletion($year, $month, $mday) + { + return in_array(sprintf('%04d%02d%02d', $year, $month, $mday), + $this->getCompletions()); + } + + /** + * Retrieves all the completions for this event. + * + * @return array Array containing the dates of all the completions in + * YYYYMMDD form. + */ + public function getCompletions() + { + return $this->completions; + } + + /** + * Parses a vCalendar 1.0 recurrence rule. + * + * @link http://www.imc.org/pdi/vcal-10.txt + * @link http://www.shuchow.com/vCalAddendum.html + * + * @param string $rrule A vCalendar 1.0 conform RRULE value. + */ + public function fromRRule10($rrule) + { + $this->reset(); + + if (!$rrule) { + return; + } + + if (!preg_match('/([A-Z]+)(\d+)?(.*)/', $rrule, $matches)) { + // No recurrence data - event does not recur. + $this->setRecurType(self::RECUR_NONE); + } + + // Always default the recurInterval to 1. + $this->setRecurInterval(!empty($matches[2]) ? $matches[2] : 1); + + $remainder = trim($matches[3]); + + switch ($matches[1]) { + case 'D': + $this->setRecurType(self::RECUR_DAILY); + break; + + case 'W': + $this->setRecurType(self::RECUR_WEEKLY); + if (!empty($remainder)) { + $mask = 0; + while (preg_match('/^ ?[A-Z]{2} ?/', $remainder, $matches)) { + $day = trim($matches[0]); + $remainder = substr($remainder, strlen($matches[0])); + $mask |= $maskdays[$day]; + } + $this->setRecurOnDay($mask); + } else { + // Recur on the day of the week of the original recurrence. + $maskdays = array( + Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY, + Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY, + Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY, + Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY, + Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY, + Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY, + Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY, + ); + $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]); + } + break; + + case 'MP': + $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); + break; + + case 'MD': + $this->setRecurType(self::RECUR_MONTHLY_DATE); + break; + + case 'YM': + $this->setRecurType(self::RECUR_YEARLY_DATE); + break; + + case 'YD': + $this->setRecurType(self::RECUR_YEARLY_DAY); + break; + } + + // We don't support modifiers at the moment, strip them. + while ($remainder && !preg_match('/^(#\d+|\d{8})($| |T\d{6})/', $remainder)) { + $remainder = substr($remainder, 1); + } + if (!empty($remainder)) { + if (strpos($remainder, '#') === 0) { + $this->setRecurCount(substr($remainder, 1)); + } else { + list($year, $month, $mday) = sscanf($remainder, '%04d%02d%02d'); + $this->setRecurEnd(new Horde_Date(array('year' => $year, + 'month' => $month, + 'mday' => $mday, + 'hour' => 23, + 'min' => 59, + 'sec' => 59))); + } + } + } + + /** + * Creates a vCalendar 1.0 recurrence rule. + * + * @link http://www.imc.org/pdi/vcal-10.txt + * @link http://www.shuchow.com/vCalAddendum.html + * + * @param Horde_Icalendar $calendar A Horde_Icalendar object instance. + * + * @return string A vCalendar 1.0 conform RRULE value. + */ + public function toRRule10($calendar) + { + switch ($this->recurType) { + case self::RECUR_NONE: + return ''; + + case self::RECUR_DAILY: + $rrule = 'D' . $this->recurInterval; + break; + + case self::RECUR_WEEKLY: + $rrule = 'W' . $this->recurInterval; + $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); + + for ($i = 0; $i <= 7; ++$i) { + if ($this->recurOnDay(pow(2, $i))) { + $rrule .= ' ' . $vcaldays[$i]; + } + } + break; + + case self::RECUR_MONTHLY_DATE: + $rrule = 'MD' . $this->recurInterval . ' ' . trim($this->start->mday); + break; + + case self::RECUR_MONTHLY_WEEKDAY: + $nth_weekday = (int)($this->start->mday / 7); + if (($this->start->mday % 7) > 0) { + $nth_weekday++; + } + + $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); + $rrule = 'MP' . $this->recurInterval . ' ' . $nth_weekday . '+ ' . $vcaldays[$this->start->dayOfWeek()]; + + break; + + case self::RECUR_YEARLY_DATE: + $rrule = 'YM' . $this->recurInterval . ' ' . trim($this->start->month); + break; + + case self::RECUR_YEARLY_DAY: + $rrule = 'YD' . $this->recurInterval . ' ' . $this->start->dayOfYear(); + break; + + default: + return ''; + } + + if ($this->hasRecurEnd()) { + $recurEnd = clone $this->recurEnd; + return $rrule . ' ' . $calendar->_exportDateTime($recurEnd); + } + + return $rrule . ' #' . (int)$this->getRecurCount(); + } + + /** + * Parses an iCalendar 2.0 recurrence rule. + * + * @link http://rfc.net/rfc2445.html#s4.3.10 + * @link http://rfc.net/rfc2445.html#s4.8.5 + * @link http://www.shuchow.com/vCalAddendum.html + * + * @param string $rrule An iCalendar 2.0 conform RRULE value. + */ + public function fromRRule20($rrule) + { + $this->reset(); + + // Parse the recurrence rule into keys and values. + $rdata = array(); + $parts = explode(';', $rrule); + foreach ($parts as $part) { + list($key, $value) = explode('=', $part, 2); + $rdata[strtoupper($key)] = $value; + } + + if (isset($rdata['FREQ'])) { + // Always default the recurInterval to 1. + $this->setRecurInterval(isset($rdata['INTERVAL']) ? $rdata['INTERVAL'] : 1); + + $maskdays = array( + 'SU' => Horde_Date::MASK_SUNDAY, + 'MO' => Horde_Date::MASK_MONDAY, + 'TU' => Horde_Date::MASK_TUESDAY, + 'WE' => Horde_Date::MASK_WEDNESDAY, + 'TH' => Horde_Date::MASK_THURSDAY, + 'FR' => Horde_Date::MASK_FRIDAY, + 'SA' => Horde_Date::MASK_SATURDAY, + ); + + switch (strtoupper($rdata['FREQ'])) { + case 'DAILY': + $this->setRecurType(self::RECUR_DAILY); + break; + + case 'WEEKLY': + $this->setRecurType(self::RECUR_WEEKLY); + if (isset($rdata['BYDAY'])) { + $days = explode(',', $rdata['BYDAY']); + $mask = 0; + foreach ($days as $day) { + $mask |= $maskdays[$day]; + } + $this->setRecurOnDay($mask); + } else { + // Recur on the day of the week of the original + // recurrence. + $maskdays = array( + Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY, + Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY, + Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY, + Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY, + Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY, + Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY, + Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY); + $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]); + } + break; + + case 'MONTHLY': + if (isset($rdata['BYDAY'])) { + $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); + if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) { + $this->setRecurOnDay($maskdays[$m[2]]); + $this->setRecurNthWeekday($m[1]); + } + } else { + $this->setRecurType(self::RECUR_MONTHLY_DATE); + } + break; + + case 'YEARLY': + if (isset($rdata['BYYEARDAY'])) { + $this->setRecurType(self::RECUR_YEARLY_DAY); + } elseif (isset($rdata['BYDAY'])) { + $this->setRecurType(self::RECUR_YEARLY_WEEKDAY); + if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) { + $this->setRecurOnDay($maskdays[$m[2]]); + $this->setRecurNthWeekday($m[1]); + } + if ($rdata['BYMONTH']) { + $months = explode(',', $rdata['BYMONTH']); + $this->setRecurByMonth($months); + } + } else { + $this->setRecurType(self::RECUR_YEARLY_DATE); + } + break; + } + + if (isset($rdata['UNTIL'])) { + list($year, $month, $mday) = sscanf($rdata['UNTIL'], + '%04d%02d%02d'); + $this->setRecurEnd(new Horde_Date(array('year' => $year, + 'month' => $month, + 'mday' => $mday, + 'hour' => 23, + 'min' => 59, + 'sec' => 59))); + } + if (isset($rdata['COUNT'])) { + $this->setRecurCount($rdata['COUNT']); + } + } else { + // No recurrence data - event does not recur. + $this->setRecurType(self::RECUR_NONE); + } + } + + /** + * Creates an iCalendar 2.0 recurrence rule. + * + * @link http://rfc.net/rfc2445.html#s4.3.10 + * @link http://rfc.net/rfc2445.html#s4.8.5 + * @link http://www.shuchow.com/vCalAddendum.html + * + * @param Horde_Icalendar $calendar A Horde_Icalendar object instance. + * + * @return string An iCalendar 2.0 conform RRULE value. + */ + public function toRRule20($calendar) + { + switch ($this->recurType) { + case self::RECUR_NONE: + return ''; + + case self::RECUR_DAILY: + $rrule = 'FREQ=DAILY;INTERVAL=' . $this->recurInterval; + break; + + case self::RECUR_WEEKLY: + $rrule = 'FREQ=WEEKLY;INTERVAL=' . $this->recurInterval . ';BYDAY='; + $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); + + for ($i = $flag = 0; $i <= 7; ++$i) { + if ($this->recurOnDay(pow(2, $i))) { + if ($flag) { + $rrule .= ','; + } + $rrule .= $vcaldays[$i]; + $flag = true; + } + } + break; + + case self::RECUR_MONTHLY_DATE: + $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval; + break; + + case self::RECUR_MONTHLY_WEEKDAY: + if (isset($this->recurNthDay)) { + $nth_weekday = $this->recurNthDay; + $day_of_week = log($this->recurData, 2); + } else { + $day_of_week = $this->start->dayOfWeek(); + $nth_weekday = (int)($this->start->mday / 7); + if (($this->start->mday % 7) > 0) { + $nth_weekday++; + } + } + $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); + $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval + . ';BYDAY=' . $nth_weekday . $vcaldays[$day_of_week]; + break; + + case self::RECUR_YEARLY_DATE: + $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval; + break; + + case self::RECUR_YEARLY_DAY: + $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval + . ';BYYEARDAY=' . $this->start->dayOfYear(); + break; + + case self::RECUR_YEARLY_WEEKDAY: + if (isset($this->recurNthDay)) { + $nth_weekday = $this->recurNthDay; + $day_of_week = log($this->recurData, 2); + } else { + $day_of_week = $this->start->dayOfWeek(); + $nth_weekday = (int)($this->start->mday / 7); + if (($this->start->mday % 7) > 0) { + $nth_weekday++; + } + } + $months = !empty($this->recurMonths) ? join(',', $this->recurMonths) : $this->start->month; + $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); + $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval + . ';BYDAY=' + . $nth_weekday + . $vcaldays[$day_of_week] + . ';BYMONTH=' . $this->start->month; + break; + } + + if ($this->hasRecurEnd()) { + $recurEnd = clone $this->recurEnd; + $rrule .= ';UNTIL=' . $calendar->_exportDateTime($recurEnd); + } + if ($count = $this->getRecurCount()) { + $rrule .= ';COUNT=' . $count; + } + return $rrule; + } + + /** + * Parses the recurrence data from a hash. + * + * @param array $hash The hash to convert. + * + * @return boolean True if the hash seemed valid, false otherwise. + */ + public function fromHash($hash) + { + $this->reset(); + + if (!isset($hash['interval']) || !isset($hash['cycle'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + $this->setRecurInterval((int)$hash['interval']); + + $month2number = array( + 'january' => 1, + 'february' => 2, + 'march' => 3, + 'april' => 4, + 'may' => 5, + 'june' => 6, + 'july' => 7, + 'august' => 8, + 'september' => 9, + 'october' => 10, + 'november' => 11, + 'december' => 12, + ); + + $parse_day = false; + $set_daymask = false; + $update_month = false; + $update_daynumber = false; + $update_weekday = false; + $nth_weekday = -1; + + switch ($hash['cycle']) { + case 'daily': + $this->setRecurType(self::RECUR_DAILY); + break; + + case 'weekly': + $this->setRecurType(self::RECUR_WEEKLY); + $parse_day = true; + $set_daymask = true; + break; + + case 'monthly': + if (!isset($hash['daynumber'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + switch ($hash['type']) { + case 'daynumber': + $this->setRecurType(self::RECUR_MONTHLY_DATE); + $update_daynumber = true; + break; + + case 'weekday': + $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); + $this->setRecurNthWeekday($hash['daynumber']); + $parse_day = true; + $set_daymask = true; + break; + } + break; + + case 'yearly': + if (!isset($hash['type'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + switch ($hash['type']) { + case 'monthday': + $this->setRecurType(self::RECUR_YEARLY_DATE); + $update_month = true; + $update_daynumber = true; + break; + + case 'yearday': + if (!isset($hash['month'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + $this->setRecurType(self::RECUR_YEARLY_DAY); + // Start counting days in January. + $hash['month'] = 'january'; + $update_month = true; + $update_daynumber = true; + break; + + case 'weekday': + if (!isset($hash['daynumber'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + $this->setRecurType(self::RECUR_YEARLY_WEEKDAY); + $this->setRecurNthWeekday($hash['daynumber']); + $parse_day = true; + $set_daymask = true; + + if ($hash['month'] && isset($month2number[$hash['month']])) { + $this->setRecurByMonth($month2number[$hash['month']]); + } + break; + } + } + + if (isset($hash['range-type']) && isset($hash['range'])) { + switch ($hash['range-type']) { + case 'number': + $this->setRecurCount((int)$hash['range']); + break; + + case 'date': + $recur_end = new Horde_Date($hash['range']); + $recur_end->hour = 23; + $recur_end->min = 59; + $recur_end->sec = 59; + $this->setRecurEnd($recur_end); + break; + } + } + + // Need to parse ? + $last_found_day = -1; + if ($parse_day) { + if (!isset($hash['day'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + $mask = 0; + $bits = array( + 'monday' => Horde_Date::MASK_MONDAY, + 'tuesday' => Horde_Date::MASK_TUESDAY, + 'wednesday' => Horde_Date::MASK_WEDNESDAY, + 'thursday' => Horde_Date::MASK_THURSDAY, + 'friday' => Horde_Date::MASK_FRIDAY, + 'saturday' => Horde_Date::MASK_SATURDAY, + 'sunday' => Horde_Date::MASK_SUNDAY, + ); + $days = array( + 'monday' => Horde_Date::DATE_MONDAY, + 'tuesday' => Horde_Date::DATE_TUESDAY, + 'wednesday' => Horde_Date::DATE_WEDNESDAY, + 'thursday' => Horde_Date::DATE_THURSDAY, + 'friday' => Horde_Date::DATE_FRIDAY, + 'saturday' => Horde_Date::DATE_SATURDAY, + 'sunday' => Horde_Date::DATE_SUNDAY, + ); + + foreach ($hash['day'] as $day) { + // Validity check. + if (empty($day) || !isset($bits[$day])) { + continue; + } + + $mask |= $bits[$day]; + $last_found_day = $days[$day]; + } + + if ($set_daymask) { + $this->setRecurOnDay($mask); + } + } + + if ($update_month || $update_daynumber || $update_weekday) { + if ($update_month) { + if (isset($month2number[$hash['month']])) { + $this->start->month = $month2number[$hash['month']]; + } + } + + if ($update_daynumber) { + if (!isset($hash['daynumber'])) { + $this->setRecurType(self::RECUR_NONE); + return false; + } + + $this->start->mday = $hash['daynumber']; + } + + if ($update_weekday) { + $this->setNthWeekday($nth_weekday); + } + } + + // Exceptions. + if (isset($hash['exceptions'])) { + $this->exceptions = $hash['exceptions']; + } + + if (isset($hash['completions'])) { + $this->completions = $hash['completions']; + } + + return true; + } + + /** + * Export this object into a hash. + * + * @return array The recurrence hash. + */ + public function toHash() + { + if ($this->getRecurType() == self::RECUR_NONE) { + return array(); + } + + $day2number = array( + 0 => 'sunday', + 1 => 'monday', + 2 => 'tuesday', + 3 => 'wednesday', + 4 => 'thursday', + 5 => 'friday', + 6 => 'saturday' + ); + $month2number = array( + 1 => 'january', + 2 => 'february', + 3 => 'march', + 4 => 'april', + 5 => 'may', + 6 => 'june', + 7 => 'july', + 8 => 'august', + 9 => 'september', + 10 => 'october', + 11 => 'november', + 12 => 'december' + ); + + $hash = array('interval' => $this->getRecurInterval()); + $start = $this->getRecurStart(); + + switch ($this->getRecurType()) { + case self::RECUR_DAILY: + $hash['cycle'] = 'daily'; + break; + + case self::RECUR_WEEKLY: + $hash['cycle'] = 'weekly'; + $bits = array( + 'monday' => Horde_Date::MASK_MONDAY, + 'tuesday' => Horde_Date::MASK_TUESDAY, + 'wednesday' => Horde_Date::MASK_WEDNESDAY, + 'thursday' => Horde_Date::MASK_THURSDAY, + 'friday' => Horde_Date::MASK_FRIDAY, + 'saturday' => Horde_Date::MASK_SATURDAY, + 'sunday' => Horde_Date::MASK_SUNDAY, + ); + $days = array(); + foreach ($bits as $name => $bit) { + if ($this->recurOnDay($bit)) { + $days[] = $name; + } + } + $hash['day'] = $days; + break; + + case self::RECUR_MONTHLY_DATE: + $hash['cycle'] = 'monthly'; + $hash['type'] = 'daynumber'; + $hash['daynumber'] = $start->mday; + break; + + case self::RECUR_MONTHLY_WEEKDAY: + $hash['cycle'] = 'monthly'; + $hash['type'] = 'weekday'; + $hash['daynumber'] = $start->weekOfMonth(); + $hash['day'] = array ($day2number[$start->dayOfWeek()]); + break; + + case self::RECUR_YEARLY_DATE: + $hash['cycle'] = 'yearly'; + $hash['type'] = 'monthday'; + $hash['daynumber'] = $start->mday; + $hash['month'] = $month2number[$start->month]; + break; + + case self::RECUR_YEARLY_DAY: + $hash['cycle'] = 'yearly'; + $hash['type'] = 'yearday'; + $hash['daynumber'] = $start->dayOfYear(); + break; + + case self::RECUR_YEARLY_WEEKDAY: + $hash['cycle'] = 'yearly'; + $hash['type'] = 'weekday'; + $hash['daynumber'] = $start->weekOfMonth(); + $hash['day'] = array ($day2number[$start->dayOfWeek()]); + $hash['month'] = $month2number[$start->month]; + } + + if ($this->hasRecurCount()) { + $hash['range-type'] = 'number'; + $hash['range'] = $this->getRecurCount(); + } elseif ($this->hasRecurEnd()) { + $date = $this->getRecurEnd(); + $hash['range-type'] = 'date'; + $hash['range'] = $date->datestamp(); + } else { + $hash['range-type'] = 'none'; + $hash['range'] = ''; + } + + // Recurrence exceptions + $hash['exceptions'] = $this->exceptions; + $hash['completions'] = $this->completions; + + return $hash; + } + + /** + * Returns a simple object suitable for json transport representing this + * object. + * + * Possible properties are: + * - t: type + * - i: interval + * - e: end date + * - c: count + * - d: data + * - co: completions + * - ex: exceptions + * + * @return object A simple object. + */ + public function toJson() + { + $json = new stdClass; + $json->t = $this->recurType; + $json->i = $this->recurInterval; + if ($this->hasRecurEnd()) { + $json->e = $this->recurEnd->toJson(); + } + if ($this->recurCount) { + $json->c = $this->recurCount; + } + if ($this->recurData) { + $json->d = $this->recurData; + } + if ($this->completions) { + $json->co = $this->completions; + } + if ($this->exceptions) { + $json->ex = $this->exceptions; + } + return $json; + } + +} diff --git a/lib/calendar_itip.php b/lib/calendar_itip.php new file mode 100644 index 0000000..dc9a692 --- /dev/null +++ b/lib/calendar_itip.php @@ -0,0 +1,374 @@ + + * @package @package_name@ + * + * Copyright (C) 2011, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +class calendar_itip +{ + private $rc; + private $cal; + private $sender; + private $itip_send = false; + + function __construct($cal, $identity = null) + { + $this->cal = $cal; + $this->rc = $cal->rc; + $this->sender = $identity ? $identity : $this->rc->user->get_identity(); + + $this->cal->add_hook('smtp_connect', array($this, 'smtp_connect_hook')); + } + + function set_sender_email($email) + { + if (!empty($email)) + $this->sender['email'] = $email; + } + + /** + * Send an iTip mail message + * + * @param array Event object to send + * @param string iTip method (REQUEST|REPLY|CANCEL) + * @param array Hash array with recipient data (name, email) + * @param string Mail subject + * @param string Mail body text label + * @param object Mail_mime object with message data + * @return boolean True on success, false on failure + */ + public function send_itip_message($event, $method, $recipient, $subject, $bodytext, $message = null) + { + if (!$this->sender['name']) + $this->sender['name'] = $this->sender['email']; + + if (!$message) + $message = $this->compose_itip_message($event, $method); + + $mailto = rcube_idn_to_ascii($recipient['email']); + + $headers = $message->headers(); + $headers['To'] = format_email_recipient($mailto, $recipient['name']); + $headers['Subject'] = $this->cal->gettext(array( + 'name' => $subject, + 'vars' => array('title' => $event['title'], 'name' => $this->sender['name']) + )); + + // compose a list of all event attendees + $attendees_list = array(); + foreach ((array)$event['attendees'] as $attendee) { + $attendees_list[] = ($attendee['name'] && $attendee['email']) ? + $attendee['name'] . ' <' . $attendee['email'] . '>' : + ($attendee['name'] ? $attendee['name'] : $attendee['email']); + } + + $mailbody = $this->cal->gettext(array( + 'name' => $bodytext, + 'vars' => array( + 'title' => $event['title'], + 'date' => $this->cal->lib->event_date_text($event, true), + 'attendees' => join(', ', $attendees_list), + 'sender' => $this->sender['name'], + 'organizer' => $this->sender['name'], + ) + )); + + // append links for direct invitation replies + if ($method == 'REQUEST' && ($token = $this->store_invitation($event, $recipient['email']))) { + $mailbody .= "\n\n" . $this->cal->gettext(array( + 'name' => 'invitationattendlinks', + 'vars' => array('url' => $this->cal->get_url(array('action' => 'attend', 't' => $token))), + )); + } + else if ($method == 'CANCEL') { + $this->cancel_itip_invitation($event); + } + + $message->headers($headers, true); + $message->setTXTBody(rcube_mime::format_flowed($mailbody, 79)); + + // finally send the message + $this->itip_send = true; + $sent = $this->rc->deliver_message($message, $headers['X-Sender'], $mailto, $smtp_error); + $this->itip_send = false; + + return $sent; + } + + /** + * Plugin hook to alter SMTP authentication. + * This is used if iTip messages are to be sent from an unauthenticated session + */ + public function smtp_connect_hook($p) + { + // replace smtp auth settings if we're not in an authenticated session + if ($this->itip_send && !$this->rc->user->ID) { + foreach (array('smtp_server', 'smtp_user', 'smtp_pass') as $prop) { + $p[$prop] = $this->rc->config->get("calendar_itip_$prop", $p[$prop]); + } + } + + return $p; + } + + /** + * Helper function to build a Mail_mime object to send an iTip message + * + * @param array Event object to send + * @param string iTip method (REQUEST|REPLY|CANCEL) + * @return object Mail_mime object with message data + */ + public function compose_itip_message($event, $method) + { + $from = rcube_idn_to_ascii($this->sender['email']); + $from_utf = rcube_idn_to_utf8($from); + $sender = format_email_recipient($from, $this->sender['name']); + + // truncate list attendees down to the recipient of the iTip Reply. + // constraints for a METHOD:REPLY according to RFC 5546 + if ($method == 'REPLY') { + $replying_attendee = null; $reply_attendees = array(); + foreach ($event['attendees'] as $attendee) { + if ($attendee['role'] == 'ORGANIZER') { + $reply_attendees[] = $attendee; + } + else if (strcasecmp($attedee['email'], $from) == 0 || strcasecmp($attendee['email'], $from_utf) == 0) { + $replying_attendee = $attendee; + } + } + if ($replying_attendee) { + $reply_attendees[] = $replying_attendee; + $event['attendees'] = $reply_attendees; + } + } + + // compose multipart message using PEAR:Mail_Mime + $message = new Mail_mime("\r\n"); + $message->setParam('text_encoding', 'quoted-printable'); + $message->setParam('head_encoding', 'quoted-printable'); + $message->setParam('head_charset', RCMAIL_CHARSET); + $message->setParam('text_charset', RCMAIL_CHARSET . ";\r\n format=flowed"); + $message->setContentType('multipart/alternative'); + + // compose common headers array + $headers = array( + 'From' => $sender, + 'Date' => $this->rc->user_date(), + 'Message-ID' => $this->rc->gen_message_id(), + 'X-Sender' => $from, + ); + if ($agent = $this->rc->config->get('useragent')) + $headers['User-Agent'] = $agent; + + $message->headers($headers); + + // attach ics file for this event + $ical = $this->cal->get_ical(); + $ics = $ical->export(array($event), $method, false, $method == 'REQUEST' ? array($this->cal->driver, 'get_attachment_body') : false); + $message->addAttachment($ics, 'text/calendar', 'event.ics', false, '8bit', '', RCMAIL_CHARSET . "; method=" . $method); + + return $message; + } + + + /** + * Find invitation record by token + * + * @param string Invitation token + * @return mixed Invitation record as hash array or False if not found + */ + public function get_invitation($token) + { + if ($parts = $this->decode_token($token)) { + $result = $this->rc->db->query("SELECT * FROM itipinvitations WHERE token=?", $parts['base']); + if ($result && ($rec = $this->rc->db->fetch_assoc($result))) { + $rec['event'] = unserialize($rec['event']); + $rec['attendee'] = $parts['attendee']; + return $rec; + } + } + + return false; + } + + /** + * Update the attendee status of the given invitation record + * + * @param array Invitation record as fetched with calendar_itip::get_invitation() + * @param string Attendee email address + * @param string New attendee status + */ + public function update_invitation($invitation, $email, $newstatus) + { + if (is_string($invitation)) + $invitation = $this->get_invitation($invitation); + + if ($invitation['token'] && $invitation['event']) { + // update attendee record in event data + foreach ($invitation['event']['attendees'] as $i => $attendee) { + if ($attendee['role'] == 'ORGANIZER') { + $organizer = $attendee; + } + else if ($attendee['email'] == $email) { + // nothing to be done here + if ($attendee['status'] == $newstatus) + return true; + + $invitation['event']['attendees'][$i]['status'] = $newstatus; + $this->sender = $attendee; + } + } + $invitation['event']['changed'] = new DateTime(); + + // send iTIP REPLY message to organizer + if ($organizer) { + $status = strtolower($newstatus); + if ($this->send_itip_message($invitation['event'], 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status)) + $this->rc->output->command('display_message', $this->cal->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation'); + else + $this->rc->output->command('display_message', $this->cal->gettext('itipresponseerror'), 'error'); + } + + // update record in DB + $query = $this->rc->db->query( + "UPDATE itipinvitations + SET event=? + WHERE token=?", + self::serialize_event($invitation['event']), + $invitation['token'] + ); + + if ($this->rc->db->affected_rows($query)) + return true; + } + + return false; + } + + + /** + * Create iTIP invitation token for later replies via URL + * + * @param array Hash array with event properties + * @param string Attendee email address + * @return string Invitation token + */ + public function store_invitation($event, $attendee) + { + static $stored = array(); + + if (!$event['uid'] || !$attendee) + return false; + + // generate token for this invitation + $token = $this->generate_token($event, $attendee); + $base = substr($token, 0, 40); + + // already stored this + if ($stored[$base]) + return $token; + + // delete old entry + $this->rc->db->query("DELETE FROM itipinvitations WHERE token=?", $base); + + $query = $this->rc->db->query( + "INSERT INTO itipinvitations + (token, event_uid, user_id, event, expires) + VALUES(?, ?, ?, ?, ?)", + $base, + $event['uid'], + $this->rc->user->ID, + self::serialize_event($event), + date('Y-m-d H:i:s', $event['end'] + 86400 * 2) + ); + + if ($this->rc->db->affected_rows($query)) { + $stored[$base] = 1; + return $token; + } + + return false; + } + + /** + * Mark invitations for the given event as cancelled + * + * @param array Hash array with event properties + */ + public function cancel_itip_invitation($event) + { + // flag invitation record as cancelled + $this->rc->db->query( + "UPDATE itipinvitations + SET cancelled=1 + WHERE event_uid=? AND user_id=?", + $event['uid'], + $this->rc->user->ID + ); + } + + /** + * Generate an invitation request token for the given event and attendee + * + * @param array Event hash array + * @param string Attendee email address + */ + public function generate_token($event, $attendee) + { + $base = sha1($event['uid'] . ';' . $this->rc->user->ID); + $mail = base64_encode($attendee); + $hash = substr(md5($base . $mail . $this->rc->config->get('des_key')), 0, 6); + + return "$base.$mail.$hash"; + } + + /** + * Decode the given iTIP request token and return its parts + * + * @param string Request token to decode + * @return mixed Hash array with parts or False if invalid + */ + public function decode_token($token) + { + list($base, $mail, $hash) = explode('.', $token); + + // validate and return parts + if ($mail && $hash && $hash == substr(md5($base . $mail . $this->rc->config->get('des_key')), 0, 6)) { + return array('base' => $base, 'attendee' => base64_decode($mail)); + } + + return false; + } + + /** + * Helper method to serialize the given event for storing in invitations table + */ + private static function serialize_event($event) + { + $ev = $event; + $ev['description'] = abbreviate_string($ev['description'], 100); + unset($ev['attachments']); + return serialize($ev); + } + +} diff --git a/lib/calendar_recurrence.php b/lib/calendar_recurrence.php new file mode 100644 index 0000000..d4a3641 --- /dev/null +++ b/lib/calendar_recurrence.php @@ -0,0 +1,115 @@ + + * @package @package_name@ + * + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +class calendar_recurrence +{ + private $cal; + private $event; + private $next; + private $engine; + private $duration; + private $hour = 0; + + /** + * Default constructor + * + * @param object calendar The calendar plugin instance + * @param array The event object to operate on + */ + function __construct($cal, $event) + { + // use Horde classes to compute recurring instances + // TODO: replace with something that has less than 6'000 lines of code + require_once(__DIR__ . '/Horde_Date_Recurrence.php'); + + $this->cal = $cal; + $this->event = $event; + $this->next = new Horde_Date($event['start'], $cal->timezone->getName()); + $this->hour = $this->next->hour; + + if (is_object($event['start']) && is_object($event['end'])) + $this->duration = $event['start']->diff($event['end']); + + $this->engine = new Horde_Date_Recurrence($event['start']); + $this->engine->fromRRule20(libcalendaring::to_rrule($event['recurrence'])); + + if (is_array($event['recurrence']['EXDATE'])) { + foreach ($event['recurrence']['EXDATE'] as $exdate) + $this->engine->addException($exdate->format('Y'), $exdate->format('n'), $exdate->format('j')); + } + } + + /** + * Get date/time of the next occurence of this event + * + * @return mixed DateTime object or False if recurrence ended + */ + public function next_start() + { + $time = false; + $after = clone $this->next; + $after->mday = $after->mday + 1; + if ($this->next && ($next = $this->engine->nextActiveRecurrence($after))) { + if (!$next->after($this->next)) { + // avoid endless loops if recurrence computation fails + return false; + } + if ($this->event['allday']) { + $next->hour = $this->hour; # fix time for all-day events + $next->min = 0; + } + + $time = $next->toDateTime(); + $this->next = $next; + } + + return $time; + } + + /** + * Get the next recurring instance of this event + * + * @return mixed Array with event properties or False if recurrence ended + */ + public function next_instance() + { + if ($next_start = $this->next_start()) { + $next_end = clone $next_start; + $next_end->add($this->duration); + + $next = $this->event; + $next['recurrence_id'] = $next_start->format('Y-m-d'); + $next['start'] = $next_start; + $next['end'] = $next_end; + unset($next['_formatobj']); + + return $next; + } + + return false; + } + +} diff --git a/lib/calendar_ui.php b/lib/calendar_ui.php new file mode 100644 index 0000000..bca725e --- /dev/null +++ b/lib/calendar_ui.php @@ -0,0 +1,771 @@ + + * @author Thomas Bruederli + * + * Copyright (C) 2010, Lazlo Westerhof + * Copyright (C) 2012, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +class calendar_ui +{ + private $rc; + private $cal; + private $ready = false; + public $screen; + + function __construct($cal) + { + $this->cal = $cal; + $this->rc = $cal->rc; + $this->screen = $this->rc->task == 'calendar' ? ($this->rc->action ? $this->rc->action: 'calendar') : 'other'; + } + + /** + * Calendar UI initialization and requests handlers + */ + public function init() + { + if ($this->ready) // already done + return; + + // add taskbar button + $this->cal->add_button(array( + 'command' => 'calendar', + 'class' => 'button-calendar', + 'classsel' => 'button-calendar button-selected', + 'innerclass' => 'button-inner', + 'label' => 'calendar.calendar', + ), 'taskbar'); + + // load basic client script + $this->cal->include_script('calendar_base.js'); + + $skin_path = $this->cal->local_skin_path(); + $this->cal->include_stylesheet($skin_path . '/calendar.css'); + + $this->ready = true; + } + + /** + * Register handler methods for the template engine + */ + public function init_templates() + { + $this->cal->register_handler('plugin.calendar_css', array($this, 'calendar_css')); + $this->cal->register_handler('plugin.calendar_list', array($this, 'calendar_list')); + $this->cal->register_handler('plugin.calendar_select', array($this, 'calendar_select')); + $this->cal->register_handler('plugin.identity_select', array($this, 'identity_select')); + $this->cal->register_handler('plugin.category_select', array($this, 'category_select')); + $this->cal->register_handler('plugin.freebusy_select', array($this, 'freebusy_select')); + $this->cal->register_handler('plugin.priority_select', array($this, 'priority_select')); + $this->cal->register_handler('plugin.sensitivity_select', array($this, 'sensitivity_select')); + $this->cal->register_handler('plugin.alarm_select', array($this, 'alarm_select')); + $this->cal->register_handler('plugin.recurrence_form', array($this, 'recurrence_form')); + $this->cal->register_handler('plugin.attachments_form', array($this, 'attachments_form')); + $this->cal->register_handler('plugin.attachments_list', array($this, 'attachments_list')); + $this->cal->register_handler('plugin.filedroparea', array($this, 'file_drop_area')); + $this->cal->register_handler('plugin.attendees_list', array($this, 'attendees_list')); + $this->cal->register_handler('plugin.attendees_form', array($this, 'attendees_form')); + $this->cal->register_handler('plugin.attendees_freebusy_table', array($this, 'attendees_freebusy_table')); + $this->cal->register_handler('plugin.edit_attendees_notify', array($this, 'edit_attendees_notify')); + $this->cal->register_handler('plugin.edit_recurring_warning', array($this, 'recurring_event_warning')); + $this->cal->register_handler('plugin.event_rsvp_buttons', array($this, 'event_rsvp_buttons')); + $this->cal->register_handler('plugin.angenda_options', array($this, 'angenda_options')); + $this->cal->register_handler('plugin.events_import_form', array($this, 'events_import_form')); + $this->cal->register_handler('plugin.searchform', array($this->rc->output, 'search_form')); // use generic method from rcube_template + } + + /** + * Adds CSS stylesheets to the page header + */ + public function addCSS() + { + $skin_path = $this->cal->local_skin_path(); + $this->cal->include_stylesheet($skin_path . '/fullcalendar.css'); + $this->cal->include_stylesheet($skin_path . '/jquery.miniColors.css'); + } + + /** + * Adds JS files to the page header + */ + public function addJS() + { + $this->cal->include_script('calendar_ui.js'); + $this->cal->include_script('lib/js/fullcalendar.js'); + $this->cal->include_script('lib/js/jquery.miniColors.min.js'); + } + + /** + * + */ + function calendar_css($attrib = array()) + { + $mode = $this->rc->config->get('calendar_event_coloring', $this->cal->defaults['calendar_event_coloring']); + $categories = $this->cal->driver->list_categories(); + $css = "\n"; + + foreach ((array)$categories as $class => $color) { + if (empty($color)) + continue; + + $class = 'cat-' . asciiwords(strtolower($class), true); + $css .= ".$class { color: #$color }\n"; + if ($mode > 0) { + if ($mode == 2) { + $css .= ".fc-event-$class .fc-event-bg {"; + $css .= " opacity: 0.9;"; + $css .= " filter: alpha(opacity=90);"; + } + else { + $css .= ".fc-event-$class.fc-event-skin, "; + $css .= ".fc-event-$class .fc-event-skin, "; + $css .= ".fc-event-$class .fc-event-inner {"; + } + $css .= " background-color: #" . $color . ";"; + if ($mode % 2) + $css .= " border-color: #$color;"; + $css .= "}\n"; + } + } + + $calendars = $this->cal->driver->list_calendars(); + foreach ((array)$calendars as $id => $prop) { + if (!$prop['color']) + continue; + $color = $prop['color']; + $class = 'cal-' . asciiwords($id, true); + $css .= "li.$class, #eventshow .$class { color: #$color }\n"; + if ($mode != 1) { + if ($mode == 3) { + $css .= ".fc-event-$class .fc-event-bg {"; + $css .= " opacity: 0.9;"; + $css .= " filter: alpha(opacity=90);"; + } + else { + $css .= ".fc-event-$class, "; + $css .= ".fc-event-$class .fc-event-inner {"; + } + if (!$attrib['printmode']) + $css .= " background-color: #$color;"; + if ($mode % 2 == 0) + $css .= " border-color: #$color;"; + $css .= "}\n"; + } + $css .= ".$class .handle { background-color: #$color; }"; + } + + return html::tag('style', array('type' => 'text/css'), $css); + } + + /** + * + */ + function calendar_list($attrib = array()) + { + $calendars = $this->cal->driver->list_calendars(); + + $li = ''; + foreach ((array)$calendars as $id => $prop) { + if ($attrib['activeonly'] && !$prop['active']) + continue; + + unset($prop['user_id']); + $prop['alarms'] = $this->cal->driver->alarms; + $prop['attendees'] = $this->cal->driver->attendees; + $prop['freebusy'] = $this->cal->driver->freebusy; + $prop['attachments'] = $this->cal->driver->attachments; + $prop['undelete'] = $this->cal->driver->undelete; + $prop['feedurl'] = $this->cal->get_url(array('_cal' => $this->cal->ical_feed_hash($id) . '.ics', 'action' => 'feed')); + $jsenv[$id] = $prop; + + $html_id = html_identifier($id); + $class = 'cal-' . asciiwords($id, true); + + if ($prop['readonly']) + $class .= ' readonly'; + if ($prop['class_name']) + $class .= ' '.$prop['class_name']; + + $li .= html::tag('li', array('id' => 'rcmlical' . $html_id, 'class' => $class), + html::tag('input', array('type' => 'checkbox', 'name' => '_cal[]', 'value' => $id, 'checked' => $prop['active']), '') . + html::span('handle', ' ') . + html::span('calname', $prop['name'])); + } + + $this->rc->output->set_env('calendars', $jsenv); + $this->rc->output->add_gui_object('folderlist', $attrib['id']); + + return html::tag('ul', $attrib, $li, html::$common_attrib); + } + + /** + * + */ + function angenda_options($attrib = array()) + { + $attrib += array('id' => 'agendaoptions'); + $attrib['style'] .= 'display:none'; + + $select_range = new html_select(array('name' => 'listrange', 'id' => 'agenda-listrange')); + $select_range->add(1 . ' ' . preg_replace('/\(.+\)/', '', $this->cal->gettext('days')), $days); + foreach (array(2,5,7,14,30,60,90) as $days) + $select_range->add($days . ' ' . preg_replace('/\(|\)/', '', $this->cal->gettext('days')), $days); + + $html .= html::label('agenda-listrange', $this->cal->gettext('listrange')); + $html .= $select_range->show($this->rc->config->get('calendar_agenda_range', $this->cal->defaults['calendar_agenda_range'])); + + $select_sections = new html_select(array('name' => 'listsections', 'id' => 'agenda-listsections')); + $select_sections->add('---', ''); + foreach (array('day' => 'days', 'week' => 'weeks', 'month' => 'months', 'smart' => 'smartsections') as $val => $label) + $select_sections->add(preg_replace('/\(|\)/', '', ucfirst($this->cal->gettext($label))), $val); + + $html .= html::span('spacer', ' '); + $html .= html::label('agenda-listsections', $this->cal->gettext('listsections')); + $html .= $select_sections->show($this->rc->config->get('calendar_agenda_sections', $this->cal->defaults['calendar_agenda_sections'])); + + return html::div($attrib, $html); + } + + /** + * Render a HTML select box for calendar selection + */ + function calendar_select($attrib = array()) + { + $attrib['name'] = 'calendar'; + $attrib['is_escaped'] = true; + $select = new html_select($attrib); + + foreach ((array)$this->cal->driver->list_calendars() as $id => $prop) { + if (!$prop['readonly']) + $select->add($prop['name'], $id); + } + + return $select->show(null); + } + + /** + * Render a HTML select box for user identity selection + */ + function identity_select($attrib = array()) + { + $attrib['name'] = 'identity'; + $select = new html_select($attrib); + $identities = $this->rc->user->list_identities(); + + foreach ($identities as $ident) { + $select->add(format_email_recipient($ident['email'], $ident['name']), $ident['identity_id']); + } + + return $select->show(null); + } + + /** + * Render a HTML select box to select an event category + */ + function category_select($attrib = array()) + { + $attrib['name'] = 'categories'; + $select = new html_select($attrib); + $select->add('---', ''); + foreach (array_keys((array)$this->cal->driver->list_categories()) as $cat) { + $select->add($cat, $cat); + } + + return $select->show(null); + } + + /** + * Render a HTML select box for free/busy/out-of-office property + */ + function freebusy_select($attrib = array()) + { + $attrib['name'] = 'freebusy'; + $select = new html_select($attrib); + $select->add($this->cal->gettext('free'), 'free'); + $select->add($this->cal->gettext('busy'), 'busy'); + $select->add($this->cal->gettext('outofoffice'), 'outofoffice'); + $select->add($this->cal->gettext('tentative'), 'tentative'); + return $select->show(null); + } + + /** + * Render a HTML select for event priorities + */ + function priority_select($attrib = array()) + { + $attrib['name'] = 'priority'; + $select = new html_select($attrib); + $select->add('---', '0'); + $select->add('1 '.$this->cal->gettext('highest'), '1'); + $select->add('2 '.$this->cal->gettext('high'), '2'); + $select->add('3 ', '3'); + $select->add('4 ', '4'); + $select->add('5 '.$this->cal->gettext('normal'), '5'); + $select->add('6 ', '6'); + $select->add('7 ', '7'); + $select->add('8 '.$this->cal->gettext('low'), '8'); + $select->add('9 '.$this->cal->gettext('lowest'), '9'); + return $select->show(null); + } + + /** + * Render HTML input for sensitivity selection + */ + function sensitivity_select($attrib = array()) + { + $attrib['name'] = 'sensitivity'; + $select = new html_select($attrib); + $select->add($this->cal->gettext('public'), 'public'); + $select->add($this->cal->gettext('private'), 'private'); + $select->add($this->cal->gettext('confidential'), 'confidential'); + return $select->show(null); + } + + /** + * Render HTML form for alarm configuration + */ + function alarm_select($attrib = array()) + { + return $this->cal->lib->alarm_select($attrib, $this->cal->driver->alarm_types, $this->cal->driver->alarm_absolute); + } + + /** + * + */ + function edit_attendees_notify($attrib = array()) + { + $checkbox = new html_checkbox(array('name' => '_notify', 'id' => 'edit-attendees-donotify', 'value' => 1)); + return html::div($attrib, html::label(null, $checkbox->show(1) . ' ' . $this->cal->gettext('sendnotifications'))); + } + + /** + * Generate the form for recurrence settings + */ + function recurring_event_warning($attrib = array()) + { + $attrib['id'] = 'edit-recurring-warning'; + + $radio = new html_radiobutton(array('name' => '_savemode', 'class' => 'edit-recurring-savemode')); + $form = html::label(null, $radio->show('', array('value' => 'current')) . $this->cal->gettext('currentevent')) . ' ' . + html::label(null, $radio->show('', array('value' => 'future')) . $this->cal->gettext('futurevents')) . ' ' . + html::label(null, $radio->show('all', array('value' => 'all')) . $this->cal->gettext('allevents')) . ' ' . + html::label(null, $radio->show('', array('value' => 'new')) . $this->cal->gettext('saveasnew')); + + return html::div($attrib, html::div('message', html::span('ui-icon ui-icon-alert', '') . $this->cal->gettext('changerecurringeventwarning')) . html::div('savemode', $form)); + } + + /** + * Generate the form for recurrence settings + */ + function recurrence_form($attrib = array()) + { + switch ($attrib['part']) { + // frequency selector + case 'frequency': + $select = new html_select(array('name' => 'frequency', 'id' => 'edit-recurrence-frequency')); + $select->add($this->cal->gettext('never'), ''); + $select->add($this->cal->gettext('daily'), 'DAILY'); + $select->add($this->cal->gettext('weekly'), 'WEEKLY'); + $select->add($this->cal->gettext('monthly'), 'MONTHLY'); + $select->add($this->cal->gettext('yearly'), 'YEARLY'); + $html = html::label('edit-frequency', $this->cal->gettext('frequency')) . $select->show(''); + break; + + // daily recurrence + case 'daily': + $select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval', 'id' => 'edit-recurrence-interval-daily')); + $html = html::div($attrib, html::label(null, $this->cal->gettext('every')) . $select->show(1) . html::span('label-after', $this->cal->gettext('days'))); + break; + + // weekly recurrence form + case 'weekly': + $select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval', 'id' => 'edit-recurrence-interval-weekly')); + $html = html::div($attrib, html::label(null, $this->cal->gettext('every')) . $select->show(1) . html::span('label-after', $this->cal->gettext('weeks'))); + // weekday selection + $daymap = array('sun','mon','tue','wed','thu','fri','sat'); + $checkbox = new html_checkbox(array('name' => 'byday', 'class' => 'edit-recurrence-weekly-byday')); + $first = $this->rc->config->get('calendar_first_day', 1); + for ($weekdays = '', $j = $first; $j <= $first+6; $j++) { + $d = $j % 7; + $weekdays .= html::label(array('class' => 'weekday'), $checkbox->show('', array('value' => strtoupper(substr($daymap[$d], 0, 2)))) . $this->cal->gettext($daymap[$d])) . ' '; + } + $html .= html::div($attrib, html::label(null, $this->cal->gettext('bydays')) . $weekdays); + break; + + // monthly recurrence form + case 'monthly': + $select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval', 'id' => 'edit-recurrence-interval-monthly')); + $html = html::div($attrib, html::label(null, $this->cal->gettext('every')) . $select->show(1) . html::span('label-after', $this->cal->gettext('months'))); + + $checkbox = new html_checkbox(array('name' => 'bymonthday', 'class' => 'edit-recurrence-monthly-bymonthday')); + for ($monthdays = '', $d = 1; $d <= 31; $d++) { + $monthdays .= html::label(array('class' => 'monthday'), $checkbox->show('', array('value' => $d)) . $d); + $monthdays .= $d % 7 ? ' ' : html::br(); + } + + // rule selectors + $radio = new html_radiobutton(array('name' => 'repeatmode', 'class' => 'edit-recurrence-monthly-mode')); + $table = new html_table(array('cols' => 2, 'border' => 0, 'cellpadding' => 0, 'class' => 'formtable')); + $table->add('label', html::label(null, $radio->show('BYMONTHDAY', array('value' => 'BYMONTHDAY')) . ' ' . $this->cal->gettext('each'))); + $table->add(null, $monthdays); + $table->add('label', html::label(null, $radio->show('', array('value' => 'BYDAY')) . ' ' . $this->cal->gettext('onevery'))); + $table->add(null, $this->rrule_selectors($attrib['part'])); + + $html .= html::div($attrib, $table->show()); + + break; + + // annually recurrence form + case 'yearly': + $select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval', 'id' => 'edit-recurrence-interval-yearly')); + $html = html::div($attrib, html::label(null, $this->cal->gettext('every')) . $select->show(1) . html::span('label-after', $this->cal->gettext('years'))); + // month selector + $monthmap = array('','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'); + $checkbox = new html_checkbox(array('name' => 'bymonth', 'class' => 'edit-recurrence-yearly-bymonth')); + for ($months = '', $m = 1; $m <= 12; $m++) { + $months .= html::label(array('class' => 'month'), $checkbox->show(null, array('value' => $m)) . $this->cal->gettext($monthmap[$m])); + $months .= $m % 4 ? ' ' : html::br(); + } + $html .= html::div($attrib + array('id' => 'edit-recurrence-yearly-bymonthblock'), $months); + + // day rule selection + $html .= html::div($attrib, html::label(null, $this->cal->gettext('onevery')) . $this->rrule_selectors($attrib['part'], '---')); + break; + + // end of recurrence form + case 'until': + $radio = new html_radiobutton(array('name' => 'repeat', 'class' => 'edit-recurrence-until')); + $select = $this->interval_selector(array('name' => 'times', 'id' => 'edit-recurrence-repeat-times')); + $input = new html_inputfield(array('name' => 'untildate', 'id' => 'edit-recurrence-enddate', 'size' => "10")); + + $table = new html_table(array('cols' => 2, 'border' => 0, 'cellpadding' => 0, 'class' => 'formtable')); + + $table->add('label', ucfirst($this->cal->gettext('recurrencend'))); + $table->add(null, html::label(null, $radio->show('', array('value' => '', 'id' => 'edit-recurrence-repeat-forever')) . ' ' . + $this->cal->gettext('forever'))); + + $table->add('label', ''); + $table->add(null, $radio->show('', array('value' => 'count', 'id' => 'edit-recurrence-repeat-count')) . ' ' . + $this->cal->gettext(array( + 'name' => 'forntimes', + 'vars' => array('nr' => $select->show(1))) + )); + + $table->add('label', ''); + $table->add(null, $radio->show('', array('value' => 'until', 'id' => 'edit-recurrence-repeat-until')) . ' ' . + $this->cal->gettext('untildate') . ' ' . $input->show('')); + $html = $table->show(); + break; + } + + return $html; + } + + /** + * Input field for interval selection + */ + private function interval_selector($attrib) + { + $select = new html_select($attrib); + $select->add(range(1,30), range(1,30)); + return $select; + } + + /** + * Drop-down menus for recurrence rules like "each last sunday of" + */ + private function rrule_selectors($part, $noselect = null) + { + // rule selectors + $select_prefix = new html_select(array('name' => 'bydayprefix', 'id' => "edit-recurrence-$part-prefix")); + if ($noselect) $select_prefix->add($noselect, ''); + $select_prefix->add(array( + $this->cal->gettext('first'), + $this->cal->gettext('second'), + $this->cal->gettext('third'), + $this->cal->gettext('fourth'), + $this->cal->gettext('last') + ), + array(1, 2, 3, 4, -1)); + + $select_wday = new html_select(array('name' => 'byday', 'id' => "edit-recurrence-$part-byday")); + if ($noselect) $select_wday->add($noselect, ''); + + $daymap = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday'); + $first = $this->rc->config->get('calendar_first_day', 1); + for ($j = $first; $j <= $first+6; $j++) { + $d = $j % 7; + $select_wday->add($this->cal->gettext($daymap[$d]), strtoupper(substr($daymap[$d], 0, 2))); + } + + return $select_prefix->show() . ' ' . $select_wday->show(); + } + + /** + * Form for uploading and importing events + */ + function events_import_form($attrib = array()) + { + if (!$attrib['id']) + $attrib['id'] = 'rcmImportForm'; + + // Get max filesize, enable upload progress bar + $max_filesize = rcube_upload_init(); + + $input = new html_inputfield(array( + 'type' => 'file', 'name' => '_data', 'size' => $attrib['uploadfieldsize'])); + + $select = new html_select(array('name' => '_range', 'id' => 'event-import-range')); + $select->add(array( + $this->cal->gettext('onemonthback'), + $this->cal->gettext(array('name' => 'nmonthsback', 'vars' => array('nr'=>2))), + $this->cal->gettext(array('name' => 'nmonthsback', 'vars' => array('nr'=>6))), + $this->cal->gettext(array('name' => 'nmonthsback', 'vars' => array('nr'=>12))), + $this->cal->gettext('all'), + ), + array('1','2','6','12',0)); + + $html .= html::div('form-section', + html::div(null, $input->show()) . + html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) + ); + + $html .= html::div('form-section', + html::label('event-import-calendar', $this->cal->gettext('calendar')) . + $this->calendar_select(array('name' => 'calendar', 'id' => 'event-import-calendar')) + ); + + $html .= html::div('form-section', + html::label('event-import-range', $this->cal->gettext('importrange')) . + $select->show(1) + ); + + $this->rc->output->add_gui_object('importform', $attrib['id']); + $this->rc->output->add_label('import'); + + return html::tag('form', array('action' => $this->rc->url(array('task' => 'calendar', 'action' => 'import_events')), + 'method' => "post", 'enctype' => 'multipart/form-data', 'id' => $attrib['id']), + $html + ); + } + + /** + * Generate the form for event attachments upload + */ + function attachments_form($attrib = array()) + { + // add ID if not given + if (!$attrib['id']) + $attrib['id'] = 'rcmUploadForm'; + + // Get max filesize, enable upload progress bar + $max_filesize = rcube_upload_init(); + + $button = new html_inputfield(array('type' => 'button')); + $input = new html_inputfield(array( + 'type' => 'file', 'name' => '_attachments[]', + 'multiple' => 'multiple', 'size' => $attrib['attachmentfieldsize'])); + + return html::div($attrib, + html::div(null, $input->show()) . + html::div('formbuttons', $button->show(rcube_label('upload'), array('class' => 'button mainaction', + 'onclick' => JS_OBJECT_NAME . ".upload_file(this.form)"))) . + html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) + ); + } + + /** + * Register UI object for HTML5 drag & drop file upload + */ + function file_drop_area($attrib = array()) + { + if ($attrib['id']) { + $this->rc->output->add_gui_object('filedrop', $attrib['id']); + $this->rc->output->set_env('filedrop', array('action' => 'upload', 'fieldname' => '_attachments')); + } + } + + /** + * Generate HTML element for attachments list + */ + function attachments_list($attrib = array()) + { + if (!$attrib['id']) + $attrib['id'] = 'rcmAttachmentList'; + + $skin_path = $this->cal->local_skin_path(); + if ($attrib['deleteicon']) { + $_SESSION[calendar::SESSION_KEY . '_deleteicon'] = $skin_path . $attrib['deleteicon']; + $this->rc->output->set_env('deleteicon', $skin_path . $attrib['deleteicon']); + } + if ($attrib['cancelicon']) + $this->rc->output->set_env('cancelicon', $skin_path . $attrib['cancelicon']); + if ($attrib['loadingicon']) + $this->rc->output->set_env('loadingicon', $skin_path . $attrib['loadingicon']); + + $this->rc->output->add_gui_object('attachmentlist', $attrib['id']); + $this->attachmentlist_id = $attrib['id']; + + return html::tag('ul', $attrib, '', html::$common_attrib); + } + + /** + * Handler for calendar form template. + * The form content could be overriden by the driver + */ + function calendar_editform($action, $calendar = array()) + { + // compose default calendar form fields + $input_name = new html_inputfield(array('name' => 'name', 'id' => 'calendar-name', 'size' => 20)); + $input_color = new html_inputfield(array('name' => 'color', 'id' => 'calendar-color', 'size' => 6)); + + $formfields = array( + 'name' => array( + 'label' => $this->cal->gettext('name'), + 'value' => $input_name->show($calendar['name']), + 'id' => 'calendar-name', + ), + 'color' => array( + 'label' => $this->cal->gettext('color'), + 'value' => $input_color->show($calendar['color']), + 'id' => 'calendar-color', + ), + ); + + if ($this->cal->driver->alarms) { + $checkbox = new html_checkbox(array('name' => 'showalarms', 'id' => 'calendar-showalarms', 'value' => 1)); + $formfields['showalarms'] = array( + 'label' => $this->cal->gettext('showalarms'), + 'value' => $checkbox->show($calendar['showalarms']?1:0), + 'id' => 'calendar-showalarms', + ); + } + + // allow driver to extend or replace the form content + return html::tag('form', array('action' => "#", 'method' => "get", 'id' => 'calendarpropform'), + $this->cal->driver->calendar_form($action, $calendar, $formfields) + ); + } + + /** + * + */ + function attendees_list($attrib = array()) + { + $table = new html_table(array('cols' => 5, 'border' => 0, 'cellpadding' => 0, 'class' => 'rectable')); + $table->add_header('role', $this->cal->gettext('role')); + $table->add_header('name', $this->cal->gettext('attendee')); + $table->add_header('availability', $this->cal->gettext('availability')); + $table->add_header('confirmstate', $this->cal->gettext('confirmstate')); + $table->add_header('options', ''); + + return $table->show($attrib); + } + + /** + * + */ + function attendees_form($attrib = array()) + { + $input = new html_inputfield(array('name' => 'participant', 'id' => 'edit-attendee-name', 'size' => 30)); + $checkbox = new html_checkbox(array('name' => 'invite', 'id' => 'edit-attendees-invite', 'value' => 1)); + + return html::div($attrib, + html::div(null, $input->show() . " " . + html::tag('input', array('type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-add', 'value' => $this->cal->gettext('addattendee'))) . " " . + html::tag('input', array('type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-schedule', 'value' => $this->cal->gettext('scheduletime').'...'))) . + html::p('attendees-invitebox', html::label(null, $checkbox->show(1) . $this->cal->gettext('sendinvitations'))) + ); + } + + /** + * + */ + function attendees_freebusy_table($attrib = array()) + { + $table = new html_table(array('cols' => 2, 'border' => 0, 'cellspacing' => 0)); + $table->add('attendees', + html::tag('h3', 'boxtitle', $this->cal->gettext('tabattendees')) . + html::div('timesheader', ' ') . + html::div(array('id' => 'schedule-attendees-list', 'class' => 'attendees-list'), '') + ); + $table->add('times', + html::div('scroll', + html::tag('table', array('id' => 'schedule-freebusy-times', 'border' => 0, 'cellspacing' => 0), html::tag('thead') . html::tag('tbody')) . + html::div(array('id' => 'schedule-event-time', 'style' => 'display:none'), ' ') + ) + ); + + return $table->show($attrib); + } + + /** + * Render event details in a table + */ + function event_details_table($event, $title) + { + $table = new html_table(array('cols' => 2, 'border' => 0, 'class' => 'calendar-eventdetails')); + $table->add('ititle', $title); + $table->add('title', Q($event['title'])); + $table->add('label', $this->cal->gettext('date')); + $table->add('location', Q($this->cal->lib->event_date_text($event))); + if ($event['location']) { + $table->add('label', $this->cal->gettext('location')); + $table->add('location', Q($event['location'])); + } + + return $table->show(); + } + + /** + * + */ + function event_invitebox($attrib = array()) + { + if ($this->cal->event) { + return html::div($attrib, + $this->event_details_table($this->cal->event, $this->cal->gettext('itipinvitation')) . + $this->cal->invitestatus + ); + } + + return ''; + } + + function event_rsvp_buttons($attrib = array()) + { + $attrib += array('type' => 'button'); + foreach (array('accepted','tentative','declined') as $method) { + $buttons .= html::tag('input', array( + 'type' => $attrib['type'], + 'name' => $attrib['iname'], + 'class' => 'button', + 'rel' => $method, + 'value' => $this->cal->gettext('itip' . $method), + )); + } + + return html::div($attrib, + html::div('label', $this->cal->gettext('acceptinvitation')) . + html::div('rsvp-buttons', $buttons)); + } + +} diff --git a/lib/js/fullcalendar.js b/lib/js/fullcalendar.js new file mode 100644 index 0000000..f790eea --- /dev/null +++ b/lib/js/fullcalendar.js @@ -0,0 +1,5917 @@ +/** + * @preserve + * FullCalendar v1.5.4-rcube-0.9.0 + * https://github.com/roundcube/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 + * Copyright (c) 2011, Kolab Systems AG + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Wed Nov 7 16:28:11 2012 +0100 + * + */ + +(function($, undefined) { + + +var defaults = { + + // display + defaultView: 'month', + aspectRatio: 1.35, + header: { + left: 'title', + center: '', + right: 'today prev,next' + }, + weekends: true, + currentTimeIndicator: false, + + // 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]{ '—'[ MMM] d yyyy}", + day: 'dddd, MMM d, yyyy', + list: 'MMM d, yyyy', + table: 'MMM d, yyyy' + }, + columnFormat: { + month: 'ddd', + week: 'ddd M/d', + day: 'dddd M/d', + list: 'dddd, MMM d, yyyy', + table: 'MMM d, yyyy' + }, + 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: ' ◄ ', + next: ' ► ', + prevYear: ' << ', + nextYear: ' >> ', + today: 'today', + month: 'month', + week: 'week', + day: 'day', + list: 'list', + table: 'table' + }, + listTexts: { + until: 'until', + past: 'Past events', + today: 'Today', + tomorrow: 'Tomorrow', + thisWeek: 'This week', + nextWeek: 'Next week', + thisMonth: 'This month', + nextMonth: 'Next month', + future: 'Future events', + week: 'W' + }, + + // list/table options + listSections: 'month', // false|'day'|'week'|'month'|'smart' + listRange: 30, // number of days to be displayed + listPage: 7, // number of days to jump when paging + tableCols: ['handle', 'date', 'time', 'title'], + + // 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: ' ► ', + next: ' ◄ ', + prevYear: ' >> ', + nextYear: ' << ' + }, + buttonIcons: { + prev: 'circle-triangle-e', + next: 'circle-triangle-w' + } +}; + + + +var fc = $.fullCalendar = { version: "1.5.4-rcube-0.9.0" }; +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 = $("
    ") + .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 = + $("
    ") + .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.trigger('viewRender', currentView); + 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(source) { + fetchEvents(currentView.visStart, currentView.visEnd, source); // 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.trigger('viewRender', currentView); + 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(); + } else if (name.indexOf('list') == 0 || name == 'tableCols') { + options[name] = value; + currentView.start = null; // force re-render + } else if (name == 'maxHeight') { + options[name] = value; + } + } + + + 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 = $("") + .append( + $("") + .append(renderSection('left')) + .append(renderSection('center')) + .append(renderSection('right')) + ); + return element; + } + } + + + function destroy() { + element.remove(); + } + + + function renderSection(position) { + var e = $("" + + ""; + for (i=0; i"; // need fc- for setDayID + } + s += + "" + + "" + + ""; + for (i=0; i"; + for (j=0; j" + // need fc- for setDayID + "
    " + + (showNumbers ? + "
    " : + '' + ) + + "
    " + + "
     
    " + + "
    " + + "
    " + + ""; + } + s += + ""; + } + s += + "
    " + + "
    "); + var buttonStr = options.header[position]; + if (buttonStr) { + $.each(buttonStr.split(' '), function(i) { + if (i > 0) { + e.append(""); + } + var prevButton; + $.each(this.split(','), function(j, buttonName) { + if (buttonName == 'title') { + e.append("

     

    "); + 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 = $( + "" + + "" + + "" + + (icon ? + "" + + "" + + "" : + text + ) + + "" + + "" + + "" + + "" + ); + 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, src) { + rangeStart = start; + rangeEnd = end; + // partially clear cache if refreshing one source only (issue #1061) + cache = typeof src != 'undefined' ? $.grep(cache, function(e) { return !isSourcesEqual(e.source, src); }) : []; + var fetchID = ++currentFetchID; + var len = sources.length; + pendingSourceCnt = typeof src == 'undefined' ? len : 1; + for (var i=0; i)), 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; ii; 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'; + } , + W : function(d) { return iso8601Week(d); } +}; + + +// Determine the week of the year based on the ISO 8601 definition. +// copied from jquery UI Datepicker +var iso8601Week = function(date) { + var checkDate = cloneDate(date); + // Find Thursday of this week starting on Monday + checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); + var time = checkDate.getTime(); + checkDate.setMonth(0); // Compare with Jan 1 + checkDate.setDate(1); + return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; +}; + + +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 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=0; i--) { + res = obj[parts[i].toLowerCase()]; + if (res !== undefined) { + return res; + } + } + return obj['']; +} + + +function htmlEscape(s) { + return s.replace(/&/g, '&') + .replace(//g, '>') + .replace(/'/g, ''') + .replace(/"/g, '"') + .replace(/\n/g, '
    '); +} + + +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" + + "
    "; + 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 = + $("
    ") + .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" + + "" + + "" + + " "; + for (i=0; i"; // fc- needed for setDayID + } + s += + " " + + "" + + "" + + "" + + "" + + " "; + for (i=0; i" + // fc- needed for setDayID + "
    " + + "
    " + + "
     
    " + + "
    " + + "
    " + + ""; + } + s += + " " + + "" + + "" + + ""; + 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 = + $("
    ") + .appendTo(element); + + if (opt('allDaySlot')) { + + daySegmentContainer = + $("
    ") + .appendTo(slotLayer); + + s = + "" + + "" + + "" + + "" + + "" + + "" + + "
    " + opt('allDayText') + "" + + "
    " + + "
     
    "; + 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( + "
    " + + "
    " + + "
    " + ); + + }else{ + + daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() + + } + + slotScroller = + $("
    ") + .appendTo(slotLayer); + + slotContent = + $("
    ") + .appendTo(slotScroller); + + slotSegmentContainer = + $("
    ") + .appendTo(slotContent); + + s = + "" + + ""; + d = zeroDate(); + maxd = addMinutes(cloneDate(d), maxMinute); + addMinutes(d, minMinute); + slotCnt = 0; + for (i=0; d < maxd; i++) { + minutes = d.getMinutes(); + s += + "" + + "" + + "" + + ""; + addMinutes(d, opt('slotMinutes')); + slotCnt++; + } + s += + "" + + "
    " + + ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') + + "" + + "
     
    " + + "
    "; + 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= 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, helperOption = opt('selectHelper'); + hoverListener.start(function(cell, origCell) { + clearSelection(); + if (cell && (cell.col == origCell.col || !helperOption) && !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; + var timeLineInterval; + + + + /* Rendering + ----------------------------------------------------------------------------*/ + + + function renderEvents(events, modifiedEventId) { + reportEvents(events); + var i, len=events.length, + dayEvents=[], + slotEvents=[]; + for (i=0; i 1; + + if (rtl = opt('isRTL')) { + dis = -1; + dit = colCnt - 1; + }else{ + dis = 1; + dit = 0; + } + + // calculate position/dimensions, create html + for (i=0; i" + + "
    " + + "
    " + + "
    " + + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + + "
    " + + "
    " + + "
    " + + "
    " + + htmlEscape(event.title) + + "
    " + + "
    " + + "
    " + + "
    "; // close inner + if (seg.isEnd && isEventResizable(event)) { + html += + "
    =
    "; + } + html += + ""; + 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); + } + + + // draw a horizontal line indicating the current time (#143) + function setTimeIndicator() + { + var container = getBodyContent(); + var timeline = container.children('.fc-timeline'); + if (timeline.length == 0) { // if timeline isn't there, add it + timeline = $('
    ').addClass('fc-timeline').appendTo(container); + } + + var cur_time = new Date(); + if (t.visStart < cur_time && t.visEnd > cur_time) { + timeline.show(); + } + else { + timeline.hide(); + return; + } + + var secs = (cur_time.getHours() * 60 * 60) + (cur_time.getMinutes() * 60) + cur_time.getSeconds(); + var percents = secs / 86400; // 24 * 60 * 60 = 86400, # of seconds in a day + + timeline.css('top', Math.floor(container.height() * percents - 1) + 'px'); + + if (t.name == 'agendaWeek') { // week view, don't want the timeline to go the whole way across + var daycol = $('.fc-today', t.element); + var left = daycol.position().left + 1; + var width = daycol.width(); + timeline.css({ left: left + 'px', width: width + 'px' }); + } + } + + + /* 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 maxHeight) { + seg.overflow = true; + } + else { + seg.top = top; + top += seg.outerHeight; + } + for (k=seg.startCol; k 1) { + element = $('').addClass('fc-more-link').html('+'+link.count).appendTo(container); + element[0].style.position = 'absolute'; + element[0].style.left = link.seg.left + 'px'; + element[0].style.top = (link.top + rowDiv[0].offsetTop) + 'px'; + triggerRes = trigger('overflowRender', link, { count:link.count, date:link.date }, element); + if (triggerRes === false) + element.remove(); + } + else { + link.seg.top = link.top; + link.seg.overflow = false; + } + } + } + } + + + function renderTempDaySegs(segs, adjustRow, adjustTop) { + var tempContainer = $("
    "); + 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" + + ""; + if (!event.allDay && seg.isStart) { + html += + "" + + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + + ""; + } + html += + "" + htmlEscape(event.title) + "" + + "
    "; + if (seg.isEnd && isEventResizable(event)) { + html += + "
    " + + "   " + // makes hit area a lot better for IE6/7 + "
    "; + } + html += + ""; + 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 div'); // optimal selector? + } + return rowDivs; + } + + + function getRowTops(rowDivs) { + var i; + var rowCnt = rowDivs.length; + var tops = []; + for (i=0; i selection for IE + element + .mousedown(function(ev) { // prevent native
    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 = $("
    "); + } + 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= rows[i][0] && y < rows[i][1]) { + r = i; + break; + } + } + for (i=0; i= 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 = {}; + }; + +} + +/* Additional view: list (by bruederli@kolabsys.com) +---------------------------------------------------------------------------------*/ + +function ListEventRenderer() { + var t = this; + + // exports + t.renderEvents = renderEvents; + t.renderEventTime = renderEventTime; + t.compileDaySegs = compileSegs; // for DayEventRenderer + t.clearEvents = clearEvents; + t.lazySegBind = lazySegBind; + t.sortCmp = sortCmp; + + // imports + DayEventRenderer.call(t); + var opt = t.opt; + var trigger = t.trigger; + var reportEvents = t.reportEvents; + var reportEventClear = t.reportEventClear; + var reportEventElement = t.reportEventElement; + var eventElementHandlers = t.eventElementHandlers; + var showEvents = t.showEvents; + var hideEvents = t.hideEvents; + var getListContainer = t.getDaySegmentContainer; + var calendar = t.calendar; + var formatDate = calendar.formatDate; + var formatDates = calendar.formatDates; + + + /* Rendering + --------------------------------------------------------------------*/ + + function clearEvents() { + reportEventClear(); + getListContainer().empty(); + } + + function renderEvents(events, modifiedEventId) { + events.sort(sortCmp); + reportEvents(events); + renderSegs(compileSegs(events), modifiedEventId); + } + + function compileSegs(events) { + var segs = []; + var colFormat = opt('titleFormat', 'day'); + var firstDay = opt('firstDay'); + var segmode = opt('listSections'); + var event, i, dd, wd, md, seg, segHash, curSegHash, segDate, curSeg = -1; + var today = clearTime(new Date()); + var weekstart = addDays(cloneDate(today), -((today.getDay() - firstDay + 7) % 7)); + + for (i=0; i < events.length; i++) { + event = events[i]; + + // skip events out of range + if ((event.end || event.start) < t.start || event.start > t.visEnd) + continue; + + // define sections of this event + // create smart sections such as today, tomorrow, this week, next week, next month, ect. + segDate = cloneDate(event.start < t.start && event.end > t.start ? t.start : event.start, true); + dd = dayDiff(segDate, today); + wd = Math.floor(dayDiff(segDate, weekstart) / 7); + md = segDate.getMonth() + ((segDate.getYear() - today.getYear()) * 12) - today.getMonth(); + + // build section title + if (segmode == 'smart') { + if (dd < 0) { + segHash = opt('listTexts', 'past'); + } else if (dd == 0) { + segHash = opt('listTexts', 'today'); + } else if (dd == 1) { + segHash = opt('listTexts', 'tomorrow'); + } else if (wd == 0) { + segHash = opt('listTexts', 'thisWeek'); + } else if (wd == 1) { + segHash = opt('listTexts', 'nextWeek'); + } else if (md == 0) { + segHash = opt('listTexts', 'thisMonth'); + } else if (md == 1) { + segHash = opt('listTexts', 'nextMonth'); + } else if (md > 1) { + segHash = opt('listTexts', 'future'); + } + } else if (segmode == 'month') { + segHash = formatDate(segDate, 'MMMM yyyy'); + } else if (segmode == 'week') { + segHash = opt('listTexts', 'week') + formatDate(segDate, ' W'); + } else if (segmode == 'day') { + segHash = formatDate(segDate, colFormat); + } else { + segHash = ''; + } + + // start new segment + if (segHash != curSegHash) { + segs[++curSeg] = { events: [], start: segDate, title: segHash, daydiff: dd, weekdiff: wd, monthdiff: md }; + curSegHash = segHash; + } + + segs[curSeg].events.push(event); + } + + return segs; + } + + function sortCmp(a, b) { + var sd = a.start.getTime() - b.start.getTime(); + return sd || (a.end ? a.end.getTime() : 0) - (b.end ? b.end.getTime() : 0); + } + + function renderSegs(segs, modifiedEventId) { + var tm = opt('theme') ? 'ui' : 'fc'; + var headerClass = tm + "-widget-header"; + var contentClass = tm + "-widget-content"; + var i, j, seg, event, times, s, skinCss, skinCssAttr, classes, segContainer, eventElement, eventElements, triggerRes; + + for (j=0; j < segs.length; j++) { + seg = segs[j]; + + if (seg.title) { + $('
    ' + htmlEscape(seg.title) + '
    ').appendTo(getListContainer()); + } + segContainer = $('
    ').addClass('fc-list-section ' + contentClass).appendTo(getListContainer()); + s = ''; + + for (i=0; i < seg.events.length; i++) { + event = seg.events[i]; + times = renderEventTime(event, seg); + skinCss = getSkinCss(event, opt); + skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); + classes = ['fc-event', 'fc-event-skin', 'fc-event-vert', 'fc-corner-top', 'fc-corner-bottom'].concat(event.className); + if (event.source && event.source.className) { + classes = classes.concat(event.source.className); + } + + s += + "
    " + + "
    " + + "
    " + + "
    " + + (times[0] ? '' + times[0] + ' ' : '') + + (times[1] ? '' + times[1] + '' : '') + + "
    " + + "
    " + + "
    " + + "
    " + + htmlEscape(event.title) + + "
    " + + "
    " + + "
    " + + "
    " + // close inner + "
    "; // close outer + } + + segContainer[0].innerHTML = s; + eventElements = segContainer.children(); + + // retrieve elements, run through eventRender callback, bind event handlers + for (i=0; i < seg.events.length; i++) { + event = seg.events[i]; + 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).appendTo(segContainer); + } + if (event._id === modifiedEventId) { + eventElementHandlers(event, eventElement, seg); + } else { + eventElement[0]._fci = i; // for lazySegBind + } + reportEventElement(event, eventElement); + } + } + + lazySegBind(segContainer, seg, eventElementHandlers); + } + + markFirstLast(getListContainer()); + } + + // event time/date range to display + function renderEventTime(event, seg) { + var timeFormat = opt('timeFormat'); + var dateFormat = opt('columnFormat'); + var segmode = opt('listSections'); + var duration = event.end ? event.end.getTime() - event.start.getTime() : 0; + var datestr = '', timestr = ''; + + if (segmode == 'smart') { + if (event.start < seg.start) { + datestr = opt('listTexts', 'until') + ' ' + formatDate(event.end, (event.allDay || event.end.getDate() != seg.start.getDate()) ? dateFormat : timeFormat); + } else if (duration > DAY_MS) { + datestr = formatDates(event.start, event.end, dateFormat + '{ - ' + dateFormat + '}'); + } else if (seg.daydiff == 0) { + datestr = opt('listTexts', 'today'); + } else if (seg.daydiff == 1) { + datestr = opt('listTexts', 'tomorrow'); + } else if (seg.weekdiff == 0 || seg.weekdiff == 1) { + datestr = formatDate(event.start, 'dddd'); + } else if (seg.daydiff > 1 || seg.daydiff < 0) { + datestr = formatDate(event.start, dateFormat); + } + } else if (segmode != 'day') { + datestr = formatDates(event.start, event.end, dateFormat + (duration > DAY_MS ? '{ - ' + dateFormat + '}' : '')); + } + + if (!datestr && event.allDay) { + timestr = opt('allDayText'); + } else if ((duration < DAY_MS || !datestr) && !event.allDay) { + timestr = formatDates(event.start, event.end, timeFormat); + } + + return [datestr, timestr]; + } + + function lazySegBind(container, seg, bindHandlers) { + container.unbind('mouseover').mouseover(function(ev) { + var parent = ev.target, e = parent, i, event; + while (parent != this) { + e = parent; + parent = parent.parentNode; + } + if ((i = e._fci) !== undefined) { + e._fci = undefined; + event = seg.events[i]; + bindHandlers(event, container.children().eq(i), seg); + $(ev.target).trigger(ev); + } + ev.stopPropagation(); + }); + } + +} + + +fcViews.list = ListView; + + +function ListView(element, calendar) { + var t = this; + + // exports + t.render = render; + t.select = dummy; + t.unselect = dummy; + t.getDaySegmentContainer = function(){ return body; }; + + // imports + View.call(t, element, calendar, 'list'); + ListEventRenderer.call(t); + var opt = t.opt; + var trigger = t.trigger; + var clearEvents = t.clearEvents; + var reportEventClear = t.reportEventClear; + var formatDates = calendar.formatDates; + var formatDate = calendar.formatDate; + + // overrides + t.setWidth = setWidth; + t.setHeight = setHeight; + + // locals + var body; + var firstDay; + var nwe; + var tm; + var colFormat; + + + function render(date, delta) { + if (delta) { + addDays(date, opt('listPage') * delta); + } + t.start = t.visStart = cloneDate(date, true); + t.end = addDays(cloneDate(t.start), opt('listPage')); + t.visEnd = addDays(cloneDate(t.start), opt('listRange')); + addMinutes(t.visEnd, -1); // set end to 23:59 + t.title = formatDates(date, t.visEnd, opt('titleFormat')); + + updateOptions(); + + if (!body) { + buildSkeleton(); + } else { + clearEvents(); + } + } + + + function updateOptions() { + firstDay = opt('firstDay'); + nwe = opt('weekends') ? 0 : 1; + tm = opt('theme') ? 'ui' : 'fc'; + colFormat = opt('columnFormat', 'day'); + } + + + function buildSkeleton() { + body = $('
    ').addClass('fc-list-content').appendTo(element); + } + + function setHeight(height, dateChanged) { + if (!opt('listNoHeight')) + body.css('height', (height-1)+'px').css('overflow', 'auto'); + } + + function setWidth(width) { + // nothing to be done here + } + + function dummy() { + // Stub. + } + +} + +/* Additional view: table (by bruederli@kolabsys.com) +---------------------------------------------------------------------------------*/ + +function TableEventRenderer() { + var t = this; + + // imports + ListEventRenderer.call(t); + var opt = t.opt; + var sortCmp = t.sortCmp; + var trigger = t.trigger; + var compileSegs = t.compileDaySegs; + var reportEvents = t.reportEvents; + var reportEventClear = t.reportEventClear; + var reportEventElement = t.reportEventElement; + var eventElementHandlers = t.eventElementHandlers; + var renderEventTime = t.renderEventTime; + var showEvents = t.showEvents; + var hideEvents = t.hideEvents; + var getListContainer = t.getDaySegmentContainer; + var lazySegBind = t.lazySegBind; + var calendar = t.calendar; + var formatDate = calendar.formatDate; + var formatDates = calendar.formatDates; + + // exports + t.renderEvents = renderEvents; + t.clearEvents = clearEvents; + + + /* Rendering + --------------------------------------------------------------------*/ + + function clearEvents() { + reportEventClear(); + getListContainer().children('tbody').remove(); + } + + function renderEvents(events, modifiedEventId) { + events.sort(sortCmp); + reportEvents(events); + renderSegs(compileSegs(events), modifiedEventId); + getListContainer().removeClass('fc-list-smart fc-list-day fc-list-month fc-list-week').addClass('fc-list-' + opt('listSections')); + } + + function renderSegs(segs, modifiedEventId) { + var tm = opt('theme') ? 'ui' : 'fc'; + var table = getListContainer(); + var headerClass = tm + "-widget-header"; + var contentClass = tm + "-widget-content"; + var tableCols = opt('tableCols'); + var timecol = $.inArray('time', tableCols) >= 0; + var i, j, seg, event, times, s, skinCss, skinCssAttr, skinClasses, rowClasses, segContainer, eventElements, eventElement, triggerRes; + + for (j=0; j < segs.length; j++) { + seg = segs[j]; + + if (seg.title) { + $('' + htmlEscape(seg.title) + '').appendTo(table); + } + segContainer = $('').addClass('fc-list-section ' + contentClass).appendTo(table); + s = ''; + + for (i=0; i < seg.events.length; i++) { + event = seg.events[i]; + times = renderEventTime(event, seg); + skinCss = getSkinCss(event, opt); + skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); + skinClasses = ['fc-event-skin', 'fc-corner-left', 'fc-corner-right', 'fc-corner-top', 'fc-corner-bottom'].concat(event.className); + if (event.source && event.source.className) { + skinClasses = skinClasses.concat(event.source.className); + } + rowClasses = ['fc-event', 'fc-event-row', 'fc-'+dayIDs[event.start.getDay()]]; + if (seg.daydiff == 0) { + rowClasses.push('fc-today'); + } + + s += ""; + for (var col, c=0; c < tableCols.length; c++) { + col = tableCols[c]; + if (col == 'handle') { + s += "" + + "
    " + + "" + + "
    "; + } else if (col == 'date') { + s += "" + htmlEscape(times[0]) + ""; + } else if (col == 'time') { + if (times[1]) { + s += "" + htmlEscape(times[1]) + ""; + } + } else { + s += "" + (event[col] ? htmlEscape(event[col]) : ' ') + ""; + } + } + s += ""; + + // IE doesn't like innerHTML on tbody elements so we insert every row individually + if (document.all) { + $(s).appendTo(segContainer); + s = ''; + } + } + + if (!document.all) + segContainer[0].innerHTML = s; + + eventElements = segContainer.children(); + + // retrieve elements, run through eventRender callback, bind event handlers + for (i=0; i < seg.events.length; i++) { + event = seg.events[i]; + 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).appendTo(segContainer); + } + if (event._id === modifiedEventId) { + eventElementHandlers(event, eventElement, seg); + } else { + eventElement[0]._fci = i; // for lazySegBind + } + reportEventElement(event, eventElement); + } + } + + lazySegBind(segContainer, seg, eventElementHandlers); + markFirstLast(segContainer); + } + + //markFirstLast(table); + } + +} + + +fcViews.table = TableView; + + +function TableView(element, calendar) { + var t = this; + + // exports + t.render = render; + t.select = dummy; + t.unselect = dummy; + t.getDaySegmentContainer = function(){ return table; }; + + // imports + View.call(t, element, calendar, 'table'); + TableEventRenderer.call(t); + var opt = t.opt; + var trigger = t.trigger; + var clearEvents = t.clearEvents; + var reportEventClear = t.reportEventClear; + var formatDates = calendar.formatDates; + var formatDate = calendar.formatDate; + + // overrides + t.setWidth = setWidth; + t.setHeight = setHeight; + + // locals + var div; + var table; + var firstDay; + var nwe; + var tm; + var colFormat; + + + function render(date, delta) { + if (delta) { + addDays(date, opt('listPage') * delta); + } + t.start = t.visStart = cloneDate(date, true); + t.end = addDays(cloneDate(t.start), opt('listPage')); + t.visEnd = addDays(cloneDate(t.start), opt('listRange')); + addMinutes(t.visEnd, -1); // set end to 23:59 + t.title = (t.visEnd.getTime() - t.visStart.getTime() < DAY_MS) ? formatDate(date, opt('titleFormat')) : formatDates(date, t.visEnd, opt('titleFormat')); + + updateOptions(); + + if (!table) { + buildSkeleton(); + } else { + clearEvents(); + } + } + + + function updateOptions() { + firstDay = opt('firstDay'); + nwe = opt('weekends') ? 0 : 1; + tm = opt('theme') ? 'ui' : 'fc'; + colFormat = opt('columnFormat'); + } + + + function buildSkeleton() { + var tableCols = opt('tableCols'); + var s = + "" + + ""; + for (var c=0; c < tableCols.length; c++) { + s += ""; + } + s += "" + + "
    "; + div = $('
    ').addClass('fc-list-content').appendTo(element); + table = $(s).appendTo(div); + } + + function setHeight(height, dateChanged) { + if (!opt('listNoHeight')) + div.css('height', (height-1)+'px').css('overflow', 'auto'); + } + + function setWidth(width) { + // nothing to be done here + } + + function dummy() { + // Stub. + } + +} + +})(jQuery); diff --git a/lib/js/jquery.miniColors.min.js b/lib/js/jquery.miniColors.min.js new file mode 100644 index 0000000..cd08974 --- /dev/null +++ b/lib/js/jquery.miniColors.min.js @@ -0,0 +1,16 @@ +// http://plugins.jquery.com/project/jQueryMiniColors +jQuery&&function(d){d.extend(d.fn,{miniColors:function(j,k){var x=function(a,b){var e=l(a.val());e||(e="FFFFFF");var c=p(e),e=d('');e.insertAfter(a);a.addClass("miniColors").attr("maxlength",7).attr("autocomplete","off");a.data("trigger",e);a.data("hsb",c);b.change&&a.data("change",b.change);b.readonly&&a.attr("readonly",true);b.disabled&&q(a);b.colorValues&&a.data("colorValues",b.colorValues);e.bind("click.miniColors",function(b){b.preventDefault(); +a.trigger("focus")});a.bind("focus.miniColors",function(){w(a)});a.bind("blur.miniColors",function(){var b=l(a.val());a.val(b?"#"+b:"")});a.bind("keydown.miniColors",function(b){b.keyCode===9&&i(a)});a.bind("keyup.miniColors",function(){var b=a.val().replace(/[^A-F0-9#]/ig,"");a.val(b);r(a)||a.data("trigger").css("backgroundColor","#FFF")});a.bind("paste.miniColors",function(){setTimeout(function(){a.trigger("keyup")},5)})},q=function(a){i(a);a.attr("disabled",true);a.data("trigger").css("opacity", +0.5)},w=function(a){if(a.attr("disabled"))return false;i();var b=d('
    ');b.append('
    ');b.append('
    ');b.css({top:a.is(":visible")?a.offset().top+a.outerHeight():a.data("trigger").offset().top+a.data("trigger").outerHeight(),left:a.is(":visible")?a.offset().left:a.data("trigger").offset().left, +display:"none"}).addClass(a.attr("class"));var e=a.data("colorValues");if(e&&e.length){var c,f='
    ',g;for(g in e)c=l(e[g]),f+='
    ';f+="
    ";b.append(f);c=Math.ceil(e.length/7)*24;b.css("width",b.width()+c+5+"px");b.find(".miniColors-presets").css("width",c+"px")}c=a.data("hsb");b.find(".miniColors-colors").css("backgroundColor","#"+n(m({h:c.h,s:100,b:100})));(f=a.data("colorPosition"))|| +(f=s(c));b.find(".miniColors-colorPicker").css("top",f.y+"px").css("left",f.x+"px");(f=a.data("huePosition"))||(f=t(c));b.find(".miniColors-huePicker").css("top",f.y+"px");a.data("selector",b);a.data("huePicker",b.find(".miniColors-huePicker"));a.data("colorPicker",b.find(".miniColors-colorPicker"));a.data("mousebutton",0);d("BODY").append(b);b.fadeIn(100);b.bind("selectstart",function(){return false});d(document).bind("mousedown.miniColors",function(b){a.data("mousebutton",1);d(b.target).parents().andSelf().hasClass("miniColors-colors")&& +(b.preventDefault(),a.data("moving","colors"),u(a,b));d(b.target).parents().andSelf().hasClass("miniColors-hues")&&(b.preventDefault(),a.data("moving","hues"),v(a,b));d(b.target).parents().andSelf().hasClass("miniColors-selector")?b.preventDefault():d(b.target).parents().andSelf().hasClass("miniColors")||i(a)});d(document).bind("mouseup.miniColors",function(){a.data("mousebutton",0);a.removeData("moving")});d(document).bind("mousemove.miniColors",function(b){a.data("mousebutton")===1&&(a.data("moving")=== +"colors"&&u(a,b),a.data("moving")==="hues"&&v(a,b))});e&&(b.find(".miniColors-colorPreset").click(function(){a.val(d(this).attr("rel"));r(a)}),b.find('.miniColors-presets div[rel="'+a.val().replace(/#/,"")+'"]').addClass("miniColors-colorPreset-active"))},i=function(a){a||(a=".miniColors");d(a).each(function(){var a=d(this).data("selector");d(this).removeData("selector");d(a).fadeOut(100,function(){d(this).remove()})});d(document).unbind("mousedown.miniColors");d(document).unbind("mousemove.miniColors")}, +u=function(a,b){var e=a.data("colorPicker");e.hide();var c={x:b.clientX-a.data("selector").find(".miniColors-colors").offset().left+d(document).scrollLeft()-5,y:b.clientY-a.data("selector").find(".miniColors-colors").offset().top+d(document).scrollTop()-5};if(c.x<=-5)c.x=-5;if(c.x>=144)c.x=144;if(c.y<=-5)c.y=-5;if(c.y>=144)c.y=144;a.data("colorPosition",c);e.css("left",c.x).css("top",c.y).show();e=Math.round((c.x+5)*0.67);e<0&&(e=0);e>100&&(e=100);c=100-Math.round((c.y+5)*0.67);c<0&&(c=0);c>100&& +(c=100);var f=a.data("hsb");f.s=e;f.b=c;o(a,f,true)},v=function(a,b){var e=a.data("huePicker");e.hide();var c={y:b.clientY-a.data("selector").find(".miniColors-colors").offset().top+d(document).scrollTop()-1};if(c.y<=-1)c.y=-1;if(c.y>=149)c.y=149;a.data("huePosition",c);e.css("top",c.y).show();e=Math.round((150-c.y-1)*2.4);e<0&&(e=0);e>360&&(e=360);c=a.data("hsb");c.h=e;o(a,c,true)},o=function(a,b,e){a.data("hsb",b);var c=n(m(b));e&&a.val("#"+c);a.data("trigger").css("backgroundColor","#"+c);a.data("selector")&& +a.data("selector").find(".miniColors-colors").css("backgroundColor","#"+n(m({h:b.h,s:100,b:100})));a.data("change")&&a.data("change").call(a,"#"+c,m(b));a.data("colorValues")&&(a.data("selector").find(".miniColors-colorPreset-active").removeClass("miniColors-colorPreset-active"),a.data("selector").find('.miniColors-presets div[rel="'+c+'"]').addClass("miniColors-colorPreset-active"))},r=function(a){var b=l(a.val());if(!b)return false;var b=p(b),e=a.data("hsb");if(b.h===e.h&&b.s===e.s&&b.b===e.b)return true; +e=s(b);d(a.data("colorPicker")).css("top",e.y+"px").css("left",e.x+"px");e=t(b);d(a.data("huePicker")).css("top",e.y+"px");o(a,b,false);return true},s=function(a){var b=Math.ceil(a.s/0.67);b<0&&(b=0);b>150&&(b=150);a=150-Math.ceil(a.b/0.67);a<0&&(a=0);a>150&&(a=150);return{x:b-5,y:a-5}},t=function(a){a=150-a.h/2.4;a<0&&(h=0);a>150&&(h=150);return{y:a-1}},l=function(a){a=a.replace(/[^A-Fa-f0-9]/,"");a.length==3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]);return a.length===6?a:null},m=function(a){var b,e,c; +b=Math.round(a.h);var d=Math.round(a.s*255/100),a=Math.round(a.b*255/100);if(d==0)b=e=c=a;else{var d=(255-d)*a/255,g=(a-d)*(b%60)/60;b==360&&(b=0);b<60?(b=a,c=d,e=d+g):b<120?(e=a,c=d,b=a-g):b<180?(e=a,b=d,c=d+g):b<240?(c=a,b=d,e=a-g):b<300?(c=a,e=d,b=d+g):b<360?(b=a,e=d,c=a-g):c=e=b=0}return{r:Math.round(b),g:Math.round(e),b:Math.round(c)}},n=function(a){var b=[a.r.toString(16),a.g.toString(16),a.b.toString(16)];d.each(b,function(a,c){c.length==1&&(b[a]="0"+c)});return b.join("")},p=function(a){var b= +a,b=parseInt(b.indexOf("#")>-1?b.substring(1):b,16),a=b>>16,d=(b&65280)>>8;b&=255;var c={h:0,s:0,b:0},f=Math.min(a,d,b),g=Math.max(a,d,b),f=g-f;c.b=g;c.s=g!=0?255*f/g:0;c.h=c.s!=0?a==g?(d-b)/f:d==g?2+(b-a)/f:4+(a-d)/f:-1;c.h*=60;c.h<0&&(c.h+=360);c.s*=100/255;c.b*=100/255;if(c.s===0)c.h=360;return c};switch(j){case "readonly":return d(this).each(function(){d(this).attr("readonly",k)}),d(this);case "disabled":return d(this).each(function(){if(k)q(d(this));else{var a=d(this);a.attr("disabled",false); +a.data("trigger").css("opacity",1)}}),d(this);case "value":return d(this).each(function(){d(this).val(k).trigger("keyup")}),d(this);case "destroy":return d(this).each(function(){var a=d(this);i();a=d(a);a.data("trigger").remove();a.removeAttr("autocomplete");a.removeData("trigger");a.removeData("selector");a.removeData("hsb");a.removeData("huePicker");a.removeData("colorPicker");a.removeData("mousebutton");a.removeData("moving");a.unbind("click.miniColors");a.unbind("focus.miniColors");a.unbind("blur.miniColors"); +a.unbind("keyup.miniColors");a.unbind("keydown.miniColors");a.unbind("paste.miniColors");d(document).unbind("mousedown.miniColors");d(document).unbind("mousemove.miniColors")}),d(this);default:return j||(j={}),d(this).each(function(){d(this)[0].tagName.toLowerCase()==="input"&&(d(this).data("trigger")||x(d(this),j,k))}),d(this)}}})}(jQuery); diff --git a/localization/bg_BG.inc b/localization/bg_BG.inc new file mode 100644 index 0000000..79a79ee --- /dev/null +++ b/localization/bg_BG.inc @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/localization/cs_CZ.inc b/localization/cs_CZ.inc new file mode 100644 index 0000000..dbc1a52 --- /dev/null +++ b/localization/cs_CZ.inc @@ -0,0 +1,235 @@ + diff --git a/localization/de_DE.inc b/localization/de_DE.inc new file mode 100644 index 0000000..f5faa6f --- /dev/null +++ b/localization/de_DE.inc @@ -0,0 +1,229 @@ + diff --git a/localization/en_US.inc b/localization/en_US.inc new file mode 100644 index 0000000..7eb7063 --- /dev/null +++ b/localization/en_US.inc @@ -0,0 +1,236 @@ + diff --git a/localization/es_ES.inc b/localization/es_ES.inc new file mode 100644 index 0000000..bfa4865 --- /dev/null +++ b/localization/es_ES.inc @@ -0,0 +1,39 @@ + diff --git a/localization/et_EE.inc b/localization/et_EE.inc new file mode 100644 index 0000000..edfba0c --- /dev/null +++ b/localization/et_EE.inc @@ -0,0 +1,230 @@ + diff --git a/localization/fr_FR.inc b/localization/fr_FR.inc new file mode 100644 index 0000000..cb4e3f8 --- /dev/null +++ b/localization/fr_FR.inc @@ -0,0 +1,230 @@ + diff --git a/localization/hu_HU.inc b/localization/hu_HU.inc new file mode 100644 index 0000000..fbd2bd9 --- /dev/null +++ b/localization/hu_HU.inc @@ -0,0 +1,38 @@ + diff --git a/localization/it_IT.inc b/localization/it_IT.inc new file mode 100644 index 0000000..c03b4b9 --- /dev/null +++ b/localization/it_IT.inc @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/localization/ja_JP.inc b/localization/ja_JP.inc new file mode 100644 index 0000000..6cc76d7 --- /dev/null +++ b/localization/ja_JP.inc @@ -0,0 +1,230 @@ + diff --git a/localization/nl_NL.inc b/localization/nl_NL.inc new file mode 100644 index 0000000..502ab3c --- /dev/null +++ b/localization/nl_NL.inc @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/localization/pl_PL.inc b/localization/pl_PL.inc new file mode 100644 index 0000000..3403ea5 --- /dev/null +++ b/localization/pl_PL.inc @@ -0,0 +1,224 @@ + diff --git a/localization/pt_BR.inc b/localization/pt_BR.inc new file mode 100644 index 0000000..4d00697 --- /dev/null +++ b/localization/pt_BR.inc @@ -0,0 +1,38 @@ + diff --git a/localization/ru_RU.inc b/localization/ru_RU.inc new file mode 100644 index 0000000..fa7f34c --- /dev/null +++ b/localization/ru_RU.inc @@ -0,0 +1,242 @@ + diff --git a/print.js b/print.js new file mode 100644 index 0000000..67b6a93 --- /dev/null +++ b/print.js @@ -0,0 +1,168 @@ +/** + * Print view for the Calendar plugin + * + * @version @package_version@ + * @author Thomas Bruederli + * + * Copyright (C) 2011, Kolab Systems AG + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +/* calendar plugin printing code */ +window.rcmail && rcmail.addEventListener('init', function(evt) { + + // quote html entities + var Q = function(str) + { + return String(str).replace(//g, '>').replace(/"/g, '"'); + }; + + var rc_loading; + var showdesc = true; + var settings = $.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings); + + // create list of event sources AKA calendars + var src, event_sources = []; + var add_url = (rcmail.env.search ? '&q='+escape(rcmail.env.search) : ''); + for (var id in rcmail.env.calendars) { + source = $.extend({ + url: "./?_task=calendar&_action=load_events&source=" + escape(id) + add_url, + className: 'fc-event-cal-'+id, + id: id + }, rcmail.env.calendars[id]); + + event_sources.push(source); + } + + var viewdate = new Date(); + if (rcmail.env.date) + viewdate.setTime(rcmail.env.date * 1000); + + // initalize the fullCalendar plugin + var fc = $('#calendar').fullCalendar({ + header: { + left: '', + center: 'title', + right: 'agendaDay,agendaWeek,month,table' + }, + aspectRatio: 0.85, + ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone + date: viewdate.getDate(), + month: viewdate.getMonth(), + year: viewdate.getFullYear(), + defaultView: rcmail.env.view, + eventSources: event_sources, + monthNames : settings['months'], + monthNamesShort : settings['months_short'], + dayNames : settings['days'], + dayNamesShort : settings['days_short'], + firstDay : settings['first_day'], + firstHour : settings['first_hour'], + slotMinutes : 60/settings['timeslots'], + timeFormat: { + '': settings['time_format'], + agenda: settings['time_format'] + '{ - ' + settings['time_format'] + '}', + list: settings['time_format'] + '{ - ' + settings['time_format'] + '}', + table: settings['time_format'] + '{ - ' + settings['time_format'] + '}' + }, + axisFormat : settings['time_format'], + columnFormat: { + month: 'ddd', // Mon + week: 'ddd ' + settings['date_short'], // Mon 9/7 + day: 'dddd ' + settings['date_short'], // Monday 9/7 + list: settings['date_agenda'], + table: settings['date_agenda'] + }, + titleFormat: { + month: 'MMMM yyyy', + week: settings['dates_long'], + day: 'dddd ' + settings['date_long'], + list: settings['dates_long'], + table: settings['dates_long'] + }, + listSections: rcmail.env.listSections !== undefined ? rcmail.env.listSections : settings['agenda_sections'], + listRange: rcmail.env.listRange || settings['agenda_range'], + tableCols: ['handle', 'date', 'time', 'title', 'location'], + allDayText: rcmail.gettext('all-day', 'calendar'), + buttonText: { + day: rcmail.gettext('day', 'calendar'), + week: rcmail.gettext('week', 'calendar'), + month: rcmail.gettext('month', 'calendar'), + table: rcmail.gettext('agenda', 'calendar') + }, + listTexts: { + until: rcmail.gettext('until', 'calendar'), + past: rcmail.gettext('pastevents', 'calendar'), + today: rcmail.gettext('today', 'calendar'), + tomorrow: rcmail.gettext('tomorrow', 'calendar'), + thisWeek: rcmail.gettext('thisweek', 'calendar'), + nextWeek: rcmail.gettext('nextweek', 'calendar'), + thisMonth: rcmail.gettext('thismonth', 'calendar'), + nextMonth: rcmail.gettext('nextmonth', 'calendar'), + future: rcmail.gettext('futureevents', 'calendar'), + week: rcmail.gettext('weekofyear', 'calendar') + }, + loading: function(isLoading) { + rc_loading = rcmail.set_busy(isLoading, 'loading', rc_loading); + }, + // event rendering + eventRender: function(event, element, view) { + if (view.name != 'month') { + var cont = element.find('div.fc-event-title'); + if (event.location) { + cont.after('
    @ ' + Q(event.location) + '
    '); + cont = cont.next(); + } + if (event.description && showdesc) { + cont.after('
    ' + Q(event.description) + '
    '); + } +/* TODO: create icons black on white + if (event.recurrence) + element.find('div.fc-event-time').append(''); + if (event.alarms) + element.find('div.fc-event-time').append(''); +*/ + } + if (view.name == 'table' && event.description && showdesc) { + var cols = element.children().css('border', 0).length; + element.after('' + Q(event.description) + ''); + } + }, + viewDisplay: function(view) { + // remove hard-coded hight and make contents visible + window.setTimeout(function(){ + if (view.name == 'table') { + $('div.fc-list-content').css('overflow', 'visible').height('auto'); + } + else { + $('div.fc-agenda-divider') + .next().css('overflow', 'visible').height('auto') + .children('div').css('overflow', 'visible').height('auto'); + } + // adjust fixed height if vertical day slots + var h = $('table.fc-agenda-slots:visible').height() + $('table.fc-agenda-allday:visible').height() + 4; + if (h) $('table.fc-agenda-days td.fc-widget-content').children('div').height(h); + }, 20); + } + }); + + // activate settings form + $('#propdescription').change(function(){ + showdesc = this.checked; + fc.fullCalendar('render'); + }); + +}); diff --git a/skins/classic/README b/skins/classic/README new file mode 100644 index 0000000..ccd513a --- /dev/null +++ b/skins/classic/README @@ -0,0 +1,5 @@ +Icons by Fugue Icons + +Copyright (C) 2010 Yusuke Kamiyamane. All rights reserved. +The icons are licensed under a Creative Commons Attribution +3.0 license. diff --git a/skins/classic/calendar.css b/skins/classic/calendar.css new file mode 100644 index 0000000..b0ac630 --- /dev/null +++ b/skins/classic/calendar.css @@ -0,0 +1,1269 @@ +/*** Style for Calendar plugin ***/ + +body.calendarmain { + overflow: hidden; +} + +#taskbar a.button-calendar { + background: url(images/calendar.png) 0px 1px no-repeat; +} + +/* hack for IE 6/7 */ +* html #taskbar a.button-calendar { + background-image: url(images/calendar.gif); +} + +#main { + position: absolute; + clear: both; + top: 90px; + left: 0; + right: 0; + bottom: 10px; +} + +#calendarsidebar { + position: absolute; + top: 37px; + left: 10px; + bottom: 0; + width: 230px; +} + +#datepicker { + width: 100%; +} + +#datepicker .ui-datepicker { + width: 97% !important; + box-shadow: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; +} + +#datepicker .ui-datepicker-activerange a { + border-color: #c33; + color: #a22; +} + +#datepicker .ui-datepicker-activerange a.ui-state-active { + color: #fff; +} + +#datepicker .ui-priority-secondary { + opacity: 0.4; +} + +#datepicker td.ui-datepicker-week-col { + cursor: pointer; +} + +#calendarsidebartoggle { + position: absolute; + left: 244px; + width: 8px; + top: 37px; + bottom: 0; + background: url(images/toggle.gif) 0 48% no-repeat transparent; + cursor: pointer; +} + +div.sidebarclosed { + background-position: -8px 48% !important; +} + +#calendarsidebartoggle:hover { + background-color: #ddd; +} + +#calendar { + position: absolute; + top: 0; + left: 256px; + right: 10px; + bottom: 0; +} + +#print { + width: 680px; +} + +pre { + font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif; +} + +#calendars { + position: absolute; + top: 220px; + left: 0; + bottom: 0; + right: 0; + background-color: #F9F9F9; + border: 1px solid #999999; + overflow: hidden; +} + +#calendarslist { + list-style: none; + margin: 0; + padding: 0; +} + +#attachmentlist li, +#calendarslist li { + margin: 0; + padding: 1px; + display: block; + background: #fff; + border-bottom: 1px solid #EBEBEB; + white-space: nowrap; + cursor: default; +} + +#calendarslist li label { + display: block; +} + +#calendarslist li span.handle { + cursor: default; + background: url(images/calendars.png) 0 -2px no-repeat; + display: inline-block; + width: 20px; +} + +#calendarslist li input { + margin-right: 5px; +} + +#calendarslist li.selected { + background-color: #ccc; + border-bottom: 1px solid #bbb; +} + +#calendarslist li.selected span { + font-weight: bold; +} + +#calendarslist li.readonly span.handle { + background-position: 0 -20px; +} + +#calendarslist li.other span.handle { + background-position: 0 -38px; +} + +#calendarslist li.other.readonly span.handle { + background-position: 0 -56px; +} + +#calendarslist li.shared span.handle { + background-position: 0 -74px; +} + +#calendarslist li.shared.readonly span.handle { + background-position: 0 -92px; +} + +#calfeedurl { + width: 98%; + background: #fbfbfb; + padding: 4px; + margin-bottom: 1em; + resize: none; +} + +#agendalist { + width: 100%; + margin: 0 auto; + margin-top: 60px; + border: 1px solid #C1DAD7; + display: none; +} + +#agendalist table { + width: 100%; +} + +#agendalist td, +#agendalist th { + border-right: 1px solid #C1DAD7; + border-bottom: 1px solid #C1DAD7; + background: #fff; + padding: 6px 6px 6px 12px; +} + +#agendalist tr { + vertical-align: top; +} + +#agendalist th { + font-weight: bold; +} + +#calendartoolbar { + position: absolute; + top: 45px; + left: 256px; + height: 35px; +} + +#calendartoolbar a { + padding-right: 10px; +} + +#calendartoolbar a.button, +#calendartoolbar a.buttonPas { + display: block; + float: left; + width: 32px; + height: 32px; + padding: 0; + margin-right: 10px; + overflow: hidden; + background: url(images/toolbar.png) 0 0 no-repeat transparent; + opacity: 0.99; /* this is needed to make buttons appear correctly in Chrome */ +} + +#calendartoolbar a.buttonPas { + opacity: 0.35; +} + +#calendartoolbar a.addeventSel { + background-position: 0 -32px; +} + +#calendartoolbar a.delete { + background-position: -32px 0; +} + +#calendartoolbar a.deleteSel { + background-position: -32px -32px; +} + +#calendartoolbar a.print { + background-position: -64px 0; +} + +#calendartoolbar a.printSel { + background-position: -64px -32px; +} + +#calendartoolbar a.export { + background-position: -128px 0; +} + +#calendartoolbar a.exportSel { + background-position: -128px -32px; +} + +#quicksearchbar { + right: 4px; +} + +div.uidialog { + display: none; +} + +#user { + position: absolute; + top: 10px; + right: 100px; + left: 100px; + text-align: center; +} + +a.morelink { + font-size: 90%; + color: #C33; + text-decoration: none; +} + +a.morelink:hover { + text-decoration: underline; +} + +a.miniColors-trigger { + margin-top: -3px; +} + +#attachmentcontainer { + position: absolute; + top: 80px; + left: 20px; + right: 20px; + bottom: 20px; +} + +#attachmentframe { + width: 100%; + height: 100%; + border: 1px solid #999999; + background-color: #F9F9F9; +} + +#partheader { + position: absolute; + top: 20px; + left: 220px; + right: 20px; + height: 40px; +} + +#partheader table td { + padding-left: 2px; + padding-right: 4px; + vertical-align: middle; + font-size: 11px; +} + +#partheader table td.title { + color: #666; + font-weight: bold; +} + +.attachments-list ul { + margin: 0px; + padding: 0px; + list-style-image: none; + list-style-type: none; +} + +.attachments-list ul li { + height: 18px; + font-size: 12px; + padding-top: 2px; + padding-right: 8px; + white-space: nowrap; +} + +.attachments-list ul li img { + padding-right: 2px; + vertical-align: middle; +} + +.attachments-list ul li a { + text-decoration: none; +} + +.attachments-list ul li a:hover { + text-decoration: underline; +} + +#attachmentlist { + margin: 0 -0.8em; +} + +#attachmentlist li { + padding: 2px 2px 3px 0.8em; +} + +#eventshow .attachments-list ul li { + float: left; +} + +#edit-attachments-form { + padding-top: 1.2em; +} + +#edit-attachments-form .formbuttons { + margin: 0.5em 0; +} + +#event-attendees span.attendee { + padding-right: 18px; + margin-right: 0.5em; + background: url(images/attendee-status.gif) right 0 no-repeat; +} + +#event-attendees span.attendee a.mailtolink { + text-decoration: none; + white-space: nowrap; +} + +#event-attendees span.attendee a.mailtolink:hover { + text-decoration: underline; +} + +#event-attendees span.accepted { + background-position: right -20px; +} + +#event-attendees span.declined { + background-position: right -40px; +} + +#event-attendees span.tentative { + background-position: right -60px; +} + +#event-attendees span.organizer { + background-position: right -80px; +} + +/* jQuery UI overrides */ + +#eventshow h1 { + font-size: 20px; + margin: 0.1em 0 0.4em 0; +} + +#eventshow label, +#eventshow h5.label { + font-weight: normal; + font-size: 0.9em; + color: #999; + margin: 0 0 0.2em 0; +} + +#eventshow { + margin: 0 -0.2em; +} + +#eventshow.sensitivity-private { + background: url(images/badge_private.png) top right no-repeat; +} + +#eventshow.sensitivity-confidential { + background: url(images/badge_confidential.png) top right no-repeat; +} + +.sensitivity-private #event-title { + margin-right: 50px; +} + +.sensitivity-confidential #event-title { + margin-right: 60px; +} + +#eventshow div.event-line { + margin-top: 0.1em; + margin-bottom: 0.3em; +} + +#eventedit { + position: relative; + padding: 0.5em 0.1em; +} + +#eventedit input.text, +#eventedit textarea { + width: 97%; +} + +#eventtabs { + position: relative; + padding: 0; + border: 0; + border-radius: 0; +} + +div.form-section, +#eventshow div.event-section, +#eventtabs div.event-section { + margin-top: 0.2em; + margin-bottom: 0.8em; +} + +#eventtabs .tabsbar { + position: absolute; + top: 0; +} + +#eventtabs .ui-tabs-panel { + padding: 1em 0.8em; + border: 1px solid #aaa; + border-width: 0 1px 1px 1px; +} + +#eventtabs .ui-tabs-nav { + background: none; + padding: 0; + border-width: 0 0 1px 0; + border-radius: 0; +} + +#eventtabs .border-after { + padding-bottom: 0.6em; + margin-bottom: 0.6em; + border-bottom: 1px solid #999; +} + +#eventshow label, +#eventedit label, +.form-section label { + display: inline-block; + min-width: 7em; + padding-right: 0.5em; +} + +#eventedit .formtable td.label { + min-width: 6em; +} + +td.topalign { + vertical-align: top; +} + +#eventedit label.weekday, +#eventedit label.monthday { + min-width: 3em; +} + +#eventedit label.month { + min-width: 5em; +} + +#edit-recurrence-yearly-bymonthblock { + margin-left: 7.5em; +} + +#eventedit .recurrence-form { + display: none; +} + +#eventedit .formtable td { + padding: 0.2em 0; +} + +.ui-dialog .event-update-confirm { + padding: 0 0.5em 0.5em 0.5em; +} + +.event-dialog-message, +.event-update-confirm .message { + margin-top: 0.5em; + padding: 0.8em; + background-color: #F7FDCB; + border: 1px solid #C2D071; +} + +.event-dialog-message .message, +.event-update-confirm .message { + margin-bottom: 0.5em; +} + +.edit-recurring-warning .savemode { + padding-left: 20px; +} + +.event-update-confirm .savemode { + padding-left: 30px; +} + +.event-dialog-message span.ui-icon, +.event-update-confirm span.ui-icon { + float: left; + margin: 0 7px 20px 0; +} + +.event-dialog-message label, +.event-update-confirm label { + min-width: 3em; + padding-right: 1em; +} + +.event-update-confirm a.button { + margin: 0 0.5em 0 0.2em; + min-width: 5em; +} + +#event-rsvp, +#edit-attendees-notify { + margin: 0.3em 0; + padding: 0.5em; + background-color: #F7FDCB; + border: 1px solid #C2D071; +} + +#edit-attendees-table { + width: 100%; + display: table; + table-layout: fixed; + border-collapse: collapse; + border: 1px solid #ccc; +} + +#edit-attendees-table td { + padding: 3px; + border-bottom: 1px solid #ccc; +} + +#edit-attendees-table td.role { + width: 8em; +} + +#edit-attendees-table td.availability, +#edit-attendees-table td.confirmstate { + width: 4em; +} + +#edit-attendees-table td.options { + width: 3em; + text-align: right; + padding-right: 4px; +} + +#edit-attendees-table td.name { + width: auto; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +#edit-attendees-table thead td { + background: url(images/listheader.gif) top left repeat-x #CCC; +} + +#edit-attendees-form { + position: relative; + margin-top: 1em; +} + +#edit-attendees-form #edit-attendee-schedule { + position: absolute; + top: 0; + right: 0; +} + +#edit-attendees-table select.edit-attendee-role { + border: 0; + padding: 2px; + background: white; +} + +.availability img.availabilityicon { + margin: 1px; + width: 14px; + height: 14px; + border-radius: 4px; + -moz-border-radius: 4px; +} + +.availability img.availabilityicon.loading { + background: url(images/loading_blue.gif) center no-repeat; +} + +#schedule-freebusy-times td.unknown, +.availability img.availabilityicon.unknown { + background: #ddd; +} + +#schedule-freebusy-times td.free, +.availability img.availabilityicon.free { + background: #0c0; +} + +#schedule-freebusy-times td.busy, +.availability img.availabilityicon.busy { + background: #c00; +} + +#schedule-freebusy-times td.tentative, +.availability img.availabilityicon.tentative { + background: #66d; +} + +#schedule-freebusy-times td.out-of-office, +.availability img.availabilityicon.out-of-office { + background: #f0b400; +} + +#schedule-freebusy-times td.all-busy, +#schedule-freebusy-times td.all-tentative, +#schedule-freebusy-times td.all-out-of-office { + background-image: url(images/freebusy-colors.png); + background-position: top right; + background-repeat: no-repeat; +} + +#schedule-freebusy-times td.all-tentative { + background-position: right -40px; +} + +#schedule-freebusy-times td.all-out-of-office { + background-position: right -80px; +} + +#edit-attendees-legend { + margin-top: 3em; + margin-bottom: 0.5em; +} + +#edit-attendees-legend .legend { + margin-right: 2em; + white-space: nowrap; +} + +#edit-attendees-legend img.availabilityicon { + vertical-align: middle; +} + +#edit-attendees-table tbody td.confirmstate { + overflow: hidden; + white-space: nowrap; + text-indent: -2000%; +} + +#edit-attendees-table td.confirmstate span { + display: block; + width: 20px; + background: url(images/attendee-status.gif) 5px 0 no-repeat; +} + +#edit-attendees-table td.confirmstate span.needs-action { +} + +#edit-attendees-table td.confirmstate span.accepted { + background-position: 5px -20px; +} + +#edit-attendees-table td.confirmstate span.declined { + background-position: 5px -40px; +} + +#edit-attendees-table td.confirmstate span.tentative { + background-position: 5px -60px; +} + +#attendees-freebusy-table { + width: 100%; + table-layout: fixed; + border-collapse: collapse; + margin: 0.5em 0; +} + +#attendees-freebusy-table td.attendees { + width: 18em; + border: 1px solid #ccc; + vertical-align: top; + overflow: hidden; +} + +#attendees-freebusy-table td.times { + width: auto; + vertical-align: top; + border: 1px solid #ccc; +} + +#attendees-freebusy-table div.scroll { + position: relative; + overflow: auto; +} + +#attendees-freebusy-table h3.boxtitle { + margin: 0; + height: auto !important; + border-color: #ccc; +} + +.attendees-list .attendee { + padding: 3px 4px 3px 1px; + background: url(images/attendee-status.gif) 2px -97px no-repeat; + white-space: nowrap; +} + +.attendees-list a.attendee-role-toggle { + display: inline-block; + width: 16px; + margin-right: 3px; + cursor: pointer; +} + +.attendees-list div.attendee { + border-top: 1px solid #ccc; +} + +.attendees-list span.attendee { + padding-left: 20px; + margin-right: 2em; +} + +.attendees-list .organizer { + background-position: 3px -77px; +} + +.attendees-list .opt-participant { + background-position: 2px -117px; +} + +.attendees-list .chair { + background-position: 2px -137px; +} + +.attendees-list .loading { + background: url(images/loading_blue.gif) 1px 50% no-repeat; +} + +.attendees-list .total { + background: none; + padding-left: 4px; + font-weight: bold; +} + +.attendees-list .spacer, +#schedule-freebusy-times tr.spacer td { + background: 0; + font-size: 50%; +} + +#schedule-freebusy-times { + border-collapse: collapse; + width: 100%; +} + +#schedule-freebusy-times td { + padding: 3px; + border: 1px solid #ccc; +} + +#schedule-freebusy-times tr.dates th { + border-color: #aaa; + border-style: solid; + border-width: 0 1px 0 1px; + white-space: nowrap; +} + +#attendees-freebusy-table div.timesheader, +#schedule-freebusy-times tr.times td { + min-width: 30px; + font-size: 9px; + padding: 5px 2px 6px 2px; + text-align: center; +} + +#schedule-freebusy-times tr.times td.allday { + min-width: 60px; +} + +#schedule-freebusy-times tr.times td { + cursor: pointer; +} + +#schedule-event-time { + position: absolute; + border: 2px solid #333; + background: #777; + background: rgba(60, 60, 60, 0.6); + opacity: 0.5; + border-radius: 4px; + cursor: move; + filter: alpha(opacity=40); /* IE8 */ +} + +#eventfreebusy .schedule-options { + position: relative; + margin-bottom: 1.5em; +} + +#eventfreebusy .schedule-buttons { + position: absolute; + top: 0; + right: 0; +} + +#eventfreebusy .schedule-find-buttons { + padding-bottom:0.5em; +} + +#eventfreebusy .schedule-find-buttons button { + min-width: 9em; + text-align: center; +} + +span.edit-alarm-set { + white-space: nowrap; +} + +a.dropdown-link { + color: #CC0000; + font-size: 12px; + text-decoration: none; +} + +a.dropdown-link:after { + content: ' â–¼'; + font-size: 11px; + color: #666; +} + +#eventedit .ui-tabs-panel { + min-height: 20em; +} + +.alarm-item { + margin: 0.4em 0 1em 0; +} + +.alarm-item .event-title { + font-size: 14px; + margin: 0.1em 0 0.3em 0; +} + +.alarm-item div.event-section { + margin-top: 0.1em; + margin-bottom: 0.3em; +} + +.alarm-item .alarm-actions { + margin-top: 0.4em; +} + +.alarm-item div.alarm-actions a { + color: #CC0000; + margin-right: 0.8em; + text-decoration: none; +} + +a.alarm-action-snooze:after { + content: ' â–¼'; + font-size: 10px; + color: #666; +} + +#alarm-snooze-dropdown { + z-index: 5000; +} + +.ui-dialog-buttonset a.dropdown-link { + margin-right: 1em; +} + +.ui-datepicker-calendar .ui-datepicker-today .ui-state-default { + border-color: #cccccc; + background: #ffffcc; + color: #000; +} + +.ui-datepicker-calendar .ui-datepicker-week-col { + text-align: right; + padding-right: 0.5em; +} + +.ui-datepicker th { + padding: 0.3em 0; + font-size: 10px; +} + +.ui-datepicker td span, +.ui-datepicker td a { + padding-left: 0.1em; +} + +.ui-autocomplete { + max-height: 160px; + overflow-y: auto; + overflow-x: hidden; +} + +.ui-autocomplete .ui-menu-item { + white-space: nowrap; +} + +* html .ui-autocomplete { + height: 160px; +} + +span.spacer { + padding-left: 3em; +} + +#agendaoptions { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: auto; + z-index: 200; + border: 1px solid #ccc; + padding: 2px 5px 1px; + font-size: 90%; +} + +#agendaoptions label { + color: #444; + text-shadow: 1px 1px #eee; + padding-right: 0.5em; +} + +#calendar-kolabform { + position: relative; + padding-top: 24px; + margin: 0 -8px; + min-width: 660px; + min-height: 400px; +} + +#calendar-kolabform div.tabsbar { + top: 0; + right: 2px; + left: 2px; + height: 24px; +} + +#calendar-kolabform fieldset.tabbed { + background-color: #fff; + margin-top: 0; +} + +#calendar-kolabform span.tablink { + background-color: #e8e8e9; + background-image: -moz-linear-gradient(center top, #f4f4f4, #e6e6e6); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #f4f4f4), color-stop(1.0, #e6e6e6)); + filter: progid:DXImageTransform.Microsoft.gradient(enabled='true', startColorstr=#f4f4f4, endColorstr=#e6e6e6, GradientType=0); + height: 24px !important; +} + +#calendar-kolabform span.tablink-selected { + background: #fff; + height: 25px !important; +} + +#calendar-kolabform span.tablink a, +#calendar-kolabform span.tablink-selected a { + background: none; + border: 1px solid #AAAAAA; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + padding: 4px 10px 0 10px; + margin-left: 0; +} + +#calendar-kolabform table td.title { + font-weight: bold; + white-space: nowrap; + color: #666; + padding-right: 10px; +} + + +/* fullcalendar style overrides */ + +.rcube-fc-content { + position: absolute !important; + top: 37px; + left: 0; + right: 0; + bottom: 0; + overflow: hidden; +} + +.fc-event-title { + font-weight: bold; +} + +.fc-event-hori .fc-event-title { + font-weight: normal; + white-space: nowrap; +} + +.fc-event-hori .fc-event-time { + white-space: nowrap; + font-weight: normal !important; + font-size: 10px; + padding-right: 0.6em; +} + +.fc-grid .fc-event-time { + font-weight: normal !important; + padding-right: 0.3em; +} + +.fc-event-cateories { + font-style:italic; +} + +div.fc-event-location { + font-size: 90%; +} + +.fc-more-link { + color: #999; + padding-top: 1px; + cursor: pointer; +} + +.fc-agenda-slots td div { + height: 22px; +} + +.fc-mon, .fc-tue, .fc-wed, .fc-thu, .fc-fri { + background-color: #fdfdfd; +} + +.fc-widget-header { + background-color: #fff; +} + +.fc-icon-alarms, +.fc-icon-sensitive, +.fc-icon-recurring { + display: inline-block; + width: 11px; + height: 11px; + background: url(images/eventicons.gif) 0 0 no-repeat; + margin-left: 3px; + line-height: 10px; +} + +.fc-icon-alarms { + background-position: 0 -13px; +} + +.fc-icon-sensitive { + background-position: 0 -25px; +} + +.fc-list-section .fc-event { + cursor: pointer; +} + +.fc-view-list div.fc-list-header, +.fc-view-table td.fc-list-header, +#edit-attendees-table thead td { + padding: 3px; + background: #dddddd; + background-image: -moz-linear-gradient(center top, #f4f4f4, #d2d2d2); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0.00, #f4f4f4), color-stop(1.00, #d2d2d2)); + filter: progid:DXImageTransform.Microsoft.gradient(enabled='true', startColorstr=#f4f4f4, endColorstr=#d2d2d2, GradientType=0); + font-weight: bold; + color: #333; +} + +.fc-view-list .fc-event-skin .fc-event-content { + background: #F6F6F6; + padding: 2px; +} + +.fc-view-list .fc-event-skin .fc-event-title, +.fc-view-list .fc-event-skin .fc-event-location { + color: #333; +} + +.fc-view-table col.fc-event-location { + width: 20%; +} + +.fc-listappend { + text-align: center; + margin: 1em 0; +} + +.fc-listappend .message { + padding: 0.5em; + margin-bottom: 0.5em; + font-size: 150%; + color: #999; +} + +.fc-listappend .formlinks a { + font-size: 12px; + padding: 0 0.3em; +} + +.fc-event-temp { + opacity: 0.4; + filter: alpha(opacity=40); /* IE8 */ +} + +/* Settings section */ + +fieldset #calendarcategories div { + margin-bottom: 0.3em; +} + +/* Invitation UI in mail */ + +#messagemenu li a.calendarlink { + background-image: url(images/calendars.png); + background-position: 7px -109px; + background-repeat: no-repeat; +} + +div.calendar-invitebox { + min-height: 20px; + margin: 5px 8px; + padding: 3px 6px 6px 34px; + border: 1px solid #C2D071; + background: url(images/calendar.png) 6px 5px no-repeat #F7FDCB; +} + +div.calendar-invitebox td.ititle { + font-weight: bold; + padding-right: 0.5em; +} + +div.calendar-invitebox td.label { + color: #666; + padding-right: 1em; +} + +#event-rsvp .rsvp-buttons, +div.calendar-invitebox .rsvp-status, +div.calendar-invitebox .rsvp-buttons { + margin-top: 0.5em; +} + +#event-rsvp input.button, +div.calendar-invitebox input.button, +div.calendar-invitebox select { + font-size: 11px; + margin-right: 0.5em; +} + +div.calendar-invitebox .calendar-select { + font-size: 11px; + margin-left: 1em; +} + +div.calendar-invitebox .rsvp-status.loading { + color: #666; + padding: 1px 0 2px 24px; + background: url(images/loading_blue.gif) top left no-repeat; +} + +div.calendar-invitebox .rsvp-status.declined, +div.calendar-invitebox .rsvp-status.tentative, +div.calendar-invitebox .rsvp-status.accepted { + padding: 0 0 1px 22px; + background: url(images/attendee-status.gif) 2px -20px no-repeat; +} + +div.calendar-invitebox .rsvp-status.declined { + background-position: 2px -40px; +} + +div.calendar-invitebox .rsvp-status.tentative { + background-position: 2px -60px; +} + +/* iTIP attend reply page */ + +.calendaritipattend .centerbox { + width: 40em; + margin: 80px auto; + padding: 10px 10px 10px 90px; + border: 1px solid #ccc; + box-shadow: 1px 1px 24px #ccc; + -moz-box-shadow: 1px 1px 18px #ccc; + -webkit-box-shadow: #ccc 1px 1px 18px; + background: url(images/invitation.png) 10px 10px no-repeat #fbfbfb; +} + +.calendaritipattend .calendar-invitebox { + background: none; + padding-left: 0; + border: 0; + margin: 0 0 2em 0; +} + +.calendaritipattend .calendar-invitebox .rsvp-status { + margin-top: 2.5em; + font-size: 110%; + font-weight: bold; +} + +.calendaritipattend .calendar-invitebox td.title, +.calendaritipattend .calendar-invitebox td.ititle { + font-size: 120%; +} + diff --git a/skins/classic/fullcalendar.css b/skins/classic/fullcalendar.css new file mode 100644 index 0000000..bf9e7dd --- /dev/null +++ b/skins/classic/fullcalendar.css @@ -0,0 +1,724 @@ +/* + * FullCalendar v1.5.4-rcube-0.9.0 Stylesheet + * + * Copyright (c) 2011 Adam Shaw + * Copyright (c) 2011, Kolab Systems AG + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Wed Nov 7 16:28:11 2012 +0100 + * + */ + + +.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, /* , usually */ +.fc-widget-content { /* , usually */ + border: 1px solid #ccc; + } + +.fc-state-highlight { /* today cell */ /* TODO: add .fc-today to */ + 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; + } + +.fc-more-link { + font-size: 0.85em; + white-space: nowrap; + text-decoration: none; + cursor: pointer; + padding: 1px; +} + +/* 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; + } + +.fc-timeline { + position: absolute; + width: 100%; + left: 0; + margin: 0; + padding: 0; + border: none; + border-top: 2px solid #3ec400; + z-index: 999; +} + +/* List view (by bruederli@kolabsys.com) +------------------------------------------------------------------------*/ + +.fc-view-list, +.fc-view-table { + border: 1px solid #ccc; + width: auto; +} + +.fc-view-list .fc-list-header, +.fc-view-table td.fc-list-header { + border-width: 0; + border-bottom-width: 1px; + padding: 3px 5px; +} + +.fc-view-table .fc-first td.fc-list-header { + border-top-width: 0; +} + +.fc-list-section { + padding: 4px 2px; + border-width: 0; + border-bottom-width: 1px; +} + +.fc-view-list .fc-last { + border-bottom-width: 0; +} + +.fc-list-section .fc-event { + position: relative; + margin: 1px 2px 3px 2px; +} + +.fc-view-table tr.fc-event td { + padding: 2px; + border-bottom: 1px solid #ccc; +} + +.fc-view-table tr.fc-event td.fc-event-handle { + padding: 3px 8px 3px 3px; +} + +.fc-view-table .fc-event-handle .fc-event-skin { + border-radius: 2px; + -moz-border-radius: 2px; +} + +.fc-view-table .fc-event-handle .fc-event-inner { + display: block; + width: 8px; + height: 10px; + border-radius: 2px; + -moz-border-radius: 2px; +} + +.fc-view-table table { + table-layout: fixed; + width: 100%; +} + +.fc-view-table col.fc-event-handle { + width: 18px; +} + +.fc-event-handle .fc-event-inner { + border-color: inherit; + background-color: inherit; +} + +.fc-view-table col.fc-event-date { + width: 7em; +} + +.fc-view-table .fc-list-day col.fc-event-date { + width: 1px; +} + +.fc-view-table col.fc-event-time { + width: 8em; +} + +.fc-view-table td.fc-event-date, +.fc-view-table td.fc-event-time { + white-space: nowrap; + padding-right: 1em; +} + diff --git a/skins/classic/iehacks.css b/skins/classic/iehacks.css new file mode 100644 index 0000000..42bd736 --- /dev/null +++ b/skins/classic/iehacks.css @@ -0,0 +1,88 @@ +/* CSS hacks for IE 6/7 */ + +#main { + width: expression(Math.max(300, parseInt(document.documentElement.clientWidth)-10)+'px'); + height: expression(Math.max(300, parseInt(document.documentElement.clientHeight)-100)+'px'); +} + +#calendarsidebar, +#calendarsidebartoggle { + height: expression((parseInt(this.parentNode.offsetHeight)-37)+'px'); +} + +#calendar { + width: expression((parseInt(this.parentNode.offsetWidth)-parseInt(document.getElementById('calendarsidebartoggle').offsetWidth)-parseInt(document.getElementById('calendarsidebartoggle').offsetLeft)-4)+'px'); + height: expression(parseInt(this.parentNode.offsetHeight)+'px'); +} + +#calendars { + height: expression((parseInt(this.parentNode.offsetHeight)-220)+'px'); +} + +#agendaoptions { + width: expression((parseInt(this.parentNode.offsetWidth)-12)+'px'); +} + +#calendartoolbar a.buttonPas { + filter: alpha(opacity=35); +} + +html #calendartoolbar a.button, +html #calendartoolbar a.buttonPas { + background-image: url(images/toolbar.gif); +} + +#datepicker a.ui-priority-secondary { + filter: alpha(opacity=40); +} + +#calendarslist li span.handle { + background-image: url(images/calendars.gif); +} + +#datepicker .ui-widget-header { + width: 102%; +} + +#eventshow.sensitivity-private { + background-image: url(images/badge_private.gif); +} + +#eventshow.sensitivity-confidential { + background-image: url(images/badge_confidential.gif); +} + +.fc-day-content { + cursor: default; +} + +.fc-header-title h2 { + font-size: 16px; +} + +.fc-event-temp .fc-event-bg { + display: none; /* nested opacity filters while dragging don't work */ +} + +#schedule-event-time { + filter: alpha(opacity=40); +} + +#eventfreebusy .schedule-buttons, +#edit-attendees-form #edit-attendee-schedule { + right: 0.6em; +} + +#schedule-freebusy-times td.all-busy, +#schedule-freebusy-times td.all-tentative, +#schedule-freebusy-times td.all-out-of-office { + background-image: url('images/freebusy-colors.gif'); +} + +#schedule-freebusy-times tr.times td.allday { + width: expression(Math.max(60, parseInt(this.offsetWidth))+'px'); +} + +.ui-dialog .ui-dialog-titlebar { + width: expression((parseInt(this.parentNode.offsetWidth)-26)+'px'); +} diff --git a/skins/classic/images/attendee-status.gif b/skins/classic/images/attendee-status.gif new file mode 100644 index 0000000000000000000000000000000000000000..5c08aae316ad60f3b71dd178c6e0e922943888b1 GIT binary patch literal 2041 zcmVuB@TiUv3>Hq-X%eBG5!T-!W?8}9?luFy}_0_$a_S~DMrl!Qi#Idol z;^N}Y+vA&?n`nK8ugIRpq*Bq*(Y3X;$<*4($;r97xr&{p-KP`%%`(&F?PYX(yLu;0 zX?9qf9Vez;M|IkNfsW0WZPycs!JXK*h zP+afNe9SX5X@igc+-GR3F=whUufodu_w&G7TKC_TO@$!4nN@O?TJXCaznxjmj1-+; z9@5&+Lx2z6q)Ow@&+yOB@4P$6ri8<-mdc}HZLc@&)1KVv@x_e>zGnc|q(a-FL$txi z$RHr<@aL*&BByg8@W))longzZcZWj&lTHQ6fGW?NJdk~9)!^po-Oq?1Afx+N2=ap$MqC!=qYS(c;9`;m?DR zmTfWsYlB*{!OHaK=YNx(*4o?(Xhea(=D3zWdl| zGC@h5vAJ@9hsDXujhCF_*1yi+>Hq1a_SBHVpIZI>{Ewrol&7!It!ALHx2mwR;=*~! zq)hzz_5c6>A^8LW00930EC2ui01g14000R80RIUbNU)&5I5jkk7@?tt!73#-z?itO zM3sSYN{rB=K}19tCQ1y1He!Q_At;BKFfjs}KnY^Pn9u-&!w?QI#7GdhAxsGgBQl^H zB4R|C4FWUx)UYAPkQx~@gv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CRqA%OI-rRD-=*lFH=gwLvR=ff&kuy)*0U$ z{q--DQsSbNxu-8TZ^47Nz6c`|EH%2<14(i8&j|&U;sn88K zrmt)&!HvG}qKq-^;4>*FG0TCZZvm}YL5V+4O>siNM~;}ciL>jOp!gQp$~ybvg?_d$ zxLe23${o0u{}lej6t%=&@2B_{;PPBkGNqpD)f;Bi3=CAmgkxIlOl5J$s6|0p7e1o@ z1A-#o0$n+L3P3U3(-&>z1gk07?oR7Jl0)mk`G47WApul2)ghEGO2db?ZQHilw}982 z3q5Z1Q}!#`=ED)g>iRf5_oe=d5sX-J6?ua4_maZj`WE<_Rr+$a#dHtl2|&P_@d%zF zrW8e>P(A!-@EmJQrtZrp%e$k`^bIG^F$f!tcOUt~cYGW}jR1azL*XGfJkGu>^JuuI z91ewk1p?Dn+{NkNcWaS#2#V)`;&%I%uF>cop^yrkFcL0JLPCJdt*lEpXtU@VIw*LjS#LjRIBoi5GhA8Amo)S9;lJqd% zU?}&9UlcOe*_TdVnSjI%`&lpaC~mE;vlhvg{|G+CSyv{QQZo4u0rHZ^EED?vyX9ky zncyU4z2ril@NlbGw)rJNiDz*40_0_y#|%TsY))Uc_XR?M|3BE%m?e|T7a;SHzT)CT zUJdi;rJ##K=3(}gtK*XGd?`@e&7&yfHSj62jq}wK8lLgi0^~KQDY9+z z3#FEiS;QF5Ka>wXDO`P$D@C?z9-&lLR&E9;JL=Y~It+i%;GqDSXDDT5W#Ou-stSOz z`5!@J5B$3Jlx)*HLMbUJF86}Z00000NkvXXu0mjfg9I+{ literal 0 HcmV?d00001 diff --git a/skins/classic/images/badge_private.gif b/skins/classic/images/badge_private.gif new file mode 100644 index 0000000000000000000000000000000000000000..900ed73389ad823f514ed73f928fb00e98fe7110 GIT binary patch literal 1221 zcmV;$1UmaiNk%w1VO#)Q0K^{vq{QhFWyC9X%;DkTr?$uxX~PLv#M9&TON!NzqPF(- z_K36N9c;r4T*SfF@DE_bbf?~BoZImB{267#2v@}8?Dsf-&lX?94PL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Ey6C1Oo&e@^r>;8ddb@sl>#}nJyX@bsPCM?lFOGZe jj{m;s+QR=yK-0z700q~{(@;Y5HS7%i^wd{RLkIvn)r3V1 literal 0 HcmV?d00001 diff --git a/skins/classic/images/badge_private.png b/skins/classic/images/badge_private.png new file mode 100644 index 0000000000000000000000000000000000000000..acf32070c598dc80b0b896336f7824c38814936c GIT binary patch literal 3359 zcmV+)4dC*LP)l9dA1;OP_Av&WKHIa;x#wPvHsb)G&(xwURwEfVDwO=}I zXIQ*TphDfzGMWU(Mr=*7iG#9ejGEi?ocD9@T_8s6413PZnS1vxk<^Lw7>vg5j3 zbmiscO+nkeXwf3iSBqX<7gKU#aB4}=gzctBd|ukY&qv!|DUSS}8~cXlG7z=#ys5m@x%GpNgQT zRyH1xp}S>pBc#}xXt%e6{uTsnd#Vf_>t*6Yp9Fi>tXU7wnKLIgJw1Iof}W9+lk*J( zy(oQULo+}J7mwuih()#3;RaZ@*9v`a^g++c%2J@ai`&8@x;aA9nL>D?OPo_4<0Tv5 z$0EICMLYDg6)5Q?7N-|SP>k$pZ--4Ca-wb50DKvN9+i5rCp|EF(n}*GS_1vl;j`wc z3&Uo|d)Lj(ZQVpCG~w(R=hb>CN?+BeKp$x!aw?8X_JlC({|tU+ZurqT^W|gzGT*;^ z)6A?tslaB6(MgvIX+*fPN~HJR3JjPxZ+&ilboDdy+s~cha9e)gkD;g6oit<1gjTT6 zwO;JdBlXtuek*XrWb5u-(=0#w0Z%dPljnzU;`y~Qb;p%yy%6XnDsm+Jo;(!~waX#w;jf4Yp{ zpV!c%w1y0FthD2N1bWt!I_Ws+e44bheURKp&|%fTao(m7+@<&gbU26f>!eFbC(xy- z(JPKn5TP(SEl>^y?Uho!Q93&8xQzh~9g-efN}$UHktH^*7U|{RYSMpYTrm@T9o*e9 zWd?^HV*_pwtucETp) z^e45`vC|c`SSLw&xUm#X2Ai#G!*|T3dqZ3)@{ZTgRlTUnFbHItVi`2+MnEGB_TY^> z=JCH@#piHsW_1@yI#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pKgB`L?dw%z7**92T6LoaMZ(A&Z(^0+Q18=cSDA*NA)zWaCo6o0}) zZ6kvYTTx0aDWVKGhF^mVX(RpL>M~ptbd6j{QPMqrlyqri_eev{i+>a!n_IB28^eTj zvsLob_qek~vek5B`1JMkIt2Z@`?taW%jlZGYgE0+&^?y1ooNG-4tfEg039^)Eu~-@ z5?ldUxn56_p0(jXwQGW}5hqgObfy=>Hnz8R4sfjibXE{CP@3!%3v>ZFs2uTmZD7b1 z1#9G_uR%$#4uoZ;h>21_hdzAH&Q7%xp&IcxK)0tnh?DM$k~IdWw-M;l*iIZB#Lxlw z>>ZsFTxVx1>8_*i*9+yiqG*lMy-3jIXCz!3L9P;^6z4<}(1rkA&t3Jt1^2|i;wfSo~-9d4z7w@^E zbd9bT4Bb$55>X)z1ya%q-%$*F>`r&+M63x{+$||Zq}+)5gpV0|3NECP+dkfjNIFsB z2cx=Z-cz5Bro^zLN-V<-QHRClb?SAE`wKeV3Y?|ep6Z~zcxvEZ4EnU1wy*-RPENL^ zLy3@djrpFS2T70ZFxXfXq7+T-@OyN6ErKqO@AYbuJ(g=8o$&hyJ(5N|wiZz*{L4+G zYpGsFD3FR?bkV#&NuORD2rC1RrT6w&MtzO+OGDpoPx=VYQ#8);){AB0)F|&ebi<4Y zUMGAU^olTqgbrVK4Bs&gU+hi4P2HpMj3adV9n+7{Z&P>Y<>k3Gn(>D| pnSO=+LkRd3jpYHt*BJf}>wjQcdjcJotUv$&002ovPDHLkV1nw;d$#}p literal 0 HcmV?d00001 diff --git a/skins/classic/images/calendar-blue.png b/skins/classic/images/calendar-blue.png new file mode 100644 index 0000000000000000000000000000000000000000..95c9452cae5306914be81b78de3f6916dbd9fa75 GIT binary patch literal 896 zcmV-`1AqL9P)`?_PK7O5p`^G4OH|b8~a3J6+z;)O;MeZa@ec)*R;3DQMw}#em&i1AaAv%gLX{bhai#p~oe`crHsx1s_2~UngO;3K^et$(m=(s&(X6BrWmHz9 z`b;f^ONFpv#`cznarKURYO*G&sP+RbJxj>Q2;gDpI|Au`JPsQ;k%PmTra5?SODiW( zRCE#|t|Q?0Q=bI4z7F&LEoo2e;t+a_aROY|?YIG^tW3>1auw8S2KSYCD>m?ajv z6`!=^VtY?4Y+2q}aydOvlr*P+)mFc5RX-L8q;?L>;dct~&oY++9*+m literal 0 HcmV?d00001 diff --git a/skins/classic/images/calendar.gif b/skins/classic/images/calendar.gif new file mode 100644 index 0000000000000000000000000000000000000000..4b25de072c75b10e3aa3658b2966c7651dcc0dda GIT binary patch literal 546 zcmV+-0^R*bNk%w1VHf}y0M$PL=}=JG;^JCsYwPXp);v6lnwpAuc=Pk~c87=btE>5B zWS4}5)ZN|D*4C}Jx9j=&!OP2>ii+gqh|{K@bJdc(t?wd`276w`ugSc^!)z* zzRSzE#KfASqJ?^To~^A(T3Y>aas7UN?DX{M^77&B?f3ip^!fS0FE5`bC&tFc;Ymq# zVq*V;gOPuK&NMWFZ*TTwWbpR(@?Ku-Q&ZdN>E7$>;^N}^{QTnc^VsO<@K{)AS6Bc4 z|NQ*?A^8LW002J#EC2ui02lxm000L6z@KnPEEvI{U|jYKI`N<^>M@CH*BG z7bX;_&@aG*4*v2DG4P;*!-p0GaB#>#K!=A93@oHzqNB%%985R}LDEA<3L1qNpm3w* zjU5gqcyLLxCCVW&G}zb)B7^`x5IchkwV@%#kQN$tC|%05sZtFsjy}*qwW`&tR3AkB kG2lawuVBN94f|ohj{^fF;8@GHt=qK{1{`2Qmq`!+JEQRkw*UYD literal 0 HcmV?d00001 diff --git a/skins/classic/images/calendar.png b/skins/classic/images/calendar.png new file mode 100644 index 0000000000000000000000000000000000000000..caab8a3842ca95f280fb4a5b2a7f69aba751a05c GIT binary patch literal 888 zcmV-;1Bd*HP)UOIsI> zkazC%%-r1TO>8jK95{F8&YbzabLN~gIAIK&^RlaftAgaaqJYu(iFB0n4jLLszXlom z+==2+%${3p*dZ|y%WIn76AKHR*Z1%2_*a^mHlHwdh%2OseJBIG@@g8?w7$^dotSuv zOa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UonAai z+)pwfis}H1S&yHrZ>&`(#wU}j@4s6V)mh(IBaY*zSzDQzogOo@+mfyy1suom%Q%kb z9^8Mpo&#svK&Ye$90yJUC&IV@w1GdsKJXLx1^fnD;XitT6Ymw06hfkb5HlbSpk{b) c|GR>J0Sg-&j4Z6xZvX%Q07*qoM6N<$f{ma00092 zoR6u??GFct^Z`+`x>$SOc@-Fn5LucHnyQ-s$E|y?Fum9}j_5ltkqLh|UkqqG7KhB4 zCMlyqqpB%YWW7F{T;izP{eZ)nEVDcYf79d>TkU?gS8_PLK7Zl!y}dnQ_Lk!}rbn0; zSl4%0Xpo5K$jBBXnFe$T6oBavpt-rw>G_EeDmpq)YWkU~ipkoV`8xXAxk?M`a$9?; zyUWw-O9LFNGE6LDe5{eIT*2HN@eKVSJ>5`k4T_C>z0Ixd?d+XxFdiCho}GTqxjyaA z4i3)%Un*a(P@kHhzkks04;4Ur0tcQm81R%r3k!QpXea@|!-WzhHmqn-A;yepqc(Ef zQyV&ut~#y9cy-jS&U%UessIBD%_uQGawv<9^TQ zL#vESX_awOz$Kgva1AE`+`@$e_i&-W99$SM7Z(C7!O?-GI4ZCPM+4U4C_oDi4z%K+ zKo1-Y=!Js-J#p?pZ=5R-fpY_*a4tY3&J0B3Oh5*%8py&`0hzdBARAW%jKF0Bqi|Wk zNZc+k8n+2lz^wvRaEm}C+zhCOn*bGYBTyAL0F`kmjrvYBDa|I%BZa@^y1&G9%foPlw$iP(tS-2`76ITpmcfhY1K#4KfJ-xP=P`?%_g#Ik+%jE-nOEf};aVaa3Rpjs~p7 zQGga49B9QsfgU&*&OxEW9lHvuZ*MxZJ#rRjTJT*|)y0|4)uSqBM$ R2VwvK002ovPDHLkV1fXt{W|~v literal 0 HcmV?d00001 diff --git a/skins/classic/images/invitation.png b/skins/classic/images/invitation.png new file mode 100644 index 0000000000000000000000000000000000000000..f3df83a722f349ddab903916ea6e88d4ba50a139 GIT binary patch literal 1909 zcmV-*2a5QKP)K&KWAr#v*Q_dW_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90cH>#+5P+X;URu4rIlm~ z?g6%J+5~R2U2llbzI(_ibp!Na4$Lcvem&+BgYR}<_ zH7)rsH*SPTCPR`3&6A-Aj}DvuE%CC5V$j1krrOiUKs(b~i4sbiFQV)GHKonh0qv8k zm7?VX-6N2EVDQmOdf=1fHv2=)HNB+mZx$V7ODLccn#@4UY-;fx$_if00000NkvXXu0mjfxoWh@ literal 0 HcmV?d00001 diff --git a/skins/classic/images/listheader.gif b/skins/classic/images/listheader.gif new file mode 100644 index 0000000000000000000000000000000000000000..bf77a11c13302ba639458d1bd621a4f577783c69 GIT binary patch literal 322 zcmV-I0lof5Nk%w1VGIB?0K@gw+A@6OK7@$&N0($mq=(B9tNs;R2Iy}YHP zqu}7+nV6Wv!@}$A?C0s}(9h46lasc#x3I9V%E`*)3)ld@;4nBtE}O}Pw0fO3xZiO1U;u&4 z>-a%u-_h&&9Up>&go1#Fh>41eiyV%Rkdcy)6_u8kl?$4ioSGP)prM~z`h8>#Kpr3$jQpc7R}Dj%?#4h)Y1{x*xAGe375_;&7o{eaq^2m8 zXO?6rBxWU6otbEINafjWLRY2!70|NW6iz~gEtaOk8&Zmh)doe~~B7us%UunTmtm@p|k*U*tz=BAkF!4MHVgQGFmbjeo6 zBo~h@Yz(V*CMM}{^{F-#7>gwzQQn~bgZGURyNQ{3fSOi>euG9&uL@R6z+soy%IayL(jn0+=WV`;*F%T>V5e?LvsP2HtCWbqlEbVA#nav0=JHKcBOC28X^OOB!p8W_OR8B7-$3d4d4|tKba{ literal 0 HcmV?d00001 diff --git a/skins/classic/images/minicolors-all.png b/skins/classic/images/minicolors-all.png new file mode 100644 index 0000000000000000000000000000000000000000..001ed888c232598a57e83ea746ecab7b6772674d GIT binary patch literal 13370 zcmV-AG{wt_P)uS<=^Yq zujjx1^{@KH7hlXj`q7W(fB4`3OP`ckN;QDfM^69BvbEH2Y5NcVl~QCmtQ6ROc>h`^ z`N#kMqyKhz`%Ss-zyJHuM<4w&Zg_h5TfT94esBF<@lAN0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C6aQS_>F(*SdLE{yog~A=ANb%=MOW3QUR8fz zJ@`(h>V3?Pj@$?S{7lA!qeqS%|E!tW(Gd|5(ONfj5s~cZh}2{J&}f6%*;#VA9023v zPf<#7;J`tYQrNalTU%T0$(L+ktrmT2Yb#Sz&q$?GB$G*|rk-KjHkM^IeE`6T6DP4OYdJVrHRAq(zMgo{vTz&+$8ks` z60BdpA%@moMeUlp;QoQWGr;rOh;7@(wr#d=-$7?*CzfT!USrRrwQ2=88n`of{vrUy zVi5pi3|ed2+ka*A=5{>K!*yL27Z>9>U6~BPo&JHo(^aNg4qcefGd3~7_}Cc6=!QS` z7uzP2$*^bdKHj~1%fr7O0-U`tcxkvAtyIl*UHMXT97i0-k(rqp=^yBmC90S&2#XO$w@jo zwvbM*1u6;sDn%I90T&7dy1Fv_)YeL2zJLWtq#h9=2m?M8iI zy}t&Cs>!_TK<~GdqaX-xUb%er91y5Fr78uq0GoiHfpx%-k(+3a0g8YF{14=S5}>28 v`ZX`g_ccHwYLijF3f9q6=|-(tUO_$rB9yL?Z@7iG00000NkvXXu0mjfkWG&7 literal 0 HcmV?d00001 diff --git a/skins/classic/images/spacer.gif b/skins/classic/images/spacer.gif new file mode 100644 index 0000000000000000000000000000000000000000..c749aaf73f7ab4dfbee94f96a60be4eff9f5ac17 GIT binary patch literal 807 zcmYjQO=uHg5PcgqNqf*kSjY+Og^}XFK&A{ZF@0&OCW@aZB=Fb;SEn2X! z0|Y?;$uX)u%wWg*+^C_7Mcl&!Ji!T+v4n^8woNhR2#QBZ-{g8O_U?m|Su`yNz26yn z9ZaWvlczOzKzIk6H3w_-3IF3y2JUv-6o?^rAneJ0hCIeo-4osTYleQTR{dCweV2EA7p_wwQjX2*SVnYxg4kVgU~@+XLC zpJjexB;vY1V!O;eMVxs1F|YX4b0pCmRHwKlE$S7HG|6+9y>>sj_|BZ_waPr|Rdc(0 z$T!ca-uf$3)yZB8j8T3J{yps}h6PT>b7~T!SYb8G1kcf0Dz~%fu3JbmM?LPL9>8`z4;%XgjZ8dV_ol5D|L7($eJu`o!`3<-m;?$0O zU5WY_BW^%D>O*n+QuSyOk%lXl7>e}D%3IAleC&p= Nh|`n8lO7BV)&PTMCu{%! literal 0 HcmV?d00001 diff --git a/skins/classic/images/toolbar.gif b/skins/classic/images/toolbar.gif new file mode 100644 index 0000000000000000000000000000000000000000..2cf2693c5a7957cfc0faff3d83fc24b8551b170d GIT binary patch literal 6186 zcmWlc`(I0smPXj@O(Ufc)7W|+H43Y1sK40B{0$7f6LmsZ|F@$ zMddyz#(h8Ma`E*)QBl>k(vAKJr_aQio3FXOd9#`8f$8ZlG9RD$`L87--!ERg*x%pZ z9vqyKebGH=U2{w8U!`*Mp`^K=zvI*MX7}#BQFcE&Bt-o7mqIZ!_w~ono7L6T zwY7DJwr{uLkiH*2-1xY8`9}X=@$tNieshzPALr&`BDL8R3l^oZQ_V$;lI+W-Xa34i>(RH#E$xmOgp% z?l~jzP`1;I6R!02L%c4 z=M`O*%jKs_pY4oDJC$1CQwAT3&mI2U?~`u)c48tcJ6Aq6#jT!vJ3Bjb`<5UpdvI{* z)vMP7#>S^o4+jMW?NV3g$ESuH85MYV_&4;@ektz(KCHwY!Ix zw6im%<#SlsMBu@on7WS(bo!5lg#>5kL>rs2g9n4IzsdITX;`)D!|X(PRfCVu&Vs7s z&belz#y`I04Dy?0H0 z``gg{u*uf;c3IhW7Z*(?lJG=$y~XFTrX)a^`2O8p!X5*l^LYm0Z} z;lrB_UJAVUTFzvC`tf6_8yHw;^tkPbpljxQUQyrlLVjP&C%OC(Z>P&<*NDio+rsni z-+!==ms@a%F+5n@0|t-SAU6KQnXa$O-FzR_I%4_?$S)q0^7&6a=@MmDF6><-7NozrRB~aO5<*==z=81Idp+mNqYB z{rdfzpbmWcH1&CM^2MwE2laO^6lUyXdqkZNKX~Y1_p?r^{PCN2<8R))8S3lfKc3@_ zI^Vr3diba|CZ8L8F6rC%AE@4%VWo0+)zVmDWdN_DHuM)>#EY6DHgJfy_36jRu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CPHnvt zoPzw>p~ZKYoZKMhx}<}2+o7FKD;Vm^TFE`}m{&ghF6-|7{rxp~u@3jCIUj;Th=T`# zmx*1S5;aCTGa%g_u1j$8i`C8LGMk}L(NKMq*@_f&r$i#jNl8gD_O+xL`#=OYHFW0e zbf-Wh`(%@Xf)=VNYOH5|(sqtJ_M2Y6O_Z@1F%-=VojE$&drLdHWXTe#Uaub%9TT&X zM5ULPm5(87o2Z`nqK6CAo8#_nQgU)fENn}2^E2DFZL0tu^OKGoH9E)hez_-4TylO= z(G2My5E3<9?jO0IXz4vgb#=gma|4*|dQ6mGp-ZU1#ra7YdpmH}#;I*Bb>zFAt==rm z>jKj5>+ZcR#4nF*%@5lej9?vwbrAjz5&_qOz%0RiPi?({w5h3yEaM(6&hQ>t^QGn|6;9#o`1fx+cI+ta z?rekqhWw;ro1|*Rd&)c}id5W6dbod|o?+I9Rd{ieVTQ-xFsv z8eJBPg~Q`)d3ib8($d2Az*yXXb^q-WR3Gmj{7NpUE9DPgu7LDP`NNn0C%^#WgwS%? S8l7 + + +<roundcube:object name="pagetitle" /> + + + + + + + + + +
    + +
    + + + + diff --git a/skins/classic/templates/calendar.html b/skins/classic/templates/calendar.html new file mode 100644 index 0000000..2afa653 --- /dev/null +++ b/skins/classic/templates/calendar.html @@ -0,0 +1,201 @@ + + + +<roundcube:object name="pagetitle" /> + + + + + + + + + +
    +
    +
    + +
    +
    +
    + +
    +
    + +
    +
      +
    • +
    • +
    • +
    • + +
    • + +
    +
    + +
    +

    Event Title

    +
    Location
    +
    From-To
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + Default +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + +
    + + + +
    + + +
    +   +
    + +
    +
    + +
    +
    + +   + +
    +
    + +   + +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    + + +
    + + + + +
    +
    + +
    + +
    + +
    + +
    + +
    +

    + +
    + +
    + + + + +
    + +
    + + + +
    + + + + + + + diff --git a/skins/classic/templates/eventedit.html b/skins/classic/templates/eventedit.html new file mode 100644 index 0000000..6e1c2b3 --- /dev/null +++ b/skins/classic/templates/eventedit.html @@ -0,0 +1,108 @@ +
    +
    +
      +
    • +
    • +
    • +
    • +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + + +   + +
    +
    + +   + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    + + + +
    + +
    +
    + +
    +
    + +
    +
    +
    + +
    \ No newline at end of file diff --git a/skins/classic/templates/freebusylegend.html b/skins/classic/templates/freebusylegend.html new file mode 100644 index 0000000..85a565c --- /dev/null +++ b/skins/classic/templates/freebusylegend.html @@ -0,0 +1,7 @@ +
    + + + + + +
    diff --git a/skins/classic/templates/itipattend.html b/skins/classic/templates/itipattend.html new file mode 100644 index 0000000..84968b5 --- /dev/null +++ b/skins/classic/templates/itipattend.html @@ -0,0 +1,21 @@ + + + +<roundcube:object name="pagetitle" /> + + + + +