From 99f904adcc37d93c90defcd8ce898598e25be212 Mon Sep 17 00:00:00 2001 From: Hugues Hiegel Date: Wed, 11 Mar 2015 16:55:04 +0100 Subject: Lot of plugins --- libgpl/CHANGELOG | 39 + libgpl/LICENSE | 671 ++++++ libgpl/README | 8 + libgpl/caldav/caldav-client.php | 468 +++++ libgpl/caldav/caldav_sync.php | 284 +++ libgpl/caldav/vobject_sanitize.php | 110 + libgpl/contextmenu/jquery.contextMenu.js | 1686 +++++++++++++++ libgpl/contextmenu/jquery.ui.position.js | 497 +++++ libgpl/date/date.js | 335 +++ libgpl/dialogextend/jquery.dialogextend.js | 509 +++++ libgpl/dialogextend/jquery.dialogextend.min.js | 2 + libgpl/encryption/encryption.php | 166 ++ libgpl/fancybox/blank.gif | Bin 0 -> 43 bytes libgpl/fancybox/fancy_close.png | Bin 0 -> 1517 bytes libgpl/fancybox/fancy_closebox.png | Bin 0 -> 1910 bytes libgpl/fancybox/fancy_left.png | Bin 0 -> 1623 bytes libgpl/fancybox/fancy_loading.png | Bin 0 -> 10195 bytes libgpl/fancybox/fancy_nav_left.png | Bin 0 -> 1446 bytes libgpl/fancybox/fancy_nav_right.png | Bin 0 -> 1454 bytes libgpl/fancybox/fancy_progress.png | Bin 0 -> 12412 bytes libgpl/fancybox/fancy_right.png | Bin 0 -> 1645 bytes libgpl/fancybox/fancy_shadow_e.png | Bin 0 -> 107 bytes libgpl/fancybox/fancy_shadow_n.png | Bin 0 -> 106 bytes libgpl/fancybox/fancy_shadow_ne.png | Bin 0 -> 347 bytes libgpl/fancybox/fancy_shadow_nw.png | Bin 0 -> 324 bytes libgpl/fancybox/fancy_shadow_s.png | Bin 0 -> 111 bytes libgpl/fancybox/fancy_shadow_se.png | Bin 0 -> 352 bytes libgpl/fancybox/fancy_shadow_sw.png | Bin 0 -> 340 bytes libgpl/fancybox/fancy_shadow_w.png | Bin 0 -> 103 bytes libgpl/fancybox/fancy_title_left.png | Bin 0 -> 503 bytes libgpl/fancybox/fancy_title_main.png | Bin 0 -> 96 bytes libgpl/fancybox/fancy_title_over.png | Bin 0 -> 70 bytes libgpl/fancybox/fancy_title_right.png | Bin 0 -> 506 bytes libgpl/fancybox/fancybox-x.png | Bin 0 -> 203 bytes libgpl/fancybox/fancybox-y.png | Bin 0 -> 176 bytes libgpl/fancybox/fancybox.png | Bin 0 -> 15287 bytes libgpl/fancybox/jquery.easing-1.3.pack.js | 72 + libgpl/fancybox/jquery.fancybox-1.3.4.css | 359 ++++ libgpl/fancybox/jquery.fancybox-1.3.4.js | 1156 ++++++++++ libgpl/fancybox/jquery.fancybox-1.3.4.pack.js | 46 + libgpl/fancybox/jquery.mousewheel-3.0.4.pack.js | 14 + libgpl/flashclipboard/clipboard.swf | Bin 0 -> 1071 bytes libgpl/flashclipboard/flashclipboard_libgpl.js | 309 +++ .../flashclipboard/flashclipboard_moreuserinfo.js | 290 +++ libgpl/gibberish/GibberishAES.php | 213 ++ libgpl/gibberish/gibberish-aes.js | 36 + libgpl/gibberish/gibberish-aes.js.comp.src | 1017 +++++++++ libgpl/http_request/class.http.php | 1190 +++++++++++ libgpl/ical/ical_sync.php | 144 ++ libgpl/jquery_migrate/jquery.migrate.js | 521 +++++ libgpl/libcalendaring/libcalendaring.js | 676 ++++++ libgpl/libgpl.php | 189 ++ libgpl/localization/cs_CZ.inc | 48 + libgpl/localization/en_US.inc | 36 + libgpl/localization/es_ES.inc | 48 + libgpl/localization/fi_FI.inc | 48 + libgpl/localization/fr_FR.inc | 51 + libgpl/localization/revision.inc.php | 11 + libgpl/package.xml | 22 + libgpl/password/password.js | 36 + libgpl/qtip/qtip.css | 1 + libgpl/qtip/qtip.js | 68 + libgpl/querystring/querystring.js | 34 + libgpl/skins/classic/calendar.css | 4 + libgpl/skins/classic/images/convert.png | Bin 0 -> 709 bytes libgpl/skins/classic/images/delete.png | Bin 0 -> 536 bytes libgpl/skins/classic/images/door.png | Bin 0 -> 412 bytes libgpl/skins/classic/images/edit.png | Bin 0 -> 618 bytes libgpl/skins/classic/images/message.png | Bin 0 -> 376 bytes libgpl/skins/classic/images/note.png | Bin 0 -> 844 bytes libgpl/skins/classic/images/task.png | Bin 0 -> 684 bytes .../ui-bg_highlight-hard_75_f8f8f8_1x100.png | Bin 0 -> 88 bytes .../ui-bg_highlight-hard_90_e6e6e7_1x100.png | Bin 0 -> 101 bytes .../ui-bg_highlight-soft_90_e4e4e4_1x100.png | Bin 0 -> 111 bytes .../classic/images/ui-icons_004458_256x240.png | Bin 0 -> 4369 bytes libgpl/skins/classic/jquery.contextMenu.css | 141 ++ libgpl/skins/classic/timepicker2.css | 10 + libgpl/skins/larry/calendar.css | 6 + .../ui-bg_highlight-hard_75_f8f8f8_1x100.png | Bin 0 -> 88 bytes .../ui-bg_highlight-soft_90_e4e4e4_1x100.png | Bin 0 -> 111 bytes .../skins/larry/images/ui-icons_004458_256x240.png | Bin 0 -> 4369 bytes libgpl/skins/larry/jquery.contextMenu.css | 154 ++ libgpl/skins/larry/timepicker2.css | 13 + libgpl/timepicker/jquery.timepicker.css | 72 + libgpl/timepicker/jquery.timepicker.js | 1149 ++++++++++ libgpl/timepicker/jquery.timepicker.min.js | 7 + libgpl/timepicker2/jquery.timepicker.js | 2223 ++++++++++++++++++++ 87 files changed, 15189 insertions(+) create mode 100644 libgpl/CHANGELOG create mode 100644 libgpl/LICENSE create mode 100644 libgpl/README create mode 100644 libgpl/caldav/caldav-client.php create mode 100644 libgpl/caldav/caldav_sync.php create mode 100644 libgpl/caldav/vobject_sanitize.php create mode 100644 libgpl/contextmenu/jquery.contextMenu.js create mode 100644 libgpl/contextmenu/jquery.ui.position.js create mode 100644 libgpl/date/date.js create mode 100644 libgpl/dialogextend/jquery.dialogextend.js create mode 100644 libgpl/dialogextend/jquery.dialogextend.min.js create mode 100644 libgpl/encryption/encryption.php create mode 100644 libgpl/fancybox/blank.gif create mode 100644 libgpl/fancybox/fancy_close.png create mode 100644 libgpl/fancybox/fancy_closebox.png create mode 100644 libgpl/fancybox/fancy_left.png create mode 100644 libgpl/fancybox/fancy_loading.png create mode 100644 libgpl/fancybox/fancy_nav_left.png create mode 100644 libgpl/fancybox/fancy_nav_right.png create mode 100644 libgpl/fancybox/fancy_progress.png create mode 100644 libgpl/fancybox/fancy_right.png create mode 100644 libgpl/fancybox/fancy_shadow_e.png create mode 100644 libgpl/fancybox/fancy_shadow_n.png create mode 100644 libgpl/fancybox/fancy_shadow_ne.png create mode 100644 libgpl/fancybox/fancy_shadow_nw.png create mode 100644 libgpl/fancybox/fancy_shadow_s.png create mode 100644 libgpl/fancybox/fancy_shadow_se.png create mode 100644 libgpl/fancybox/fancy_shadow_sw.png create mode 100644 libgpl/fancybox/fancy_shadow_w.png create mode 100644 libgpl/fancybox/fancy_title_left.png create mode 100644 libgpl/fancybox/fancy_title_main.png create mode 100644 libgpl/fancybox/fancy_title_over.png create mode 100644 libgpl/fancybox/fancy_title_right.png create mode 100644 libgpl/fancybox/fancybox-x.png create mode 100644 libgpl/fancybox/fancybox-y.png create mode 100644 libgpl/fancybox/fancybox.png create mode 100644 libgpl/fancybox/jquery.easing-1.3.pack.js create mode 100644 libgpl/fancybox/jquery.fancybox-1.3.4.css create mode 100644 libgpl/fancybox/jquery.fancybox-1.3.4.js create mode 100644 libgpl/fancybox/jquery.fancybox-1.3.4.pack.js create mode 100644 libgpl/fancybox/jquery.mousewheel-3.0.4.pack.js create mode 100644 libgpl/flashclipboard/clipboard.swf create mode 100644 libgpl/flashclipboard/flashclipboard_libgpl.js create mode 100644 libgpl/flashclipboard/flashclipboard_moreuserinfo.js create mode 100644 libgpl/gibberish/GibberishAES.php create mode 100644 libgpl/gibberish/gibberish-aes.js create mode 100644 libgpl/gibberish/gibberish-aes.js.comp.src create mode 100644 libgpl/http_request/class.http.php create mode 100644 libgpl/ical/ical_sync.php create mode 100644 libgpl/jquery_migrate/jquery.migrate.js create mode 100644 libgpl/libcalendaring/libcalendaring.js create mode 100644 libgpl/libgpl.php create mode 100644 libgpl/localization/cs_CZ.inc create mode 100644 libgpl/localization/en_US.inc create mode 100644 libgpl/localization/es_ES.inc create mode 100644 libgpl/localization/fi_FI.inc create mode 100644 libgpl/localization/fr_FR.inc create mode 100644 libgpl/localization/revision.inc.php create mode 100644 libgpl/package.xml create mode 100644 libgpl/password/password.js create mode 100644 libgpl/qtip/qtip.css create mode 100644 libgpl/qtip/qtip.js create mode 100644 libgpl/querystring/querystring.js create mode 100644 libgpl/skins/classic/calendar.css create mode 100644 libgpl/skins/classic/images/convert.png create mode 100644 libgpl/skins/classic/images/delete.png create mode 100644 libgpl/skins/classic/images/door.png create mode 100644 libgpl/skins/classic/images/edit.png create mode 100644 libgpl/skins/classic/images/message.png create mode 100644 libgpl/skins/classic/images/note.png create mode 100644 libgpl/skins/classic/images/task.png create mode 100644 libgpl/skins/classic/images/ui-bg_highlight-hard_75_f8f8f8_1x100.png create mode 100644 libgpl/skins/classic/images/ui-bg_highlight-hard_90_e6e6e7_1x100.png create mode 100644 libgpl/skins/classic/images/ui-bg_highlight-soft_90_e4e4e4_1x100.png create mode 100644 libgpl/skins/classic/images/ui-icons_004458_256x240.png create mode 100644 libgpl/skins/classic/jquery.contextMenu.css create mode 100644 libgpl/skins/classic/timepicker2.css create mode 100644 libgpl/skins/larry/calendar.css create mode 100644 libgpl/skins/larry/images/ui-bg_highlight-hard_75_f8f8f8_1x100.png create mode 100644 libgpl/skins/larry/images/ui-bg_highlight-soft_90_e4e4e4_1x100.png create mode 100644 libgpl/skins/larry/images/ui-icons_004458_256x240.png create mode 100644 libgpl/skins/larry/jquery.contextMenu.css create mode 100644 libgpl/skins/larry/timepicker2.css create mode 100644 libgpl/timepicker/jquery.timepicker.css create mode 100644 libgpl/timepicker/jquery.timepicker.js create mode 100644 libgpl/timepicker/jquery.timepicker.min.js create mode 100644 libgpl/timepicker2/jquery.timepicker.js (limited to 'libgpl') diff --git a/libgpl/CHANGELOG b/libgpl/CHANGELOG new file mode 100644 index 0000000..9defcc5 --- /dev/null +++ b/libgpl/CHANGELOG @@ -0,0 +1,39 @@ +VERSION COMMENT +---------------------------------------------------------------------------------- +1.0 - Initial release +1.0.1 - Added log option to CalDAV client +1.0.2 - Added date.js toolbox + (http://www.mattkruse.com/javascript/date) +1.0.3 - Added sync interval property to caldav sync client +1.0.4 - Moved ical_sync to libgpl +1.0.5 - Include querystring.js for tasklist +1.0.6 - Replace the big close button in jquery dialogs +1.0.7 - 1.0.9 - Fetch reminders almost immediately after page + initialization and not with a delay of 1 minute +1.0.10 - 1.0.12 - Include jquery contexmenu + (http://medialize.github.io/jQuery-contextMenu/demo.html) +1.0.13 - Include date.js for sticky_notes +1.0.14 - Larry skin improvements +1.0.15 - Implement contextmenu for sticky_notes +1.0.16 - Include fancybox +1.0.17 - Re-organize folder structure +1.0.18 - Clean up larry skin images +1.0.19 - Include jquery timepicker +1.0.20 - Include http_request +1.0.21 - Make sure jqueryui plugin is loaded first of all +1.0.22 - 1.0.23 - Include qtip +1.0.24 - Fix javascript error in libcalendaring.js if date format + is undefined +1.0.25 - Move label overwrites to libgpl +1.0.26 - Add password.js overwrite +1.0.27 - CalDAV: Send User-Agent header +1.0.28 - 1.0.29 - Implement gzip decompression in ical driver +1.0.30 - css fix: min-width for jqueryui dialogs (calendar/ + carddav plugins) +1.0.31 - CalDAV: Implemented digest authentication +1.0.32 - 1.0.33 - CardDAV: Overwrite default subscribed label +1.0.34 - Header User-Agent: MyRoundcube-SabreDAV +1.0.35 - Move SabreDAV components to libcalendaring plugin +1.0.36 - CalDAV: Don't use gmdate for UTC timezone conversion +1.0.37 - CalDAV: Make cURL verify host configurable +1.0.38 - CalDAV: Implement DELETE request \ No newline at end of file diff --git a/libgpl/LICENSE b/libgpl/LICENSE new file mode 100644 index 0000000..56c3b5b --- /dev/null +++ b/libgpl/LICENSE @@ -0,0 +1,671 @@ + +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. + +dev-team [at] myroundcube [dot] com +http://myroundcube.com + +--- LICENSE DETAILS --- + + 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/libgpl/README b/libgpl/README new file mode 100644 index 0000000..df9059f --- /dev/null +++ b/libgpl/README @@ -0,0 +1,8 @@ +libgpl +------ +Documentation: +http://myroundcube.com/myroundcube-plugins/ + + +MyRoundcube Dev Team +www.myroundcube.com \ No newline at end of file diff --git a/libgpl/caldav/caldav-client.php b/libgpl/caldav/caldav-client.php new file mode 100644 index 0000000..417c42b --- /dev/null +++ b/libgpl/caldav/caldav-client.php @@ -0,0 +1,468 @@ + + * + * Copyright (C) 2013, Awesome IT GbR + * + * 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__).'/../../libcalendaring/SabreDAV/vendor/autoload.php'); +require_once (dirname(__FILE__).'/vobject_sanitize.php'); + + +class caldav_client extends Sabre\DAV\Client +{ + const CLARK_GETCTAG = '{http://calendarserver.org/ns/}getctag'; + const CLARK_GETETAG = '{DAV:}getetag'; + const CLARK_CALDATA = '{urn:ietf:params:xml:ns:caldav}calendar-data'; + + public $base_uri; + public $path; + private $libvcal; + private $rc; + private $user_agent; + + /** + * Default constructor for CalDAV client. + * + * @param string Caldav URI to appropriate calendar. + * @param string Username for HTTP basic auth. + * @param string Password for HTTP basic auth. + * @param boolean Verify SSL cert. // Mod by Rosali (https://gitlab.awesome-it.de/kolab/roundcube-plugins/issues/1) + */ + public function __construct($uri, $user = null, $pass = null, $verifySSL = array(true, true)) // Mod by Rosali (https://gitlab.awesome-it.de/kolab/roundcube-plugins/issues/1) + { + $this->user_agent = 'MyRoundcube-SabreDAV/' . Sabre\DAV\Version::VERSION; + + // Include libvcalendar on demand ... + if(!class_exists("libvcalendar")) + require_once (dirname(__FILE__).'/../../libcalendaring/libvcalendar.php'); + + $this->libvcal = new libvcalendar(); + $this->rc = rcube::get_instance(); + + $tokens = parse_url($uri); + $this->base_uri = $tokens['scheme']."://".$tokens['host'].($tokens['port'] ? ":".$tokens['port'] : null); + $this->path = $tokens['path'].($tokens['query'] ? "?".$tokens['query'] : null); + $settings = array( + 'baseUri' => $this->base_uri, + 'authType' => Sabre\DAV\Client::AUTH_BASIC + ); + + if ($user) $settings['userName'] = $user; + if ($pass) $settings['password'] = $pass; + + parent::__construct($settings); + + $this->verifyPeer = $verifySSL[0]; + $this->verifyHost = $verifySSL[1]; + $this->authType = CURLAUTH_BASIC | CURLAUTH_ANY; + } + + /** + * Fetches calendar ctag. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Retrieving_calendar_information + * @return Calendar ctag or null on error. + */ + public function get_ctag() + { + try + { + $arr = $this->propFind($this->path, array(self::CLARK_GETCTAG)); + + if (isset($arr[self::CLARK_GETCTAG])) + return $arr[self::CLARK_GETCTAG]; + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), true, false); + } + + return null; + } + + /** + * Fetches event etags and urls. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Finding_out_if_anything_changed + * + * @param array Optional list of relative event URL's to retrieve specific etags. If not specified, all etags of the current calendar are returned. + * @return array List of etag properties with keys: + * url: Event ical path relative to the calendar URL. + * etag: Current event etag. + */ + public function get_etags(array $event_urls = array()) + { + $etags = array(); + + try + { + $arr = $this->prop_report($this->path, array(self::CLARK_GETETAG), $event_urls); + foreach ($arr as $path => $data) + { + // Some caldav server return an empty calendar as event where etag is missing. Skip this! + if($data[self::CLARK_GETETAG]) + { + array_push($etags, array( + "url" => $path, + "etag" => str_replace('"', null, $data[self::CLARK_GETETAG]) + )); + } + } + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), true, false); + } + + return $etags; + } + + /** + * Fetches calendar events. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Downloading_objects + * @param array $urls = array() Optional list of event URL's to fetch. If non is specified, all + * events from the appropriate calendar will be fetched. + * @return Array hash list that maps the events URL to the appropriate event properties. + */ + public function get_events($urls = array()) + { + $events = array(); + + try + { + $vcals = $this->prop_report($this->path, array( + self::CLARK_GETETAG, + self::CLARK_CALDATA + ), $urls); + + foreach ($vcals as $path => $response) + { + $vcal = $response[self::CLARK_CALDATA]; + $vobject_sanitize = new vobject_sanitize($vcal, array('CATEGORIES'), 'serialize'); + $vcal = $vobject_sanitize->vobject; + $vobject_sanitize = new vobject_sanitize($vcal, array('RDATE'), 'unserialize'); + $vcal = $vobject_sanitize->vobject; + foreach ($this->libvcal->import($vcal) as $event) { + $events[$path] = $event; + } + } + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), true, false); + } + return $events; + } + + /** + * Does a REPORT request + * + * @param string $url + * @param array $properties List of requested properties must be specified as an array, in clark + * notation. + * @param array $event_urls If specified, a multiget report request will be initiated with the + * specified event urls. + * @param int $depth = 1 Depth should be either 0 or 1. A depth of 1 will cause a request to be + * made to the server to also return all child resources. + * @return array Hash with ics event path as key and a hash array with properties and appropriate values. + */ + public function prop_report($url, array $properties, array $event_urls = array(), $depth = 1) + { + $url = slashify($url); // iCloud + + $parent_tag = sizeof($event_urls) > 0 ? "c:calendar-multiget" : "d:propfind"; + $method = sizeof($event_urls) > 0 ? 'REPORT' : 'PROPFIND'; + + $body = ''."\n".'<'.$parent_tag.' xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'."\n"; + + $body .= ' '."\n"; + foreach ($properties as $property) + { + + list($namespace, $elementName) = Sabre\DAV\XMLUtil::parseClarkNotation($property); + + if ($namespace === 'DAV:') + { + $body .= ' '."\n"; + } + else + { + $body .= ' '."\n"; + } + } + $body .= ' '."\n"; + + // http://tools.ietf.org/html/rfc4791#page-90 + // http://www.bedework.org/trac/bedework/wiki/Bedework/DevDocs/Filters + /* + if($start && $end) + { + $body.= ' '."\n". + ' '."\n". + ' '."\n". + ' '."\n". + ' '."\n". + ' '."\n". + ' ' . "\n"; + } + */ + + foreach ($event_urls as $event_url) + { + $body .= ''.$event_url.''."\n"; + } + + $body .= ''; + + $response = $this->request($method, $url, $body, array( + 'Depth' => $depth, + 'Content-Type' => 'application/xml', + 'User-Agent' => $this->user_agent + )); + + $result = $this->parseMultiStatus($response['body']); + + // If depth was 0, we only return the top item + if ($depth === 0) + { + reset($result); + $result = current($result); + return isset($result[200]) ? $result[200] : array(); + } + + $new_result = array(); + foreach ($result as $href => $status_list) + { + $new_result[$href] = isset($status_list[200]) ? $status_list[200] : array(); + } + + return $new_result; + } + + /** + * Updates or creates a calendar event. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Updating_a_calendar_object + * @param string Event ics path for the event. + * @param array Hash array with event properties. + * @param string Current event etag to match against server data. Pass null for new events. + * @return True on success, -1 if precondition failed i.e. local etag is not up to date, false on error. + */ + public function put_event($path, $event, $etag = null) + { + try + { + $headers = array( + 'Content-Type' => 'text/calendar; charset=utf-8', + 'User-Agent' => $this->user_agent + ); + if ($etag) $headers["If-Match"] = '"'.$etag.'"'; + + // Temporarily disable error reporting since libvcal seems not checking array key properly. + // TODO: Remove this todo if we could ensure that those errors come not from incomplete event properties. + //$err_rep = error_reporting(E_ERROR); + $vcal = $this->libvcal->export(array($event)); + if (is_array($vcal)) + $vcal = array_shift($vcal); + + //error_reporting($err_rep); + $response = $this->request('PUT', $path, $vcal, $headers); + + // Following http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Creating_a_calendar_object, the + // caldav server must not always return the new etag. + + return $response["statusCode"] == 201 || // 201 (created, successfully created) + $response["statusCode"] == 204; // 204 (no content, successfully updated) + } + catch(Sabre\DAV\Exception\PreconditionFailed $err) + { + // Event tag not up to date, must be updated first ... + return -1; + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), true, false); + } + return false; + } + + /** + * Removes event of given URL. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Deleting_a_calendar_object + * @param string Event ics path for the event. + * @param string Current event etag to match against server data. Pass null to force removing the event. + * @return True on success, -1 if precondition failed i.e. local etag is not up to date, false on error. + **/ + public function remove_event($path, $etag = null) + { + return $this->delete_request($path, $etag); + } + + /** + * Fires a DELETE request to a given URL. + * + * @see http://code.google.com/p/sabredav/wiki/BuildingACalDAVClient#Deleting_a_calendar_object + * @param string Path. + * @param string Current etag to match against server data or null. + * @return True on success, -1 if precondition failed i.e. local etag is not up to date, false on error. + **/ + public function delete_request($path, $etag = null) + { + try + { + $headers = array( + 'Content-Type' => 'text/calendar; charset=utf-8', + 'User-Agent' => $this->user_agent + ); + if ($etag) $headers["If-Match"] = '"'.$etag.'"'; + + $response = $this->request('DELETE', $path, null, $headers); + return $response["statusCode"] == 204; // 204 (no content, successfully deleted); + } + catch(Sabre\DAV\Exception\PreconditionFailed $err) + { + // Event tag not up to date, must be updated first ... + return -1; + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), true, false); + } + return false; + } + + /** + * Make a propFind query to caldav server + * @param string $path absolute or relative URL to Resource + * @param array $props list of properties to use for the query. Properties must have clark-notation. + * @param int $depth 0 means no recurse while 1 means recurse + * @param boolean $log log exception + * @return array + */ + public function prop_find($path, $props, $depth, $log = true) + { + try { + $response = $this->propFind($path, $props, $depth); + } + catch(Sabre\DAV\Exception $err) + { + rcube::raise_error(array( + 'code' => $err->getHTTPCode(), + 'type' => 'DAV', + 'file' => $err->getFile(), + 'line' => $err->getLine(), + 'message' => $err->getMessage() + ), $log, false); + } + return $response; + } + + /** + * Add a caldendar collection + * @param string collection URL + * @parma string displayname + * @param string resource type + * @param string namespace + * @return array response + */ + public function add_collection($url, $displayname, $resourcetype, $namespace) + { + $body = '' . + '' . + ' ' . + ' ' . + ' ' . + ' ' . + ' ' . + ' ' . + ' ' . $displayname . '' . + ' ' . + ' ' . + ' '; + + try { + $response = $this->request('MKCOL', $url, $body, array( + 'Content-Type' => 'application/xml', + 'User-Agent' => $this->user_agent + )); + } + catch(Sabre\DAV\Exception $err) + { + return false; + } + return $response; + } + + /** + * Freebusy request for a given user + * @param string username + * @param path relative path to base uri + * @param integer unix timestamp + * @param integer unix timestamp + * @retrun array List of busy timeslots within the requested range + */ + public function freebusy($user, $path, $start, $end) + { + $body = '' . + '' . + '' . + ''; + return $this->request('REPORT', $path, $body, array( + 'Content-Type' => 'application/xml', + 'Depth' => 1, + 'User-Agent' => $this->user_agent + )); + } +}; +?> diff --git a/libgpl/caldav/caldav_sync.php b/libgpl/caldav/caldav_sync.php new file mode 100644 index 0000000..0266af4 --- /dev/null +++ b/libgpl/caldav/caldav_sync.php @@ -0,0 +1,284 @@ + + * + * Copyright (C) 2013, Awesome IT GbR + * + * 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__) . '/caldav-client.php'); + +class caldav_sync +{ + const ACTION_NONE = 1; + const ACTION_UPDATE = 2; + const ACTION_CREATE = 4; + + private $cal_id = null; + private $ctag = null; + private $user = null; + private $pass = null; + private $url = null; + private $env; + + public $sync = 0; + + /** + * Default constructor for calendar synchronization adapter. + * + * @param int Calendar id. + * @param array Hash array with caldav properties: + * url: Caldav calendar URL. + * user: Caldav http basic auth user. + * pass: Password für caldav user. + * ctag: Caldav ctag for calendar. + * @param boolean verify SSL Cert // Mod by Rosali (https://gitlab.awesome-it.de/kolab/roundcube-plugins/issues/1) + */ + public function __construct($cal_id, $props, $verifySSL, $env) + { + $this->env = $env; + $this->cal_id = $cal_id; + + $this->url = $props["url"]; + $this->ctag = isset($props["tag"]) ? $props["tag"] : null; + $this->user = isset($props["user"]) ? $props["user"] : null; + $this->pass = isset($props["pass"]) ? $props["pass"] : null; + $this->sync = isset($props["sync"]) ? $props["sync"] : 0; + + $this->caldav = new caldav_client($this->url, $this->user, $this->pass, $verifySSL); // Mod by Rosali (https://gitlab.awesome-it.de/kolab/roundcube-plugins/issues/1) + } + + /** + * Getter for current calendar ctag. + * @return string + */ + public function get_ctag() + { + return $this->ctag; + } + + /** + * Determines whether current calendar needs to be synced + * regarding the CalDAV ctag. + * + * @return True if the current calendar ctag differs from the CalDAV tag which + * indicates that there are changes that must be synched. Returns false + * if the calendar is up to date, no sync necesarry. + */ + public function is_synced($force = false) + { + $is_synced = $this->ctag == $this->caldav->get_ctag() && $this->ctag; + $env = $this->env; + $env::debug_log("Ctag indicates that calendar \"$this->cal_id\" ".($is_synced ? "is synced." : "needs update!")); + + return $is_synced; + } + + /** + * Synchronizes given events with caldav server and returns updates. + * + * @param array List of local events. + * @param array List of caldav properties for each event. + * @return array Tuple containing the following lists: + * + * Caldav properties for events to be created or to be updated with the keys: + * url: Event ical URL relative to calendar URL + * etag: Remote etag of the event + * local_event: The local event in case of an update. + * remote_event: The current event retrieved from caldav server. + * + * A list of event ids that are in sync. + */ + public function get_updates($events, $caldav_props) + { + $ctag = $this->caldav->get_ctag(); + + if($ctag) + { + $this->ctag = $ctag; + $etags = $this->caldav->get_etags(); + list($updates, $synced_event_ids) = $this->_get_event_updates($events, $caldav_props, $etags); + return array($this->_get_event_data($updates), $synced_event_ids); + } + else + { + $env = $this->env; + $env::debug_log("Unkown error while fetching calendar ctag for calendar \"$this->cal_id\"!"); + } + + return null; + } + + /** + * Determines sync status and requried updates for the given events using given list of etags. + * + * @param array List of local events. + * @param array List of caldav properties for each event. + * @param array List of current remote etags. + * @return array Tuple containing the following lists: + * + * Caldav properties for events to be created or to be updated with the keys: + * url: Event ical URL relative to calendar URL + * etag: Remote etag of the event + * local_event: The local event in case of an update. + * + * A list of event ids that are in sync. + */ + private function _get_event_updates($events, $caldav_props, $etags) + { + $updates = array(); + $in_sync = array(); + + foreach ($etags as $etag) + { + $url = $etag["url"]; + $etag = $etag["etag"]; + $event_found = false; + for($i = 0; $i < sizeof($events); $i ++) + { + if ($caldav_props[$i]["url"] == $url) + { + $event_found = true; + + if ($caldav_props[$i]["tag"] != $etag) + { + $env = $this->env; + $env::debug_log("Event ".$events[$i]["uid"]." needs update."); + + array_push($updates, array( + "local_event" => $events[$i], + "etag" => $etag, + "url" => $url + )); + } + else + { + array_push($in_sync, $events[$i]["id"]); + } + } + } + + if (!$event_found) + { + $env = $this->env; + $env::debug_log("Found new event ".$url); + + array_push($updates, array( + "url" => $url, + "etag" => $etag + )); + } + } + + return array($updates, $in_sync); + } + + /** + * Fetches event data and attaches it to the given update properties. + * + * @param $updates List of update properties. + * @return array List of update properties with additional key "remote_event" containing the current caldav event. + */ + private function _get_event_data($updates) + { + $urls = array(); + + foreach ($updates as $update) + { + array_push($urls, $update["url"]); + } + + $events = $this->caldav->get_events($urls); + + foreach($updates as &$update) + { + // Attach remote events to the appropriate updates. + // Note that this assumes unique event URL's! + $url = $update["url"]; + if($events[$url]) { + $update["remote_event"] = $events[$url]; + $update["remote_event"]["calendar"] = $this->cal_id; + } + } + + return $updates; + } + + /** + * Creates the given event on the caldav server. + * + * @param array Hash array with event properties. + * @return Caldav properties with created URL on success, false on error. + */ + public function create_event($event) + { + $props = array( + "url" => parse_url($this->url, PHP_URL_PATH)."/".$event["uid"].".ics", + "tag" => null + ); + + $env = $this->env; + $env::debug_log("Push new event to url ".$props["url"]); + $result = $this->caldav->put_event($props["url"], $event); + + if($result == false || $result < 0) return false; + return $props; + } + + /** + * Updates the given event on the caldav server. + * + * @param array Hash array with event properties to update. + * @param array Hash array with caldav properties "url" and "tag" for the event. + * @return True on success, false on error, -1 if the given event/etag is not up to date. + */ + public function update_event($event, $props) + { + $env = $this->env; + $env::debug_log("Updating event uid \"".$event["uid"]."\"."); + return $this->caldav->put_event($props["url"], $event, $props["tag"]); + } + + /** + * Removes the given event from the caldav server. + * + * @param array Hash array with caldav properties "url" and "tag" for the event. + * @return True on success, false on error. + */ + public function remove_event($props) + { + $env = $this->env; + $env::debug_log("Removing event url \"".$props["url"]."\"."); + return $this->caldav->remove_event($props["url"]); + } + + /** + * Freebusy request for a given user. + * + * @param string username + * @param string relative path to caldav base uri + * @param integer unix timestamp + * @param integer unix timestamp + * @retrun array List of busy timeslots within the requested range + */ + public function freebusy($user, $path, $start, $end) + { + return $this->caldav->freebusy($user, $path, $start, $end); + } +}; +?> \ No newline at end of file diff --git a/libgpl/caldav/vobject_sanitize.php b/libgpl/caldav/vobject_sanitize.php new file mode 100644 index 0000000..9db4b41 --- /dev/null +++ b/libgpl/caldav/vobject_sanitize.php @@ -0,0 +1,110 @@ +vobject = $vobject; + $this->properties = (array) $properties; + $this->_unfoald(); + $this->_eol(); + switch($method){ + case 'serialize': + $this->_serialize(); + break; + case 'unserialize': + $this->_unserialize(); + break; + } + } + + private function _unfoald() + { + $data = array(); + $content = explode("\n", $this->vobject); + for($i = 0; $i < count($content); $i++){ + $line = rtrim($content[$i]); + while(isset($content[$i + 1]) && strlen($content[$i + 1]) > 0 && ($content[$i+1]{0} == ' ' || $content[$i + 1]{0} == "\t" )){ + $line .= rtrim(substr($content[++$i], 1)); + } + $data[] = $line; + } + $this->vobject = implode(PHP_EOL, $data); + } + + private function _eol() + { + $this->vobject = preg_replace('/\s\s+/', PHP_EOL, $this->vobject); + } + + private function _serialize() + { + $tokens = array(); + foreach($this->components as $component){ + $regex = '#BEGIN:' . $component . '(?:(?!BEGIN:' . $component . ').)*?END:' . $component . '#si'; + preg_match_all($regex, $this->vobject, $matches); + foreach($matches as $part){ + foreach($part as $match){ + $token = md5($match); + $tokens[$token] = $match; + $this->vobject = str_replace($match, '***' . $token . '***', $this->vobject); + } + } + foreach($tokens as $token => $content){ + foreach($this->properties as $property){ + $content = preg_replace('#' . PHP_EOL . $property . ':#i', PHP_EOL . 'X-ICAL-SANITIZE-' . $property . ':', $content, 1); + $content = preg_replace('#' . PHP_EOL . $property . ':#i', ',', $content); + $content = str_replace(PHP_EOL . 'X-ICAL-SANITIZE-' . $property . ':', PHP_EOL . $property . ':', $content); + $this->vobject = str_replace('***' . $token . '***', $content, $this->vobject); + } + } + } + } + + private function _unserialize() + { + foreach($this->properties as $property){ + preg_match_all('#' . PHP_EOL . $property . '.*:.*,.*' . PHP_EOL . '#i', $this->vobject, $matches); + $content = $this->vobject; + if(is_array($matches)){ + foreach($matches[0] as $match){ + $temp = explode(':', $match, 2); + $field = $temp[0]; + $values = $temp[1]; + $properties = explode(';', $field); + $tz = false; + foreach($properties as $idx => $property){ + if(strtolower(substr($property, 0, 5)) == 'tzid='){ + $temp = explode('=', $property, 2); + $tz = $temp[1]; + unset($properties[$idx]); + } + if(strtolower(substr($property, 0, 6)) == 'value='){ + $temp = explode('=', $property, 2); + $daot = $temp[1]; + } + } + $field = implode(';', $properties); + $values = explode(',', $values); + $line = ''; + foreach($values as $value){ + if($tz){ + $datetime = new DateTime($value, new DateTimeZone($tz)); + if(strtolower($daot) == 'date-time'){ + $ts = $datetime->format('U'); + $value = gmdate('Ymd\THis\Z', $ts); + } + } + $line .= $field . ':' . $value . PHP_EOL; + } + $content = preg_replace('/\s\s+/', PHP_EOL, str_replace($match, $line, $content)); + } + } + $this->vobject = $content; + } + } +} +?> \ No newline at end of file diff --git a/libgpl/contextmenu/jquery.contextMenu.js b/libgpl/contextmenu/jquery.contextMenu.js new file mode 100644 index 0000000..103a585 --- /dev/null +++ b/libgpl/contextmenu/jquery.contextMenu.js @@ -0,0 +1,1686 @@ +/*! + * jQuery contextMenu - Plugin for simple contextMenu handling + * + * Version: git-master + * + * Authors: Rodney Rehm, Addy Osmani (patches for FF) + * Web: http://medialize.github.com/jQuery-contextMenu/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * GPL v3 http://opensource.org/licenses/GPL-3.0 + * + */ + +(function($, undefined){ + + // TODO: - + // ARIA stuff: menuitem, menuitemcheckbox und menuitemradio + // create structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative + +// determine html5 compatibility +$.support.htmlMenuitem = ('HTMLMenuItemElement' in window); +$.support.htmlCommand = ('HTMLCommandElement' in window); +$.support.eventSelectstart = ("onselectstart" in document.documentElement); +/* // should the need arise, test for css user-select +$.support.cssUserSelect = (function(){ + var t = false, + e = document.createElement('div'); + + $.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) { + var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect', + prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select'; + + e.style.cssText = prop + ': text;'; + if (e.style[propCC] == 'text') { + t = true; + return false; + } + + return true; + }); + + return t; +})(); +*/ + +if (!$.ui || !$.ui.widget) { + // duck punch $.cleanData like jQueryUI does to get that remove event + // https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L16-24 + var _cleanData = $.cleanData; + $.cleanData = function( elems ) { + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + try { + $( elem ).triggerHandler( "remove" ); + // http://bugs.jquery.com/ticket/8235 + } catch( e ) {} + } + _cleanData( elems ); + }; +} + +var // currently active contextMenu trigger + $currentTrigger = null, + // is contextMenu initialized with at least one menu? + initialized = false, + // window handle + $win = $(window), + // number of registered menus + counter = 0, + // mapping selector to namespace + namespaces = {}, + // mapping namespace to options + menus = {}, + // custom command type handlers + types = {}, + // default values + defaults = { + // selector of contextMenu trigger + selector: null, + // where to append the menu to + appendTo: null, + // method to trigger context menu ["right", "left", "hover"] + trigger: "right", + // hide menu when mouse leaves trigger / menu elements + autoHide: false, + // ms to wait before showing a hover-triggered context menu + delay: 200, + // flag denoting if a second trigger should simply move (true) or rebuild (false) an open menu + // as long as the trigger happened on one of the trigger-element's child nodes + reposition: true, + // determine position to show menu at + determinePosition: function($menu) { + // position to the lower middle of the trigger element + if ($.ui && $.ui.position) { + // .position() is provided as a jQuery UI utility + // (...and it won't work on hidden elements) + $menu.css('display', 'block').position({ + my: "center top", + at: "center bottom", + of: this, + offset: "0 5", + collision: "fit" + }).css('display', 'none'); + } else { + // determine contextMenu position + var offset = this.offset(); + offset.top += this.outerHeight(); + offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2; + $menu.css(offset); + } + }, + // position menu + position: function(opt, x, y) { + var $this = this, + offset; + // determine contextMenu position + if (!x && !y) { + opt.determinePosition.call(this, opt.$menu); + return; + } else if (x === "maintain" && y === "maintain") { + // x and y must not be changed (after re-show on command click) + offset = opt.$menu.position(); + } else { + // x and y are given (by mouse event) + offset = {top: y, left: x}; + } + + // correct offset if viewport demands it + var bottom = $win.scrollTop() + $win.height(), + right = $win.scrollLeft() + $win.width(), + height = opt.$menu.height(), + width = opt.$menu.width(); + + if (offset.top + height > bottom) { + offset.top -= height; + } + + if (offset.left + width > right) { + offset.left -= width; + } + + opt.$menu.css(offset); + }, + // position the sub-menu + positionSubmenu: function($menu) { + if ($.ui && $.ui.position) { + // .position() is provided as a jQuery UI utility + // (...and it won't work on hidden elements) + $menu.css('display', 'block').position({ + my: "left top", + at: "right top", + of: this, + collision: "flipfit fit" + }).css('display', ''); + } else { + // determine contextMenu position + var offset = { + top: 0, + left: this.outerWidth() + }; + $menu.css(offset); + } + }, + // offset to add to zIndex + zIndex: 1, + // show hide animation settings + animation: { + duration: 50, + show: 'slideDown', + hide: 'slideUp' + }, + // events + events: { + show: $.noop, + hide: $.noop + }, + // default callback + callback: null, + // list of contextMenu items + items: {} + }, + // mouse position for hover activation + hoveract = { + timer: null, + pageX: null, + pageY: null + }, + // determine zIndex + zindex = function($t) { + var zin = 0, + $tt = $t; + + while (true) { + zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0); + $tt = $tt.parent(); + if (!$tt || !$tt.length || "html body".indexOf($tt.prop('nodeName').toLowerCase()) > -1 ) { + break; + } + } + + return zin; + }, + // event handlers + handle = { + // abort anything + abortevent: function(e){ + e.preventDefault(); + e.stopImmediatePropagation(); + }, + + // contextmenu show dispatcher + contextmenu: function(e) { + var $this = $(this); + + // disable actual context-menu + e.preventDefault(); + e.stopImmediatePropagation(); + + // abort native-triggered events unless we're triggering on right click + if (e.data.trigger != 'right' && e.originalEvent) { + return; + } + + // abort event if menu is visible for this trigger + if ($this.hasClass('context-menu-active')) { + return; + } + + if (!$this.hasClass('context-menu-disabled')) { + // theoretically need to fire a show event at + // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus + // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); + // e.data.$menu.trigger(evt); + + $currentTrigger = $this; + if (e.data.build) { + var built = e.data.build($currentTrigger, e); + // abort if build() returned false + if (built === false) { + return; + } + + // dynamically build menu on invocation + e.data = $.extend(true, {}, defaults, e.data, built || {}); + + // abort if there are no items to display + if (!e.data.items || $.isEmptyObject(e.data.items)) { + // Note: jQuery captures and ignores errors from event handlers + if (window.console) { + (console.error || console.log)("No items specified to show in contextMenu"); + } + + throw new Error('No Items specified'); + } + + // backreference for custom command type creation + e.data.$trigger = $currentTrigger; + + op.create(e.data); + } + // show menu + op.show.call($this, e.data, e.pageX, e.pageY); + } + }, + // contextMenu left-click trigger + click: function(e) { + e.preventDefault(); + e.stopImmediatePropagation(); + $(this).trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); + }, + // contextMenu right-click trigger + mousedown: function(e) { + // register mouse down + var $this = $(this); + + // hide any previous menus + if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) { + $currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide'); + } + + // activate on right click + if (e.button == 2) { + $currentTrigger = $this.data('contextMenuActive', true); + } + }, + // contextMenu right-click trigger + mouseup: function(e) { + // show menu + var $this = $(this); + if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) { + e.preventDefault(); + e.stopImmediatePropagation(); + $currentTrigger = $this; + $this.trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY })); + } + + $this.removeData('contextMenuActive'); + }, + // contextMenu hover trigger + mouseenter: function(e) { + var $this = $(this), + $related = $(e.relatedTarget), + $document = $(document); + + // abort if we're coming from a menu + if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { + return; + } + + // abort if a menu is shown + if ($currentTrigger && $currentTrigger.length) { + return; + } + + hoveract.pageX = e.pageX; + hoveract.pageY = e.pageY; + hoveract.data = e.data; + $document.on('mousemove.contextMenuShow', handle.mousemove); + hoveract.timer = setTimeout(function() { + hoveract.timer = null; + $document.off('mousemove.contextMenuShow'); + $currentTrigger = $this; + $this.trigger($.Event("contextmenu", { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY })); + }, e.data.delay ); + }, + // contextMenu hover trigger + mousemove: function(e) { + hoveract.pageX = e.pageX; + hoveract.pageY = e.pageY; + }, + // contextMenu hover trigger + mouseleave: function(e) { + // abort if we're leaving for a menu + var $related = $(e.relatedTarget); + if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { + return; + } + + try { + clearTimeout(hoveract.timer); + } catch(e) {} + + hoveract.timer = null; + }, + + // click on layer to hide contextMenu + layerClick: function(e) { + var $this = $(this), + root = $this.data('contextMenuRoot'), + mouseup = false, + button = e.button, + x = e.pageX, + y = e.pageY, + target, + offset, + selectors; + + e.preventDefault(); + e.stopImmediatePropagation(); + + setTimeout(function() { + var $window, hideshow, possibleTarget; + var triggerAction = ((root.trigger == 'left' && button === 0) || (root.trigger == 'right' && button === 2)); + + // find the element that would've been clicked, wasn't the layer in the way + if (document.elementFromPoint) { + root.$layer.hide(); + target = document.elementFromPoint(x - $win.scrollLeft(), y - $win.scrollTop()); + root.$layer.show(); + } + + if (root.reposition && triggerAction) { + if (document.elementFromPoint) { + if (root.$trigger.is(target) || root.$trigger.has(target).length) { + root.position.call(root.$trigger, root, x, y); + return; + } + } else { + offset = root.$trigger.offset(); + $window = $(window); + // while this looks kinda awful, it's the best way to avoid + // unnecessarily calculating any positions + offset.top += $window.scrollTop(); + if (offset.top <= e.pageY) { + offset.left += $window.scrollLeft(); + if (offset.left <= e.pageX) { + offset.bottom = offset.top + root.$trigger.outerHeight(); + if (offset.bottom >= e.pageY) { + offset.right = offset.left + root.$trigger.outerWidth(); + if (offset.right >= e.pageX) { + // reposition + root.position.call(root.$trigger, root, x, y); + return; + } + } + } + } + } + } + + if (target && triggerAction) { + root.$trigger.one('contextmenu:hidden', function() { + $(target).contextMenu({x: x, y: y}); + }); + } + + root.$menu.trigger('contextmenu:hide'); + }, 50); + }, + // key handled :hover + keyStop: function(e, opt) { + if (!opt.isInput) { + e.preventDefault(); + } + + e.stopPropagation(); + }, + key: function(e) { + var opt = $currentTrigger.data('contextMenu') || {}; + + switch (e.keyCode) { + case 9: + case 38: // up + handle.keyStop(e, opt); + // if keyCode is [38 (up)] or [9 (tab) with shift] + if (opt.isInput) { + if (e.keyCode == 9 && e.shiftKey) { + e.preventDefault(); + opt.$selected && opt.$selected.find('input, textarea, select').blur(); + opt.$menu.trigger('prevcommand'); + return; + } else if (e.keyCode == 38 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { + // checkboxes don't capture this key + e.preventDefault(); + return; + } + } else if (e.keyCode != 9 || e.shiftKey) { + opt.$menu.trigger('prevcommand'); + return; + } + // omitting break; + + // case 9: // tab - reached through omitted break; + case 40: // down + handle.keyStop(e, opt); + if (opt.isInput) { + if (e.keyCode == 9) { + e.preventDefault(); + opt.$selected && opt.$selected.find('input, textarea, select').blur(); + opt.$menu.trigger('nextcommand'); + return; + } else if (e.keyCode == 40 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') { + // checkboxes don't capture this key + e.preventDefault(); + return; + } + } else { + opt.$menu.trigger('nextcommand'); + return; + } + break; + + case 37: // left + handle.keyStop(e, opt); + if (opt.isInput || !opt.$selected || !opt.$selected.length) { + break; + } + + if (!opt.$selected.parent().hasClass('context-menu-root')) { + var $parent = opt.$selected.parent().parent(); + opt.$selected.trigger('contextmenu:blur'); + opt.$selected = $parent; + return; + } + break; + + case 39: // right + handle.keyStop(e, opt); + if (opt.isInput || !opt.$selected || !opt.$selected.length) { + break; + } + + var itemdata = opt.$selected.data('contextMenu') || {}; + if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) { + opt.$selected = null; + itemdata.$selected = null; + itemdata.$menu.trigger('nextcommand'); + return; + } + break; + + case 35: // end + case 36: // home + if (opt.$selected && opt.$selected.find('input, textarea, select').length) { + return; + } else { + (opt.$selected && opt.$selected.parent() || opt.$menu) + .children(':not(.disabled, .not-selectable)')[e.keyCode == 36 ? 'first' : 'last']() + .trigger('contextmenu:focus'); + e.preventDefault(); + return; + } + break; + + case 13: // enter + handle.keyStop(e, opt); + if (opt.isInput) { + if (opt.$selected && !opt.$selected.is('textarea, select')) { + e.preventDefault(); + return; + } + break; + } + opt.$selected && opt.$selected.trigger('mouseup'); + return; + + case 32: // space + case 33: // page up + case 34: // page down + // prevent browser from scrolling down while menu is visible + handle.keyStop(e, opt); + return; + + case 27: // esc + handle.keyStop(e, opt); + opt.$menu.trigger('contextmenu:hide'); + return; + + default: // 0-9, a-z + var k = (String.fromCharCode(e.keyCode)).toUpperCase(); + if (opt.accesskeys[k]) { + // according to the specs accesskeys must be invoked immediately + opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu + ? 'contextmenu:focus' + : 'mouseup' + ); + return; + } + break; + } + // pass event to selected item, + // stop propagation to avoid endless recursion + e.stopPropagation(); + opt.$selected && opt.$selected.trigger(e); + }, + + // select previous possible command in menu + prevItem: function(e) { + e.stopPropagation(); + var opt = $(this).data('contextMenu') || {}; + + // obtain currently selected menu + if (opt.$selected) { + var $s = opt.$selected; + opt = opt.$selected.parent().data('contextMenu') || {}; + opt.$selected = $s; + } + + var $children = opt.$menu.children(), + $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(), + $round = $prev; + + // skip disabled + while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) { + if ($prev.prev().length) { + $prev = $prev.prev(); + } else { + $prev = $children.last(); + } + if ($prev.is($round)) { + // break endless loop + return; + } + } + + // leave current + if (opt.$selected) { + handle.itemMouseleave.call(opt.$selected.get(0), e); + } + + // activate next + handle.itemMouseenter.call($prev.get(0), e); + + // focus input + var $input = $prev.find('input, textarea, select'); + if ($input.length) { + $input.focus(); + } + }, + // select next possible command in menu + nextItem: function(e) { + e.stopPropagation(); + var opt = $(this).data('contextMenu') || {}; + + // obtain currently selected menu + if (opt.$selected) { + var $s = opt.$selected; + opt = opt.$selected.parent().data('contextMenu') || {}; + opt.$selected = $s; + } + + var $children = opt.$menu.children(), + $next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(), + $round = $next; + + // skip disabled + while ($next.hasClass('disabled') || $next.hasClass('not-selectable')) { + if ($next.next().length) { + $next = $next.next(); + } else { + $next = $children.first(); + } + if ($next.is($round)) { + // break endless loop + return; + } + } + + // leave current + if (opt.$selected) { + handle.itemMouseleave.call(opt.$selected.get(0), e); + } + + // activate next + handle.itemMouseenter.call($next.get(0), e); + + // focus input + var $input = $next.find('input, textarea, select'); + if ($input.length) { + $input.focus(); + } + }, + + // flag that we're inside an input so the key handler can act accordingly + focusInput: function(e) { + var $this = $(this).closest('.context-menu-item'), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + root.$selected = opt.$selected = $this; + root.isInput = opt.isInput = true; + }, + // flag that we're inside an input so the key handler can act accordingly + blurInput: function(e) { + var $this = $(this).closest('.context-menu-item'), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + root.isInput = opt.isInput = false; + }, + + // :hover on menu + menuMouseenter: function(e) { + var root = $(this).data().contextMenuRoot; + root.hovering = true; + }, + // :hover on menu + menuMouseleave: function(e) { + var root = $(this).data().contextMenuRoot; + if (root.$layer && root.$layer.is(e.relatedTarget)) { + root.hovering = false; + } + }, + + // :hover done manually so key handling is possible + itemMouseenter: function(e) { + var $this = $(this), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + root.hovering = true; + + // abort if we're re-entering + if (e && root.$layer && root.$layer.is(e.relatedTarget)) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + + // make sure only one item is selected + (opt.$menu ? opt : root).$menu + .children('.hover').trigger('contextmenu:blur'); + + if ($this.hasClass('disabled') || $this.hasClass('not-selectable')) { + opt.$selected = null; + return; + } + + $this.trigger('contextmenu:focus'); + }, + // :hover done manually so key handling is possible + itemMouseleave: function(e) { + var $this = $(this), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) { + root.$selected && root.$selected.trigger('contextmenu:blur'); + e.preventDefault(); + e.stopImmediatePropagation(); + root.$selected = opt.$selected = opt.$node; + return; + } + + $this.trigger('contextmenu:blur'); + }, + // contextMenu item click + itemClick: function(e) { + var $this = $(this), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot, + key = data.contextMenuKey, + callback; + + // abort if the key is unknown or disabled or is a menu + if (!opt.items[key] || $this.is('.disabled, .context-menu-submenu, .context-menu-separator, .not-selectable')) { + return; + } + + e.preventDefault(); + e.stopImmediatePropagation(); + + if ($.isFunction(root.callbacks[key]) && Object.prototype.hasOwnProperty.call(root.callbacks, key)) { + // item-specific callback + callback = root.callbacks[key]; + } else if ($.isFunction(root.callback)) { + // default callback + callback = root.callback; + } else { + // no callback, no action + return; + } + + // hide menu if callback doesn't stop that + if (callback.call(root.$trigger, key, root) !== false) { + root.$menu.trigger('contextmenu:hide'); + } else if (root.$menu.parent().length) { + op.update.call(root.$trigger, root); + } + }, + // ignore click events on input elements + inputClick: function(e) { + e.stopImmediatePropagation(); + }, + + // hide + hideMenu: function(e, data) { + var root = $(this).data('contextMenuRoot'); + op.hide.call(root.$trigger, root, data && data.force); + }, + // focus + focusItem: function(e) { + e.stopPropagation(); + var $this = $(this), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + $this.addClass('hover') + .siblings('.hover').trigger('contextmenu:blur'); + + // remember selected + opt.$selected = root.$selected = $this; + + // position sub-menu - do after show so dumb $.ui.position can keep up + if (opt.$node) { + root.positionSubmenu.call(opt.$node, opt.$menu); + } + }, + // blur + blurItem: function(e) { + e.stopPropagation(); + var $this = $(this), + data = $this.data(), + opt = data.contextMenu, + root = data.contextMenuRoot; + + $this.removeClass('hover'); + opt.$selected = null; + } + }, + // operations + op = { + show: function(opt, x, y) { + var $trigger = $(this), + offset, + css = {}; + + // hide any open menus + $('#context-menu-layer').trigger('mousedown'); + + // backreference for callbacks + opt.$trigger = $trigger; + + // show event + if (opt.events.show.call($trigger, opt) === false) { + $currentTrigger = null; + return; + } + + // create or update context menu + op.update.call($trigger, opt); + + // position menu + opt.position.call($trigger, opt, x, y); + + // make sure we're in front + if (opt.zIndex) { + css.zIndex = zindex($trigger) + opt.zIndex; + } + + // add layer + op.layer.call(opt.$menu, opt, css.zIndex); + + // adjust sub-menu zIndexes + opt.$menu.find('ul').css('zIndex', css.zIndex + 1); + + // position and show context menu + opt.$menu.css( css )[opt.animation.show](opt.animation.duration, function() { + $trigger.trigger('contextmenu:visible'); + }); + // make options available and set state + $trigger + .data('contextMenu', opt) + .addClass("context-menu-active"); + + // register key handler + $(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key); + // register autoHide handler + if (opt.autoHide) { + // mouse position handler + $(document).on('mousemove.contextMenuAutoHide', function(e) { + // need to capture the offset on mousemove, + // since the page might've been scrolled since activation + var pos = $trigger.offset(); + pos.right = pos.left + $trigger.outerWidth(); + pos.bottom = pos.top + $trigger.outerHeight(); + + if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) { + // if mouse in menu... + opt.$menu.trigger('contextmenu:hide'); + } + }); + } + }, + hide: function(opt, force) { + var $trigger = $(this); + if (!opt) { + opt = $trigger.data('contextMenu') || {}; + } + + // hide event + if (!force && opt.events && opt.events.hide.call($trigger, opt) === false) { + return; + } + + // remove options and revert state + $trigger + .removeData('contextMenu') + .removeClass("context-menu-active"); + + if (opt.$layer) { + // keep layer for a bit so the contextmenu event can be aborted properly by opera + setTimeout((function($layer) { + return function(){ + $layer.remove(); + }; + })(opt.$layer), 10); + + try { + delete opt.$layer; + } catch(e) { + opt.$layer = null; + } + } + + // remove handle + $currentTrigger = null; + // remove selected + opt.$menu.find('.hover').trigger('contextmenu:blur'); + opt.$selected = null; + // unregister key and mouse handlers + //$(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705 + $(document).off('.contextMenuAutoHide').off('keydown.contextMenu'); + // hide menu + opt.$menu && opt.$menu[opt.animation.hide](opt.animation.duration, function (){ + // tear down dynamically built menu after animation is completed. + if (opt.build) { + opt.$menu.remove(); + $.each(opt, function(key, value) { + switch (key) { + case 'ns': + case 'selector': + case 'build': + case 'trigger': + return true; + + default: + opt[key] = undefined; + try { + delete opt[key]; + } catch (e) {} + return true; + } + }); + } + + setTimeout(function() { + $trigger.trigger('contextmenu:hidden'); + }, 10); + }); + }, + create: function(opt, root) { + if (root === undefined) { + root = opt; + } + // create contextMenu + opt.$menu = $('
    ').addClass(opt.className || "").data({ + 'contextMenu': opt, + 'contextMenuRoot': root + }); + + $.each(['callbacks', 'commands', 'inputs'], function(i,k){ + opt[k] = {}; + if (!root[k]) { + root[k] = {}; + } + }); + + root.accesskeys || (root.accesskeys = {}); + + // create contextMenu items + $.each(opt.items, function(key, item){ + var $t = $('
  • ').addClass(item.className || ""), + $label = null, + $input = null; + + // iOS needs to see a click-event bound to an element to actually + // have the TouchEvents infrastructure trigger the click event + $t.on('click', $.noop); + + item.$node = $t.data({ + 'contextMenu': opt, + 'contextMenuRoot': root, + 'contextMenuKey': key + }); + + // register accesskey + // NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that + if (item.accesskey) { + var aks = splitAccesskey(item.accesskey); + for (var i=0, ak; ak = aks[i]; i++) { + if (!root.accesskeys[ak]) { + root.accesskeys[ak] = item; + item._name = item.name.replace(new RegExp('(' + ak + ')', 'i'), '$1'); + break; + } + } + } + + if (typeof item == "string") { + $t.addClass('context-menu-separator not-selectable'); + } else if (item.type && types[item.type]) { + // run custom type handler + types[item.type].call($t, item, opt, root); + // register commands + $.each([opt, root], function(i,k){ + k.commands[key] = item; + if ($.isFunction(item.callback)) { + k.callbacks[key] = item.callback; + } + }); + } else { + // add label for input + if (item.type == 'html') { + $t.addClass('context-menu-html not-selectable'); + } else if (item.type) { + $label = $('').appendTo($t); + $('').html(item._name || item.name).appendTo($label); + $t.addClass('context-menu-input'); + opt.hasTypes = true; + $.each([opt, root], function(i,k){ + k.commands[key] = item; + k.inputs[key] = item; + }); + } else if (item.items) { + item.type = 'sub'; + } + + switch (item.type) { + case 'text': + $input = $('') + .attr('name', 'context-menu-input-' + key) + .val(item.value || "") + .appendTo($label); + break; + + case 'textarea': + $input = $('') + .attr('name', 'context-menu-input-' + key) + .val(item.value || "") + .appendTo($label); + + if (item.height) { + $input.height(item.height); + } + break; + + case 'checkbox': + $input = $('') + .attr('name', 'context-menu-input-' + key) + .val(item.value || "") + .prop("checked", !!item.selected) + .prependTo($label); + break; + + case 'radio': + $input = $('') + .attr('name', 'context-menu-input-' + item.radio) + .val(item.value || "") + .prop("checked", !!item.selected) + .prependTo($label); + break; + + case 'select': + $input = $(' + if (item.type && item.type != 'sub' && item.type != 'html') { + $input + .on('focus', handle.focusInput) + .on('blur', handle.blurInput); + + if (item.events) { + $input.on(item.events, opt); + } + } + + // add icons + if (item.icon) { + $t.addClass("icon icon-" + item.icon); + } + } + + // cache contained elements + item.$input = $input; + item.$label = $label; + + // attach item to menu + $t.appendTo(opt.$menu); + + // Disable text selection + if (!opt.hasTypes && $.support.eventSelectstart) { + // browsers support user-select: none, + // IE has a special event for text-selection + // browsers supporting neither will not be preventing text-selection + $t.on('selectstart.disableTextSelect', handle.abortevent); + } + }); + // attach contextMenu to (to bypass any possible overflow:hidden issues on parents of the trigger element) + if (!opt.$node) { + opt.$menu.css('display', 'none').addClass('context-menu-root'); + } + opt.$menu.appendTo(opt.appendTo || document.body); + }, + resize: function($menu, nested) { + // determine widths of submenus, as CSS won't grow them automatically + // position:absolute within position:absolute; min-width:100; max-width:200; results in width: 100; + // kinda sucks hard... + + // determine width of absolutely positioned element + $menu.css({position: 'absolute', display: 'block'}); + // don't apply yet, because that would break nested elements' widths + // add a pixel to circumvent word-break issue in IE9 - #80 + $menu.data('width', Math.ceil($menu.width()) + 1); + // reset styles so they allow nested elements to grow/shrink naturally + $menu.css({ + position: 'static', + minWidth: '0px', + maxWidth: '100000px' + }); + // identify width of nested menus + $menu.find('> li > ul').each(function() { + op.resize($(this), true); + }); + // reset and apply changes in the end because nested + // elements' widths wouldn't be calculatable otherwise + if (!nested) { + $menu.find('ul').andSelf().css({ + position: '', + display: '', + minWidth: '', + maxWidth: '' + }).width(function() { + return $(this).data('width'); + }); + } + }, + update: function(opt, root) { + var $trigger = this; + if (root === undefined) { + root = opt; + op.resize(opt.$menu); + } + // re-check disabled for each item + opt.$menu.children().each(function(){ + var $item = $(this), + key = $item.data('contextMenuKey'), + item = opt.items[key], + disabled = ($.isFunction(item.disabled) && item.disabled.call($trigger, key, root)) || item.disabled === true; + + // dis- / enable item + $item[disabled ? 'addClass' : 'removeClass']('disabled'); + + if (item.type) { + // dis- / enable input elements + $item.find('input, select, textarea').prop('disabled', disabled); + + // update input states + switch (item.type) { + case 'text': + case 'textarea': + item.$input.val(item.value || ""); + break; + + case 'checkbox': + case 'radio': + item.$input.val(item.value || "").prop('checked', !!item.selected); + break; + + case 'select': + item.$input.val(item.selected || ""); + break; + } + } + + if (item.$menu) { + // update sub-menu + op.update.call($trigger, item, root); + } + }); + }, + layer: function(opt, zIndex) { + // add transparent layer for click area + // filter and background for Internet Explorer, Issue #23 + var $layer = opt.$layer = $('
    ') + .css({height: $win.height(), width: $win.width(), display: 'block'}) + .data('contextMenuRoot', opt) + .insertBefore(this) + .on('contextmenu', handle.abortevent) + .on('mousedown', handle.layerClick); + + // IE6 doesn't know position:fixed; + if (!$.support.fixedPosition) { + $layer.css({ + 'position' : 'absolute', + 'height' : $(document).height() + }); + } + + return $layer; + } + }; + +// split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key +function splitAccesskey(val) { + var t = val.split(/\s+/), + keys = []; + + for (var i=0, k; k = t[i]; i++) { + k = k[0].toUpperCase(); // first character only + // theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it. + // a map to look up already used access keys would be nice + keys.push(k); + } + + return keys; +} + +// handle contextMenu triggers +$.fn.contextMenu = function(operation) { + if (operation === undefined) { + this.first().trigger('contextmenu'); + } else if (operation.x && operation.y) { + this.first().trigger($.Event("contextmenu", {pageX: operation.x, pageY: operation.y})); + } else if (operation === "hide") { + var $menu = this.data('contextMenu').$menu; + $menu && $menu.trigger('contextmenu:hide'); + } else if (operation === "destroy") { + $.contextMenu("destroy", {context: this}); + } else if ($.isPlainObject(operation)) { + operation.context = this; + $.contextMenu("create", operation); + } else if (operation) { + this.removeClass('context-menu-disabled'); + } else if (!operation) { + this.addClass('context-menu-disabled'); + } + + return this; +}; + +// manage contextMenu instances +$.contextMenu = function(operation, options) { + if (typeof operation != 'string') { + options = operation; + operation = 'create'; + } + + if (typeof options == 'string') { + options = {selector: options}; + } else if (options === undefined) { + options = {}; + } + + // merge with default options + var o = $.extend(true, {}, defaults, options || {}); + var $document = $(document); + var $context = $document; + var _hasContext = false; + + if (!o.context || !o.context.length) { + o.context = document; + } else { + // you never know what they throw at you... + $context = $(o.context).first(); + o.context = $context.get(0); + _hasContext = o.context !== document; + } + + switch (operation) { + case 'create': + // no selector no joy + if (!o.selector) { + throw new Error('No selector specified'); + } + // make sure internal classes are not bound to + if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) { + throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className'); + } + if (!o.build && (!o.items || $.isEmptyObject(o.items))) { + throw new Error('No Items specified'); + } + counter ++; + o.ns = '.contextMenu' + counter; + if (!_hasContext) { + namespaces[o.selector] = o.ns; + } + menus[o.ns] = o; + + // default to right click + if (!o.trigger) { + o.trigger = 'right'; + } + + if (!initialized) { + // make sure item click is registered first + $document + .on({ + 'contextmenu:hide.contextMenu': handle.hideMenu, + 'prevcommand.contextMenu': handle.prevItem, + 'nextcommand.contextMenu': handle.nextItem, + 'contextmenu.contextMenu': handle.abortevent, + 'mouseenter.contextMenu': handle.menuMouseenter, + 'mouseleave.contextMenu': handle.menuMouseleave + }, '.context-menu-list') + .on('mouseup.contextMenu', '.context-menu-input', handle.inputClick) + .on({ + 'mouseup.contextMenu': handle.itemClick, + 'contextmenu:focus.contextMenu': handle.focusItem, + 'contextmenu:blur.contextMenu': handle.blurItem, + 'contextmenu.contextMenu': handle.abortevent, + 'mouseenter.contextMenu': handle.itemMouseenter, + 'mouseleave.contextMenu': handle.itemMouseleave + }, '.context-menu-item'); + + initialized = true; + } + + // engage native contextmenu event + $context + .on('contextmenu' + o.ns, o.selector, o, handle.contextmenu); + + if (_hasContext) { + // add remove hook, just in case + $context.on('remove' + o.ns, function() { + $(this).contextMenu("destroy"); + }); + } + + switch (o.trigger) { + case 'hover': + $context + .on('mouseenter' + o.ns, o.selector, o, handle.mouseenter) + .on('mouseleave' + o.ns, o.selector, o, handle.mouseleave); + break; + + case 'left': + $context.on('click' + o.ns, o.selector, o, handle.click); + break; + /* + default: + // http://www.quirksmode.org/dom/events/contextmenu.html + $document + .on('mousedown' + o.ns, o.selector, o, handle.mousedown) + .on('mouseup' + o.ns, o.selector, o, handle.mouseup); + break; + */ + } + + // create menu + if (!o.build) { + op.create(o); + } + break; + + case 'destroy': + var $visibleMenu; + if (_hasContext) { + // get proper options + var context = o.context; + $.each(menus, function(ns, o) { + if (o.context !== context) { + return true; + } + + $visibleMenu = $('.context-menu-list').filter(':visible'); + if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is($(o.context).find(o.selector))) { + $visibleMenu.trigger('contextmenu:hide', {force: true}); + } + + try { + if (menus[o.ns].$menu) { + menus[o.ns].$menu.remove(); + } + + delete menus[o.ns]; + } catch(e) { + menus[o.ns] = null; + } + + $(o.context).off(o.ns); + + return true; + }); + } else if (!o.selector) { + $document.off('.contextMenu .contextMenuAutoHide'); + $.each(menus, function(ns, o) { + $(o.context).off(o.ns); + }); + + namespaces = {}; + menus = {}; + counter = 0; + initialized = false; + + $('#context-menu-layer, .context-menu-list').remove(); + } else if (namespaces[o.selector]) { + $visibleMenu = $('.context-menu-list').filter(':visible'); + if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) { + $visibleMenu.trigger('contextmenu:hide', {force: true}); + } + + try { + if (menus[namespaces[o.selector]].$menu) { + menus[namespaces[o.selector]].$menu.remove(); + } + + delete menus[namespaces[o.selector]]; + } catch(e) { + menus[namespaces[o.selector]] = null; + } + + $document.off(namespaces[o.selector]); + } + break; + + case 'html5': + // if or are not handled by the browser, + // or options was a bool true, + // initialize $.contextMenu for them + if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options == "boolean" && options)) { + $('menu[type="context"]').each(function() { + if (this.id) { + $.contextMenu({ + selector: '[contextmenu=' + this.id +']', + items: $.contextMenu.fromMenu(this) + }); + } + }).css('display', 'none'); + } + break; + + default: + throw new Error('Unknown operation "' + operation + '"'); + } + + return this; +}; + +// import values into commands +$.contextMenu.setInputValues = function(opt, data) { + if (data === undefined) { + data = {}; + } + + $.each(opt.inputs, function(key, item) { + switch (item.type) { + case 'text': + case 'textarea': + item.value = data[key] || ""; + break; + + case 'checkbox': + item.selected = data[key] ? true : false; + break; + + case 'radio': + item.selected = (data[item.radio] || "") == item.value ? true : false; + break; + + case 'select': + item.selected = data[key] || ""; + break; + } + }); +}; + +// export values from commands +$.contextMenu.getInputValues = function(opt, data) { + if (data === undefined) { + data = {}; + } + + $.each(opt.inputs, function(key, item) { + switch (item.type) { + case 'text': + case 'textarea': + case 'select': + data[key] = item.$input.val(); + break; + + case 'checkbox': + data[key] = item.$input.prop('checked'); + break; + + case 'radio': + if (item.$input.prop('checked')) { + data[item.radio] = item.value; + } + break; + } + }); + + return data; +}; + +// find