From 217151eb9c2da9ab6ef0c5a3df1e5e1e4f8abd9a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 11:50:45 +0100 Subject: [PATCH 001/430] add textfield style declaration --- core/css/styles.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/css/styles.css b/core/css/styles.css index 53af8b383e3..afab1fc4cdb 100644 --- a/core/css/styles.css +++ b/core/css/styles.css @@ -32,7 +32,7 @@ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#35537a', end /* INPUTS */ input[type="text"], input[type="password"] { cursor:text; } -input, select, button, .button, #quota, div.jp-progress, .pager li a { font-size:1em; width:10em; margin:.3em; padding:.6em .5em .4em; background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #fff, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; } +input, textarea, select, button, .button, #quota, div.jp-progress, .pager li a { font-size:1em; width:10em; margin:.3em; padding:.6em .5em .4em; background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #fff, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; } input[type="text"], input[type="password"], input[type="search"] { background:#f8f8f8; color:#555; cursor:text; } input[type="text"], input[type="password"], input[type="search"] { -webkit-appearance:textfield; -moz-appearance:textfield; -webkit-box-sizing:content-box; -moz-box-sizing:content-box; box-sizing:content-box; } input[type="text"]:hover, input[type="text"]:focus, input[type="text"]:active, -- GitLab From fc70c7094a32be06329e1674339a4d6d7329db65 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 11:57:09 +0100 Subject: [PATCH 002/430] add tabs for repeating and attendees in the event form --- apps/calendar/js/calendar.js | 1 + apps/calendar/templates/part.eventform.php | 50 +++++++++++++--------- 2 files changed, 31 insertions(+), 20 deletions(-) diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index afd1b692dd4..6b24fbc2f9c 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -52,6 +52,7 @@ Calendar={ $('#advanced_month').change(function(){ Calendar.UI.repeat('month'); }); + $( "#event" ).tabs({ selected: 0}); $('#event').dialog({ width : 500, close : function(event, ui) { diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index 1f2073f4bc7..fc81ebc1758 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -1,3 +1,9 @@ + +
@@ -56,7 +62,27 @@
t("Title");?>:
" onclick="Calendar.UI.showadvancedoptions();" id="advanced_options_button"> +
+
+
t("Repeat");?>: @@ -200,23 +226,7 @@
+ t('Summary'); ?>:
-
- - - - - - -
t("Location");?>: - " value="" maxlength="100" name="location" /> -
- - - - - -
t("Description");?>: - -
- + +
\ No newline at end of file -- GitLab From 4c1fb4c2823a55bb4039484e2d8b270ee83e9cac Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 16:49:21 +0100 Subject: [PATCH 003/430] fix style of the tabs --- apps/calendar/css/style.css | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/calendar/css/style.css b/apps/calendar/css/style.css index cffaf356402..1701a36a1f9 100644 --- a/apps/calendar/css/style.css +++ b/apps/calendar/css/style.css @@ -56,6 +56,8 @@ button.category{margin:0 3px;} .calendar-colorpicker-color{display:inline-block;width:20px;height:20px;margin-right:2px;cursor:pointer;border:2px solid transparent;} .calendar-colorpicker-color.active{border:2px solid black;} +#event {padding: 0;margin: 0;margin-top:-5px} + .fc-list-table { margin: 10px; -- GitLab From c72c4dd41282c23f5c4ea2a9c3a7cbe2876f894b Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 16:59:34 +0100 Subject: [PATCH 004/430] add alarm as a tab --- apps/calendar/templates/part.eventform.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index fc81ebc1758..fa588f75e23 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -2,6 +2,7 @@
  • Eventinfo
  • Repeating
  • Attendees
  • +
  • Alarm
  • @@ -229,4 +230,5 @@ t('Summary'); ?>: -
    \ No newline at end of file +
    +
    \ No newline at end of file -- GitLab From 149bbeb260aa0f2b2b762e0722bbf23b4cff0680 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 17:15:25 +0100 Subject: [PATCH 005/430] make tab names translatable --- apps/calendar/templates/part.eventform.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index fa588f75e23..217199fca2e 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -1,8 +1,8 @@
    -- GitLab From 64a617b2a1016108c946cc533875a40030bbd317 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 20:46:27 +0100 Subject: [PATCH 006/430] fix all day with one day to much - bugfix for oc-126 --- apps/calendar/ajax/events.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 998991c2fb4..73bdfcc270b 100644 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -39,13 +39,13 @@ foreach($events as $event){ $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); $return_event = array(); $start_dt = $dtstart->getDateTime(); - $start_dt->setTimezone(new DateTimeZone($user_timezone)); $end_dt = $dtend->getDateTime(); - $end_dt->setTimezone(new DateTimeZone($user_timezone)); if ($dtstart->getDateType() == Sabre_VObject_Element_DateTime::DATE){ $return_event['allDay'] = true; }else{ $return_event['allDay'] = false; + $start_dt->setTimezone(new DateTimeZone($user_timezone)); + $end_dt->setTimezone(new DateTimeZone($user_timezone)); } //Repeating Events if($event['repeating'] == 1){ -- GitLab From 32bff22dc7bf46df33b4d9d7e3a4791d21639ea8 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 21:26:09 +0100 Subject: [PATCH 007/430] change db structure of calendar for sharing calendars --- apps/calendar/appinfo/database.xml | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/apps/calendar/appinfo/database.xml b/apps/calendar/appinfo/database.xml index 7f7b6457559..5ae4dafd39d 100644 --- a/apps/calendar/appinfo/database.xml +++ b/apps/calendar/appinfo/database.xml @@ -187,5 +187,99 @@
    + + + + *dbprefix*calendar_share_event + + + + + owner + text + true + 255 + + + + share + text + true + 255 + + + + sharetype + text + true + 5 + + + + eventid + integer + + true + true + 11 + + + + permissions + integer + true + 1 + + + + +
    + + + + *dbprefix*calendar_share_calendar + + + + + owner + text + true + 255 + + + + share + text + true + 255 + + + + sharetype + text + true + 5 + + + + calendarid + integer + + true + true + 11 + + + permissions + integer + true + 1 + + + + +
    + -- GitLab From 3a5d3dfd9720ab503c0c86208d3484833bf88fd2 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 21:33:50 +0100 Subject: [PATCH 008/430] increase version number to force db upgrade --- apps/calendar/appinfo/info.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/calendar/appinfo/info.xml b/apps/calendar/appinfo/info.xml index 46292af3db1..c38861e1589 100644 --- a/apps/calendar/appinfo/info.xml +++ b/apps/calendar/appinfo/info.xml @@ -2,7 +2,7 @@ calendar Calendar - 0.2 + 0.3 AGPL Georg Ehrke, Bart Visscher, Jakob Sack 2 -- GitLab From 153467dbe0db215582a745359d824fb9cf94fad5 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 21:39:40 +0100 Subject: [PATCH 009/430] add share as a tab --- apps/calendar/templates/part.eventform.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index 217199fca2e..1b7aa1acb4c 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -1,8 +1,9 @@
    @@ -231,4 +232,5 @@
    -
    \ No newline at end of file +
    +
    \ No newline at end of file -- GitLab From 2b8ec1cad048e6ae9a72710d1532a3da23f9b456 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 31 Jan 2012 22:03:08 +0100 Subject: [PATCH 010/430] Calendar: fix html of import dialog --- apps/calendar/templates/part.import.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/templates/part.import.php b/apps/calendar/templates/part.import.php index 8f46484b42b..90691a33e50 100644 --- a/apps/calendar/templates/part.import.php +++ b/apps/calendar/templates/part.import.php @@ -3,7 +3,7 @@ -

    t('Please choose the calendar'); ?> +

    t('Please choose the calendar'); ?>

    -- GitLab From f870f9efcf36a3c7e839b8c37195d94bfa92d6fe Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 2 Feb 2012 12:18:29 +0100 Subject: [PATCH 012/430] validate parameters in changeview.php --- apps/calendar/ajax/changeview.php | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/apps/calendar/ajax/changeview.php b/apps/calendar/ajax/changeview.php index ef05c7cd496..df3e2827b7e 100644 --- a/apps/calendar/ajax/changeview.php +++ b/apps/calendar/ajax/changeview.php @@ -1,15 +1,24 @@ + * Copyright (c) 2012 Georg Ehrke * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ -require_once ("../../../lib/base.php"); +require_once ('../../../lib/base.php'); OC_JSON::checkLoggedIn(); OC_JSON::checkAppEnabled('calendar'); -$currentview = $_GET["v"]; -OC_Preferences::setValue(OC_USER::getUser(), "calendar", "currentview", $currentview); +$currentview = $_GET['v']; +switch($currentview){ + case 'agendaWeek': + case 'month'; + case 'list': + break; + default: + OC_JSON::error(); + exit; +} +OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'currentview', $currentview); OC_JSON::success(); -?> +?> \ No newline at end of file -- GitLab From 91b705cc4febce2675d31b520c52bf9c39f13554 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 2 Feb 2012 12:37:58 +0100 Subject: [PATCH 013/430] remove debug file --- apps/calendar/resettimezone.php | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 apps/calendar/resettimezone.php diff --git a/apps/calendar/resettimezone.php b/apps/calendar/resettimezone.php deleted file mode 100644 index 1ef9591ae39..00000000000 --- a/apps/calendar/resettimezone.php +++ /dev/null @@ -1,4 +0,0 @@ - \ No newline at end of file -- GitLab From b810380d56b41ebad4fd67a30d6789744c69deb3 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 4 Feb 2012 21:23:31 +0100 Subject: [PATCH 014/430] add sharing management for calendars --- apps/calendar/ajax/changepermission.php | 40 +++++ apps/calendar/ajax/share.dropdown.php | 18 ++ apps/calendar/ajax/share.php | 51 ++++++ apps/calendar/ajax/unshare.php | 44 +++++ apps/calendar/appinfo/app.php | 3 + apps/calendar/appinfo/database.xml | 4 +- apps/calendar/css/style.css | 4 + apps/calendar/js/calendar.js | 103 ++++++++++- apps/calendar/lib/share.php | 163 ++++++++++++++++++ apps/calendar/share.php | 1 + .../templates/part.choosecalendar.php | 23 ++- .../part.choosecalendar.rowfields.php | 10 +- .../part.choosecalendar.rowfields.shared.php | 4 + apps/calendar/templates/part.eventform.php | 6 +- apps/calendar/templates/share.dropdown.php | 71 ++++++++ 15 files changed, 535 insertions(+), 10 deletions(-) create mode 100644 apps/calendar/ajax/changepermission.php create mode 100644 apps/calendar/ajax/share.dropdown.php create mode 100644 apps/calendar/ajax/share.php create mode 100644 apps/calendar/ajax/unshare.php create mode 100644 apps/calendar/lib/share.php create mode 100644 apps/calendar/share.php create mode 100644 apps/calendar/templates/part.choosecalendar.rowfields.shared.php create mode 100644 apps/calendar/templates/share.dropdown.php diff --git a/apps/calendar/ajax/changepermission.php b/apps/calendar/ajax/changepermission.php new file mode 100644 index 00000000000..caee894521c --- /dev/null +++ b/apps/calendar/ajax/changepermission.php @@ -0,0 +1,40 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +$permission = (int) strip_tags($_GET['permission']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +$success = OC_Calendar_Share::changepermission($sharewith, $sharetype, $id, $permission, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/ajax/share.dropdown.php b/apps/calendar/ajax/share.dropdown.php new file mode 100644 index 00000000000..7e78521a76b --- /dev/null +++ b/apps/calendar/ajax/share.dropdown.php @@ -0,0 +1,18 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../lib/base.php'); +$user = OC_USER::getUser(); +$calid = $_GET['calid']; +$calendar = OC_Calendar_Calendar::find($calid); +if($calendar['userid'] != $user){ + OC_JSON::error(); + exit; +} +$tmpl = new OC_Template('calendar', 'share.dropdown'); +$tmpl->assign('calid', $calid); +$tmpl->printPage(); \ No newline at end of file diff --git a/apps/calendar/ajax/share.php b/apps/calendar/ajax/share.php new file mode 100644 index 00000000000..1b75c1731b9 --- /dev/null +++ b/apps/calendar/ajax/share.php @@ -0,0 +1,51 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +if($sharetype == 'user' && OC_User::getUser() == $sharewith){ + OC_JSON::error(array('meesage'=>'you can not share with yourself')); +} +$success = OC_Calendar_Share::share(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +if($success){ + if($sharetype == 'public'){ + OC_JSON::success(array('message'=>$success)); + }else{ + OC_JSON::success(array('message'=>'shared')); + } +}else{ + OC_JSON::error(array('message'=>'can not share')); + exit; +} \ No newline at end of file diff --git a/apps/calendar/ajax/unshare.php b/apps/calendar/ajax/unshare.php new file mode 100644 index 00000000000..f69295fd075 --- /dev/null +++ b/apps/calendar/ajax/unshare.php @@ -0,0 +1,44 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +$success = OC_Calendar_Share::unshare(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +if($success){ + OC_JSON::success(); +}else{ + OC_JSON::error(array('message'=>'can not unshare')); + exit; +} \ No newline at end of file diff --git a/apps/calendar/appinfo/app.php b/apps/calendar/appinfo/app.php index 9c95768895f..a684adb679b 100644 --- a/apps/calendar/appinfo/app.php +++ b/apps/calendar/appinfo/app.php @@ -6,8 +6,11 @@ if(version_compare(PHP_VERSION, '5.3.0', '>=')){ OC::$CLASSPATH['OC_Calendar_Object'] = 'apps/calendar/lib/object.php'; OC::$CLASSPATH['OC_Calendar_Hooks'] = 'apps/calendar/lib/hooks.php'; OC::$CLASSPATH['OC_Connector_Sabre_CalDAV'] = 'apps/calendar/lib/connector_sabre.php'; + OC::$CLASSPATH['OC_Calendar_Share'] = 'apps/calendar/lib/share.php'; OC_HOOK::connect('OC_User', 'post_deleteUser', 'OC_Calendar_Hooks', 'deleteUser'); OC_Util::addScript('calendar','loader'); + OC_Util::addScript('3rdparty', 'chosen/chosen.jquery.min'); + OC_Util::addStyle('3rdparty', 'chosen/chosen'); OC_App::register( array( 'order' => 10, 'id' => 'calendar', diff --git a/apps/calendar/appinfo/database.xml b/apps/calendar/appinfo/database.xml index ee672574a09..b065ab3f94a 100644 --- a/apps/calendar/appinfo/database.xml +++ b/apps/calendar/appinfo/database.xml @@ -212,7 +212,7 @@ sharetype text true - 5 + 6 @@ -259,7 +259,7 @@ sharetype text true - 5 + 6 diff --git a/apps/calendar/css/style.css b/apps/calendar/css/style.css index 1701a36a1f9..373a4565638 100644 --- a/apps/calendar/css/style.css +++ b/apps/calendar/css/style.css @@ -58,6 +58,10 @@ button.category{margin:0 3px;} #event {padding: 0;margin: 0;margin-top:-5px} +.calendar_share_dropdown{ display:block; position:absolute; z-index:100; width:16em; right:0; margin-right:7em; background:#F8F8F8; padding:1em; +-moz-box-shadow:0 1px 1px #777; -webkit-box-shadow:0 1px 1px #777; box-shadow:0 1px 1px #777; +-moz-border-radius:0 0 1em 1em; -webkit-border-radius:0 0 1em 1em; border-radius:0 0 1em 1em;} + .fc-list-table { margin: 10px; diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index 6b24fbc2f9c..bbefa1bcf2c 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -454,7 +454,7 @@ Calendar={ $('#calendar_holder').fullCalendar('removeEventSource', data.eventSource.url); $('#calendar_holder').fullCalendar('addEventSource', data.eventSource); if (calendarid == 'new'){ - $('#choosecalendar_dialog > table').append(''); + $('#choosecalendar_dialog > table:first').append(''); } }else{ $("#displayname_"+calendarid).css('background-color', '#FF2626'); @@ -493,6 +493,106 @@ Calendar={ left: -10000 }); } + }, + Share:{ + currentid: 'false', + idtype: '', + dropdown:function(userid, calid){ + $('.calendar_share_dropdown').remove(); + $('
    ').appendTo('#'+userid+'_'+calid); + $.get(OC.filePath('calendar', 'ajax', 'share.dropdown.php') + '?calid=' + calid, function(data){ + $('#'+userid+'_'+calid+' > .calendar_share_dropdown').html(data); + $('#'+userid+'_'+calid+' > .calendar_share_dropdown').show('blind'); + $('#share_user').chosen(); + $('#share_group').chosen(); + }); + Calendar.UI.Share.currentid = calid; + Calendar.UI.Share.idtype = 'calendar'; + }, + share:function(id, idtype, sharewith, sharetype){ + $.getJSON(OC.filePath('calendar', 'ajax', 'share.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(data){ + if(sharetype == 'public'){ + $('#public_token').val(OC.linkTo('calendar', 'share.php?t=' + data.message)); + $('#public_token').css('display', 'block'); + } + }); + }, + unshare:function(id, idtype, sharewith, sharetype){ + $.getJSON(OC.filePath('calendar', 'ajax', 'unshare.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(){ + if(sharetype == 'public'){ + $('#public_token').val(''); + $('#public_token').css('display', 'none'); + } + }); + }, + changepermission:function(id, idtype, sharewith, sharetype, permission){ + $.getJSON(OC.filePath('calendar', 'ajax', 'changepermission.php'),{id:id, idtype:idtype, sharewith: sharewith, sharetype:sharetype, permission: (permission?1:0)}); + }, + init:function(){ + $('.calendar_share_dropdown').live('mouseleave', function(){ + $('.calendar_share_dropdown').hide('blind', function(){ + $('.calendar_share_dropdown').remove(); + }); + }); + $('#share_user').live('change', function(){ + if($('#sharewithuser_' + $('#share_user option:selected').text()).length == 0){ + Calendar.UI.Share.share(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $('#share_user option:selected').text(), 'user'); + var newitem = '
  • ' + $('#share_user option:selected').text() + '
  • '; + $('#sharewithuser_list').append(newitem); + $('#sharewithuser_' + $('#share_user option:selected').text() + ' > img').click(function(){ + $('#share_user option[value="' + $(this).parent().text() + '"]').attr('disabled', 'false'); + Calendar.UI.Share.unshare(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'user' ); + $(this).parent().remove(); + }); + $('#share_user option:selected').attr('disabled', 'disabled'); + $("#share_user").trigger("liszt:updated"); + } + }); + $('#share_group').live('change', function(){ + if($('#sharewithgroup_' + $('#share_group option:selected').text()).length == 0){ + Calendar.UI.Share.share(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $('#share_group option:selected').text(), 'group'); + var newitem = '
  • ' + $('#share_group option:selected').text() + '
  • '; + $('#sharewithgroup_list').append(newitem); + $('#sharewithgroup_' + $('#share_user option:selected').text() + ' > img').click(function(){ + $('#share_group option[value="' + $(this).parent().text() + '"]').attr('disabled', 'false'); + Calendar.UI.Share.unshare(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'group'); + $(this).parent().remove(); + }); + $('#share_group option:selected').attr('disabled', 'disabled'); + $("#share_group").trigger("liszt:updated"); + } + }); + $('#sharewithuser_list > li > input:checkbox').live('change', function(){ + Calendar.UI.Share.changepermission(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'user', this.checked); + }); + $('#sharewithgroup_list > li > input:checkbox').live('change', function(){ + Calendar.UI.Share.changepermission(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'group', this.checked); + }); + $('#publish').live('change', function(){ + if(this.checked == 1){ + Calendar.UI.Share.share(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, '', 'public'); + }else{ + Calendar.UI.Share.unshare(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, '', 'public'); + } + }); + $('#sharewithuser_list').live('mouseenter', function(){ + $('#sharewithuser_list > li > img').css('display', 'block'); + $('#sharewithuser_list > li > input').css('visibility', 'visible'); + }); + $('#sharewithuser_list').live('mouseleave', function(){ + $('#sharewithuser_list > li > img').css('display', 'none'); + $('#sharewithuser_list > li > input').css('visibility', 'hidden'); + }); + $('#sharewithgroup_list').live('mouseenter', function(){ + $('#sharewithgroup_list > li > img').css('display', 'block'); + $('#sharewithgroup_list > li > input').css('visibility', 'visible'); + }); + $('#sharewithgroup_list').live('mouseleave', function(){ + $('#sharewithgroup_list > li > img').css('display', 'none'); + $('#sharewithgroup_list > li > input').css('visibility', 'hidden'); + }); + /*var permissions = (this.checked) ? 1 : 0;*/ + } } } } @@ -732,4 +832,5 @@ $(document).ready(function(){ $('#datecontrol_right').click(function(){ $('#calendar_holder').fullCalendar('next'); }); + Calendar.UI.Share.init(); }); diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php new file mode 100644 index 00000000000..bbc8770f65a --- /dev/null +++ b/apps/calendar/lib/share.php @@ -0,0 +1,163 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +/* + * This class manages shared calendars + */ +class OC_Calendar_Share{ + const CALENDAR = 'calendar'; + const EVENT = 'event'; + /* + * @brief: returns informations about all calendar or events which users are sharing with the user - userid + * @param: (string) $userid - id of the user + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return: (array) $return - information about calendars + */ + public static function allSharedwithuser($userid, $type){ + $group_where = 'false'; + $groups = OC_Group::getUserGroups($userid); + $i = 0; + foreach($groups as $group){ + if($i == 0){ + $group_where = ''; + }else{ + $group_where .= ' OR '; + } + $group_where .= ' (share = "' . $group . '" and sharetype = "group") '; + $i++; + } + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE (share = ? AND sharetype = "user") OR (' . $group_where . ')'); + $result = $stmt->execute(array($userid)); + $return = array(); + while( $row = $result->fetchRow()){ + $return[] = $row; + } + return $return; + } + /* + * @brief: returns all users a calendar / event is shared with + * @param: (int) id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return: (array) $users - information about users a calendar / event is shared with + */ + public static function allUsersSharedwith($id, $type){ + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ' . $type . 'id = ? ORDER BY share'); + $result = $stmt->execute(array($id)); + $users = array(); + while( $row = $result->fetchRow()){ + $users[] = $row; + } + return $users; + } + /* + * @brief: shares a calendar / event + * @param: (string) $owner - userid of the owner + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $sharetype - type of sharing (can be: user/group/public) + * @param: (string) $id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (mixed) - token (if $sharetype == public) / bool (if $sharetype != public) + */ + public static function share($owner, $share, $sharetype, $id, $type){ + if(self::is_already_shared($owner, $share, $sharetype, $id, $type)){ + return false; + } + switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + return false; + } + if($sharetype == 'public'){ + $share = self::generate_token(); + } + $stmt = OC_DB::prepare('INSERT INTO *PREFIX*calendar_share_' . $type . ' (owner,share,sharetype,' . $type . 'id,permissions' . (($type == self::CALENDAR)?', active':'') . ') VALUES(?,?,?,?,0' . (($type == self::CALENDAR)?', 1':'') . ')' ); + $result = $stmt->execute(array($owner,$share,$sharetype,$id)); + if($sharetype == 'public'){ + return $share; + }else{ + return true; + } + } + /* + * @brief: stops sharing a calendar / event + * @param: (string) $owner - userid of the owner + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $sharetype - type of sharing (can be: user/group/public) + * @param: (string) $id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (bool) + */ + public static function unshare($owner, $share, $sharetype, $id, $type){ + $stmt = OC_DB::prepare('DELETE FROM *PREFIX*calendar_share_' . $type . ' WHERE owner = ? ' . (($sharetype != 'public')?'AND share = ?':'') . ' AND sharetype = ? AND ' . $type . 'id = ?'); + if($sharetype != 'public'){ + $stmt->execute(array($owner,$share,$sharetype,$id)); + }else{ + $stmt->execute(array($owner,$sharetype,$id)); + } + return true; + } + /* + * @brief: changes the permission for a calendar / event + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $sharetype - type of sharing (can be: user/group/public) + * @param: (string) $id - id of the calendar / event + * @param: (int) $permission - permission of user the calendar / event is shared with (if $sharetype == public then $permission = 0) + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (bool) + */ + public static function changepermission($share, $sharetype, $id, $permission, $type){ + if($sharetype == 'public' && $permission == 1){ + $permission = 0; + } + $stmt = OC_DB::prepare('UPDATE *PREFIX*calendar_share_' . $type . ' SET permissions = ? WHERE share = ? AND sharetype = ? AND ' . $type . 'id = ?'); + $stmt->execute(array($permission, $share, $sharetype, $id)); + return true; + } + /* + * @brief: generates a token for public calendars / events + * @return: (string) $token + */ + private static function generate_token($id, $type){ + $uniqid = uniqid(); + if($type == self::CALENDAR){ + $events = OC_Calendar_Objects::all($id); + $string = ''; + foreach($events as $event){ + $string .= $event['calendardata']; + } + }else{ + $string = OC_Calendar_Object::find($id); + } + $string = sha1($string); + $id = sha1($id); + $array = array($uniqid,$string,$id); + shuffle($array); + $string = implode('', $array); + $token = md5($string); + return substr($token, rand(0,16), 15); + } + /* + * @brief: checks if it is already shared + * @param: (string) $owner - userid of the owner + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $sharetype - type of sharing (can be: user/group/public) + * @param: (string) $id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (bool) + */ + private static function is_already_shared($owner, $share, $sharetype, $id, $type){ + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE owner = ? AND share = ? AND sharetype = ? AND ' . $type . 'id = ?'); + $result = $stmt->execute(array($owner, $share, $sharetype, $id)); + if($result->numRows() > 0){ + return true; + } + return false; + } +} \ No newline at end of file diff --git a/apps/calendar/share.php b/apps/calendar/share.php new file mode 100644 index 00000000000..8d1c8b69c3f --- /dev/null +++ b/apps/calendar/share.php @@ -0,0 +1 @@ + diff --git a/apps/calendar/templates/part.choosecalendar.php b/apps/calendar/templates/part.choosecalendar.php index 86f09d62076..21da5dd7cd9 100644 --- a/apps/calendar/templates/part.choosecalendar.php +++ b/apps/calendar/templates/part.choosecalendar.php @@ -1,4 +1,5 @@
    "> +

    t('Your calendars'); ?>:

    +
    -

    ">

    +

    ">


    +

    t('Shared calendars'); ?>:

    + +'; + $tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields.shared'); + $tmpl->assign('share', $share[$i]); + $tmpl->printpage(); + echo ''; +} +?>
    +' . $l->t('No shared calendars') . '

    '; +} +?> +
    \ No newline at end of file diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.php b/apps/calendar/templates/part.choosecalendar.rowfields.php index a789be45a43..156d50bc48f 100644 --- a/apps/calendar/templates/part.choosecalendar.rowfields.php +++ b/apps/calendar/templates/part.choosecalendar.rowfields.php @@ -1,4 +1,8 @@ "; - echo ""; - echo "t("CalDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Calendar.UI.Calendar.edit(this, " . $_['calendar']["id"] . ");\">t("Delete") . "\" class=\"action\">"; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.shared.php b/apps/calendar/templates/part.choosecalendar.rowfields.shared.php new file mode 100644 index 00000000000..2e1210415bf --- /dev/null +++ b/apps/calendar/templates/part.choosecalendar.rowfields.shared.php @@ -0,0 +1,4 @@ +'; +echo ''; +echo '' . $l->t('shared with you by') . ' ' . $_['share']['owner'] . ''; \ No newline at end of file diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index 1b7aa1acb4c..4a9a467549f 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -231,6 +231,6 @@ t('Summary'); ?>:
    -
    -
    -
    \ No newline at end of file +
    //Alarm
    +
    //Attendees
    +
    //Share
    \ No newline at end of file diff --git a/apps/calendar/templates/share.dropdown.php b/apps/calendar/templates/share.dropdown.php new file mode 100644 index 00000000000..6a944f1f091 --- /dev/null +++ b/apps/calendar/templates/share.dropdown.php @@ -0,0 +1,71 @@ + +t('Users');?>:
    +
    +
      + +
    • style="visibility:hidden;" title="t('Editable'); ?>">
    • + + +
    +t('Groups');?>:
    +
    +
      + +
    • style="visibility:hidden;" title="t('Editable'); ?>">
    • + + +
    +
    + >
    + +
    \ No newline at end of file -- GitLab From 1a0c273a201e2478cea6d3fbc0abcd43b0670bd0 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Fri, 10 Feb 2012 20:04:49 +0100 Subject: [PATCH 015/430] initial project import from KDevelop --- owncloud.php | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 owncloud.php diff --git a/owncloud.php b/owncloud.php new file mode 100644 index 00000000000..adb6e8a2807 --- /dev/null +++ b/owncloud.php @@ -0,0 +1,7 @@ + Date: Sat, 11 Feb 2012 13:30:15 +0100 Subject: [PATCH 016/430] fix sharing calendar manager --- apps/calendar/js/calendar.js | 8 +++++--- apps/calendar/templates/share.dropdown.php | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index f6a353edd62..cf0bb079c88 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -540,9 +540,10 @@ Calendar={ var newitem = '
  • ' + $('#share_user option:selected').text() + '
  • '; $('#sharewithuser_list').append(newitem); $('#sharewithuser_' + $('#share_user option:selected').text() + ' > img').click(function(){ - $('#share_user option[value="' + $(this).parent().text() + '"]').attr('disabled', 'false'); + $('#share_user option[value="' + $(this).parent().text() + '"]').removeAttr('disabled'); Calendar.UI.Share.unshare(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'user' ); $(this).parent().remove(); + $("#share_user").trigger("liszt:updated"); }); $('#share_user option:selected').attr('disabled', 'disabled'); $("#share_user").trigger("liszt:updated"); @@ -553,10 +554,11 @@ Calendar={ Calendar.UI.Share.share(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $('#share_group option:selected').text(), 'group'); var newitem = '
  • ' + $('#share_group option:selected').text() + '
  • '; $('#sharewithgroup_list').append(newitem); - $('#sharewithgroup_' + $('#share_user option:selected').text() + ' > img').click(function(){ - $('#share_group option[value="' + $(this).parent().text() + '"]').attr('disabled', 'false'); + $('#sharewithgroup_' + $('#share_group option:selected').text() + ' > img').click(function(){ + $('#share_group option[value="' + $(this).parent().text() + '"]').removeAttr('disabled'); Calendar.UI.Share.unshare(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $(this).parent().text(), 'group'); $(this).parent().remove(); + $("#share_group").trigger("liszt:updated"); }); $('#share_group option:selected').attr('disabled', 'disabled'); $("#share_group").trigger("liszt:updated"); diff --git a/apps/calendar/templates/share.dropdown.php b/apps/calendar/templates/share.dropdown.php index 6a944f1f091..ca1e128ea78 100644 --- a/apps/calendar/templates/share.dropdown.php +++ b/apps/calendar/templates/share.dropdown.php @@ -53,7 +53,7 @@ echo html_select_options($allgroups, array());
      -
    • style="visibility:hidden;" title="t('Editable'); ?>">
    • +
    • style="visibility:hidden;" title="t('Editable'); ?>">
    • '); -} -OC_JSON::checkAppEnabled('calendar'); - -$id = $_GET['id']; -$data = OC_Calendar_App::getEventObject($id); -$object = OC_VObject::parse($data['calendardata']); -$vevent = $object->VEVENT; - -$dtstart = $vevent->DTSTART; -$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); -switch($dtstart->getDateType()) { - case Sabre_VObject_Element_DateTime::LOCALTZ: - case Sabre_VObject_Element_DateTime::LOCAL: - $startdate = $dtstart->getDateTime()->format('d-m-Y'); - $starttime = $dtstart->getDateTime()->format('H:i'); - $enddate = $dtend->getDateTime()->format('d-m-Y'); - $endtime = $dtend->getDateTime()->format('H:i'); - $allday = false; - break; - case Sabre_VObject_Element_DateTime::DATE: - $startdate = $dtstart->getDateTime()->format('d-m-Y'); - $starttime = ''; - $dtend->getDateTime()->modify('-1 day'); - $enddate = $dtend->getDateTime()->format('d-m-Y'); - $endtime = ''; - $allday = true; - break; -} - -$summary = $vevent->getAsString('SUMMARY'); -$location = $vevent->getAsString('LOCATION'); -$categories = $vevent->getAsArray('CATEGORIES'); -$description = $vevent->getAsString('DESCRIPTION'); -foreach($categories as $category){ - if (!in_array($category, $category_options)){ - array_unshift($category_options, $category); - } -} -$last_modified = $vevent->__get('LAST-MODIFIED'); -if ($last_modified){ - $lastmodified = $last_modified->getDateTime()->format('U'); -}else{ - $lastmodified = 0; -} -if($data['repeating'] == 1){ - $rrule = explode(';', $vevent->getAsString('RRULE')); - $rrulearr = array(); - foreach($rrule as $rule){ - list($attr, $val) = explode('=', $rule); - $rrulearr[$attr] = $val; - } - if(!isset($rrulearr['INTERVAL']) || $rrulearr['INTERVAL'] == ''){ - $rrulearr['INTERVAL'] = 1; - } - if(array_key_exists('BYDAY', $rrulearr)){ - if(substr_count($rrulearr['BYDAY'], ',') == 0){ - if(strlen($rrulearr['BYDAY']) == 2){ - $repeat['weekdays'] = array($rrulearr['BYDAY']); - }elseif(strlen($rrulearr['BYDAY']) == 3){ - $repeat['weekofmonth'] = substr($rrulearr['BYDAY'], 0, 1); - $repeat['weekdays'] = array(substr($rrulearr['BYDAY'], 1, 2)); - }elseif(strlen($rrulearr['BYDAY']) == 4){ - $repeat['weekofmonth'] = substr($rrulearr['BYDAY'], 0, 2); - $repeat['weekdays'] = array(substr($rrulearr['BYDAY'], 2, 2)); - } - }else{ - $byday_days = explode(',', $rrulearr['BYDAY']); - foreach($byday_days as $byday_day){ - if(strlen($byday_day) == 2){ - $repeat['weekdays'][] = $byday_day; - }elseif(strlen($byday_day) == 3){ - $repeat['weekofmonth'] = substr($byday_day , 0, 1); - $repeat['weekdays'][] = substr($byday_day , 1, 2); - }elseif(strlen($byday_day) == 4){ - $repeat['weekofmonth'] = substr($byday_day , 0, 2); - $repeat['weekdays'][] = substr($byday_day , 2, 2); - } - } - } - } - if(array_key_exists('BYMONTHDAY', $rrulearr)){ - if(substr_count($rrulearr['BYMONTHDAY'], ',') == 0){ - $repeat['bymonthday'][] = $rrulearr['BYMONTHDAY']; - }else{ - $bymonthdays = explode(',', $rrulearr['BYMONTHDAY']); - foreach($bymonthdays as $bymonthday){ - $repeat['bymonthday'][] = $bymonthday; - } - } - } - if(array_key_exists('BYYEARDAY', $rrulearr)){ - if(substr_count($rrulearr['BYYEARDAY'], ',') == 0){ - $repeat['byyearday'][] = $rrulearr['BYYEARDAY']; - }else{ - $byyeardays = explode(',', $rrulearr['BYYEARDAY']); - foreach($byyeardays as $yearday){ - $repeat['byyearday'][] = $yearday; - } - } - } - if(array_key_exists('BYWEEKNO', $rrulearr)){ - if(substr_count($rrulearr['BYWEEKNO'], ',') == 0){ - $repeat['byweekno'][] = (string) $rrulearr['BYWEEKNO']; - }else{ - $byweekno = explode(',', $rrulearr['BYWEEKNO']); - foreach($byweekno as $weekno){ - $repeat['byweekno'][] = (string) $weekno; - } - } - } - if(array_key_exists('BYMONTH', $rrulearr)){ - $months = OC_Calendar_App::getByMonthOptions(); - if(substr_count($rrulearr['BYMONTH'], ',') == 0){ - $repeat['bymonth'][] = $months[$month]; - }else{ - $bymonth = explode(',', $rrulearr['BYMONTH']); - foreach($bymonth as $month){ - $repeat['bymonth'][] = $months[$month]; - } - } - } - switch($rrulearr['FREQ']){ - case 'DAILY': - $repeat['repeat'] = 'daily'; - break; - case 'WEEKLY': - if($rrulearr['INTERVAL'] % 2 == 0){ - $repeat['repeat'] = 'biweekly'; - $rrulearr['INTERVAL'] = $rrulearr['INTERVAL'] / 2; - }elseif($rrulearr['BYDAY'] == 'MO,TU,WE,TH,FR'){ - $repeat['repeat'] = 'weekday'; - }else{ - $repeat['repeat'] = 'weekly'; - } - break; - case 'MONTHLY': - $repeat['repeat'] = 'monthly'; - if(array_key_exists('BYDAY', $rrulearr)){ - $repeat['month'] = 'weekday'; - }else{ - $repeat['month'] = 'monthday'; - } - break; - case 'YEARLY': - $repeat['repeat'] = 'yearly'; - if(array_key_exists('BYMONTH', $rrulearr)){ - $repeat['year'] = 'bydaymonth'; - }elseif(array_key_exists('BYWEEKNO', $rrulearr)){ - $repeat['year'] = 'byweekno'; - }else{ - $repeat['year'] = 'byyearday'; - } - } - $repeat['interval'] = $rrulearr['INTERVAL']; - if(array_key_exists('COUNT', $rrulearr)){ - $repeat['end'] = 'count'; - $repeat['count'] = $rrulearr['COUNT']; - }elseif(array_key_exists('UNTIL', $rrulearr)){ - $repeat['end'] = 'date'; - $endbydate_day = substr($rrulearr['UNTIL'], 6, 2); - $endbydate_month = substr($rrulearr['UNTIL'], 4, 2); - $endbydate_year = substr($rrulearr['UNTIL'], 0, 4); - $repeat['date'] = $endbydate_day . '-' . $endbydate_month . '-' . $endbydate_year; - }else{ - $repeat['end'] = 'never'; - } - if(array_key_exists('weekdays', $repeat)){ - $repeat_weekdays_ = array(); - $days = OC_Calendar_App::getWeeklyOptions(); - foreach($repeat['weekdays'] as $weekday){ - $repeat_weekdays_[] = $days[$weekday]; - } - $repeat['weekdays'] = $repeat_weekdays_; - } -}else{ - $repeat['repeat'] = 'doesnotrepeat'; -} - -$calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); -$category_options = OC_Calendar_App::getCategoryOptions(); -$repeat_options = OC_Calendar_App::getRepeatOptions(); -$repeat_end_options = OC_Calendar_App::getEndOptions(); -$repeat_month_options = OC_Calendar_App::getMonthOptions(); -$repeat_year_options = OC_Calendar_App::getYearOptions(); -$repeat_weekly_options = OC_Calendar_App::getWeeklyOptions(); -$repeat_weekofmonth_options = OC_Calendar_App::getWeekofMonth(); -$repeat_byyearday_options = OC_Calendar_App::getByYearDayOptions(); -$repeat_bymonth_options = OC_Calendar_App::getByMonthOptions(); -$repeat_byweekno_options = OC_Calendar_App::getByWeekNoOptions(); -$repeat_bymonthday_options = OC_Calendar_App::getByMonthDayOptions(); - -$tmpl = new OC_Template('calendar', 'part.editevent'); -$tmpl->assign('id', $id); -$tmpl->assign('lastmodified', $lastmodified); -$tmpl->assign('calendar_options', $calendar_options); -$tmpl->assign('category_options', $category_options); -$tmpl->assign('repeat_options', $repeat_options); -$tmpl->assign('repeat_month_options', $repeat_month_options); -$tmpl->assign('repeat_weekly_options', $repeat_weekly_options); -$tmpl->assign('repeat_end_options', $repeat_end_options); -$tmpl->assign('repeat_year_options', $repeat_year_options); -$tmpl->assign('repeat_byyearday_options', $repeat_byyearday_options); -$tmpl->assign('repeat_bymonth_options', $repeat_bymonth_options); -$tmpl->assign('repeat_byweekno_options', $repeat_byweekno_options); -$tmpl->assign('repeat_bymonthday_options', $repeat_bymonthday_options); -$tmpl->assign('repeat_weekofmonth_options', $repeat_weekofmonth_options); - -$tmpl->assign('title', $summary); -$tmpl->assign('location', $location); -$tmpl->assign('categories', $categories); -$tmpl->assign('calendar', $data['calendarid']); -$tmpl->assign('allday', $allday); -$tmpl->assign('startdate', $startdate); -$tmpl->assign('starttime', $starttime); -$tmpl->assign('enddate', $enddate); -$tmpl->assign('endtime', $endtime); -$tmpl->assign('description', $description); - -$tmpl->assign('repeat', $repeat['repeat']); -if($repeat['repeat'] != 'doesnotrepeat'){ - $tmpl->assign('repeat_month', $repeat['month']); - $tmpl->assign('repeat_weekdays', $repeat['weekdays']); - $tmpl->assign('repeat_interval', $repeat['interval']); - $tmpl->assign('repeat_end', $repeat['end']); - $tmpl->assign('repeat_count', $repeat['count']); - $tmpl->assign('repeat_weekofmonth', $repeat['weekofmonth']); - $tmpl->assign('repeat_date', $repeat['date']); - $tmpl->assign('repeat_year', $repeat['year']); - $tmpl->assign('repeat_byyearday', $repeat['byyearday']); - $tmpl->assign('repeat_bymonthday', $repeat['bymonthday']); - $tmpl->assign('repeat_bymonth', $repeat['bymonth']); - $tmpl->assign('repeat_byweekno', $repeat['byweekno']); -} -$tmpl->printpage(); - -?> \ No newline at end of file diff --git a/apps/calendar/ajax/gettimezonedetection.php b/apps/calendar/ajax/gettimezonedetection.php deleted file mode 100644 index ae58370712d..00000000000 --- a/apps/calendar/ajax/gettimezonedetection.php +++ /dev/null @@ -1,11 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once ("../../../lib/base.php"); -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); -OC_JSON::success(array('detection' => OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezonedetection'))); \ No newline at end of file diff --git a/apps/calendar/ajax/guesstimezone.php b/apps/calendar/ajax/guesstimezone.php deleted file mode 100755 index 41aea26985f..00000000000 --- a/apps/calendar/ajax/guesstimezone.php +++ /dev/null @@ -1,48 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -function make_array_out_of_xml ($xml){ - $returnarray = array(); - $xml = (array)$xml ; - foreach ($xml as $property => $value){ - $value = (array)$value; - if(!isset($value[0])){ - $returnarray[$property] = make_array_out_of_xml($value); - }else{ - $returnarray[$property] = trim($value[0]); - } - } - return $returnarray; -} -require_once ("../../../lib/base.php"); -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); -$l = new OC_L10N('calendar'); -$lat = $_GET['lat']; -$long = $_GET['long']; -if(OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'position') == $lat . '-' . $long && OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone') != null){ - OC_JSON::success(); - exit; -} -OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'position', $lat . '-' . $long); -$geolocation = file_get_contents('http://ws.geonames.org/timezone?lat=' . $lat . '&lng=' . $long); -//Information are by Geonames (http://www.geonames.org) and licensed under the Creative Commons Attribution 3.0 License -$geoxml = simplexml_load_string($geolocation); -$geoarray = make_array_out_of_xml($geoxml); -if($geoarray['timezone']['timezoneId'] == OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone')){ - OC_JSON::success(); - exit; -} -if(in_array($geoarray['timezone']['timezoneId'], DateTimeZone::listIdentifiers())){ - OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezone', $geoarray['timezone']['timezoneId']); - $message = array('message'=> $l->t('New Timezone:') . $geoarray['timezone']['timezoneId']); - OC_JSON::success($message); -}else{ - OC_JSON::error(); -} - -?> diff --git a/apps/calendar/ajax/importdialog.php b/apps/calendar/ajax/importdialog.php deleted file mode 100644 index f6b8453fc22..00000000000 --- a/apps/calendar/ajax/importdialog.php +++ /dev/null @@ -1,17 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -require_once('../../../lib/base.php'); -OC_JSON::checkLoggedIn(); -OC_Util::checkAppEnabled('calendar'); -$l10n = new OC_L10N('calendar'); -$tmpl = new OC_Template('calendar', 'part.import'); -$tmpl->assign('path', $_POST['path']); -$tmpl->assign('filename', $_POST['filename']); -$tmpl->printpage(); -?> diff --git a/apps/calendar/ajax/moveevent.php b/apps/calendar/ajax/moveevent.php deleted file mode 100644 index f2256d4eee6..00000000000 --- a/apps/calendar/ajax/moveevent.php +++ /dev/null @@ -1,43 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -OC_JSON::checkLoggedIn(); - -$id = $_POST['id']; - -$vcalendar = OC_Calendar_App::getVCalendar($id); -$vevent = $vcalendar->VEVENT; - -$allday = $_POST['allDay']; -$delta = new DateInterval('P0D'); -$delta->d = $_POST['dayDelta']; -$delta->i = $_POST['minuteDelta']; - -OC_Calendar_App::isNotModified($vevent, $_POST['lastmodified']); - -$dtstart = $vevent->DTSTART; -$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); -$start_type = $dtstart->getDateType(); -$end_type = $dtend->getDateType(); -if ($allday && $start_type != Sabre_VObject_Element_DateTime::DATE){ - $start_type = $end_type = Sabre_VObject_Element_DateTime::DATE; - $dtend->setDateTime($dtend->getDateTime()->modify('+1 day'), $end_type); -} -if (!$allday && $start_type == Sabre_VObject_Element_DateTime::DATE){ - $start_type = $end_type = Sabre_VObject_Element_DateTime::LOCALTZ; -} -$dtstart->setDateTime($dtstart->getDateTime()->add($delta), $start_type); -$dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); -unset($vevent->DURATION); - -$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); -$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); - -$result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); -$lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); -OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); diff --git a/apps/calendar/ajax/newcalendar.php b/apps/calendar/ajax/newcalendar.php deleted file mode 100644 index af3ba4fbbea..00000000000 --- a/apps/calendar/ajax/newcalendar.php +++ /dev/null @@ -1,24 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -require_once('../../../lib/base.php'); -$l10n = new OC_L10N('calendar'); -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); -$calendarcolor_options = OC_Calendar_Calendar::getCalendarColorOptions(); -$calendar = array( - 'id' => 'new', - 'displayname' => '', - 'calendarcolor' => '', -); -$tmpl = new OC_Template('calendar', 'part.editcalendar'); -$tmpl->assign('new', true); -$tmpl->assign('calendarcolor_options', $calendarcolor_options); -$tmpl->assign('calendar', $calendar); -$tmpl->printPage(); -?> diff --git a/apps/calendar/ajax/newevent.php b/apps/calendar/ajax/newevent.php deleted file mode 100644 index c7c4d29943a..00000000000 --- a/apps/calendar/ajax/newevent.php +++ /dev/null @@ -1,27 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -require_once('../../../lib/base.php'); - -$l10n = new OC_L10N('calendar'); - -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); - -$errarr = OC_Calendar_Object::validateRequest($_POST); -if($errarr){ - //show validate errors - OC_JSON::error($errarr); - exit; -}else{ - $cal = $_POST['calendar']; - $vcalendar = OC_Calendar_Object::createVCalendarFromRequest($_POST); - $result = OC_Calendar_Object::add($cal, $vcalendar->serialize()); - OC_JSON::success(); -} -?> diff --git a/apps/calendar/ajax/neweventform.php b/apps/calendar/ajax/neweventform.php deleted file mode 100644 index 3870c879b0e..00000000000 --- a/apps/calendar/ajax/neweventform.php +++ /dev/null @@ -1,76 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -require_once('../../../lib/base.php'); - -if(!OC_USER::isLoggedIn()) { - die(''); -} -OC_JSON::checkAppEnabled('calendar'); - -if (!isset($_POST['start'])){ - OC_JSON::error(); - die; -} -$start = $_POST['start']; -$end = $_POST['end']; -$allday = $_POST['allday']; - -if (!$end){ - $duration = OC_Preferences::getValue( OC_User::getUser(), 'calendar', 'duration', '60'); - $end = $start + ($duration * 60); -} -$start = new DateTime('@'.$start); -$end = new DateTime('@'.$end); -$timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); -$start->setTimezone(new DateTimeZone($timezone)); -$end->setTimezone(new DateTimeZone($timezone)); - -$calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); -$category_options = OC_Calendar_App::getCategoryOptions(); -$repeat_options = OC_Calendar_App::getRepeatOptions(); -$repeat_end_options = OC_Calendar_App::getEndOptions(); -$repeat_month_options = OC_Calendar_App::getMonthOptions(); -$repeat_year_options = OC_Calendar_App::getYearOptions(); -$repeat_weekly_options = OC_Calendar_App::getWeeklyOptions(); -$repeat_weekofmonth_options = OC_Calendar_App::getWeekofMonth(); -$repeat_byyearday_options = OC_Calendar_App::getByYearDayOptions(); -$repeat_bymonth_options = OC_Calendar_App::getByMonthOptions(); -$repeat_byweekno_options = OC_Calendar_App::getByWeekNoOptions(); -$repeat_bymonthday_options = OC_Calendar_App::getByMonthDayOptions(); - -$tmpl = new OC_Template('calendar', 'part.newevent'); -$tmpl->assign('calendar_options', $calendar_options); -$tmpl->assign('category_options', $category_options); -$tmpl->assign('repeat_options', $repeat_options); -$tmpl->assign('repeat_month_options', $repeat_month_options); -$tmpl->assign('repeat_weekly_options', $repeat_weekly_options); -$tmpl->assign('repeat_end_options', $repeat_end_options); -$tmpl->assign('repeat_year_options', $repeat_year_options); -$tmpl->assign('repeat_byyearday_options', $repeat_byyearday_options); -$tmpl->assign('repeat_bymonth_options', $repeat_bymonth_options); -$tmpl->assign('repeat_byweekno_options', $repeat_byweekno_options); -$tmpl->assign('repeat_bymonthday_options', $repeat_bymonthday_options); -$tmpl->assign('repeat_weekofmonth_options', $repeat_weekofmonth_options); - -$tmpl->assign('startdate', $start->format('d-m-Y')); -$tmpl->assign('starttime', $start->format('H:i')); -$tmpl->assign('enddate', $end->format('d-m-Y')); -$tmpl->assign('endtime', $end->format('H:i')); -$tmpl->assign('allday', $allday); -$tmpl->assign('repeat', 'doesnotrepeat'); -$tmpl->assign('repeat_month', 'monthday'); -$tmpl->assign('repeat_weekdays', array()); -$tmpl->assign('repeat_interval', 1); -$tmpl->assign('repeat_end', 'never'); -$tmpl->assign('repeat_count', '10'); -$tmpl->assign('repeat_weekofmonth', 'auto'); -$tmpl->assign('repeat_date', ''); -$tmpl->assign('repeat_year', 'bydate'); -$tmpl->printpage(); -?> diff --git a/apps/calendar/ajax/resizeevent.php b/apps/calendar/ajax/resizeevent.php deleted file mode 100644 index 68347906529..00000000000 --- a/apps/calendar/ajax/resizeevent.php +++ /dev/null @@ -1,32 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -OC_JSON::checkLoggedIn(); - -$id = $_POST['id']; - -$vcalendar = OC_Calendar_App::getVCalendar($id); -$vevent = $vcalendar->VEVENT; - -$delta = new DateInterval('P0D'); -$delta->d = $_POST['dayDelta']; -$delta->i = $_POST['minuteDelta']; - -OC_Calendar_App::isNotModified($vevent, $_POST['lastmodified']); - -$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); -$end_type = $dtend->getDateType(); -$dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); -unset($vevent->DURATION); - -$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); -$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); - -$result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); -$lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); -OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); diff --git a/apps/calendar/ajax/settimeformat.php b/apps/calendar/ajax/settimeformat.php deleted file mode 100644 index 7805120ba5e..00000000000 --- a/apps/calendar/ajax/settimeformat.php +++ /dev/null @@ -1,17 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -OC_JSON::checkLoggedIn(); -if(isset($_POST["timeformat"])){ - OC_Preferences::setValue(OC_User::getUser(), 'calendar', 'timeformat', $_POST["timeformat"]); - OC_JSON::success(); -}else{ - OC_JSON::error(); -} -?> - diff --git a/apps/calendar/ajax/settimezone.php b/apps/calendar/ajax/settimezone.php deleted file mode 100644 index c726a11471d..00000000000 --- a/apps/calendar/ajax/settimezone.php +++ /dev/null @@ -1,27 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -// Init owncloud -require_once('../../../lib/base.php'); - -$l=new OC_L10N('calendar'); - -// Check if we are a user -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); - -// Get data -if( isset( $_POST['timezone'] ) ){ - $timezone=$_POST['timezone']; - OC_Preferences::setValue( OC_User::getUser(), 'calendar', 'timezone', $timezone ); - OC_JSON::success(array('data' => array( 'message' => $l->t('Timezone changed') ))); -}else{ - OC_JSON::error(array('data' => array( 'message' => $l->t('Invalid request') ))); -} - -?> diff --git a/apps/calendar/ajax/share.dropdown.php b/apps/calendar/ajax/share.dropdown.php deleted file mode 100644 index 7e78521a76b..00000000000 --- a/apps/calendar/ajax/share.dropdown.php +++ /dev/null @@ -1,18 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -$user = OC_USER::getUser(); -$calid = $_GET['calid']; -$calendar = OC_Calendar_Calendar::find($calid); -if($calendar['userid'] != $user){ - OC_JSON::error(); - exit; -} -$tmpl = new OC_Template('calendar', 'share.dropdown'); -$tmpl->assign('calid', $calid); -$tmpl->printPage(); \ No newline at end of file diff --git a/apps/calendar/ajax/share.php b/apps/calendar/ajax/share.php deleted file mode 100644 index 1b75c1731b9..00000000000 --- a/apps/calendar/ajax/share.php +++ /dev/null @@ -1,51 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -$id = strip_tags($_GET['id']); -$idtype = strip_tags($_GET['idtype']); -switch($idtype){ - case 'calendar': - case 'event': - break; - default: - OC_JSON::error(array('message'=>'unexspected parameter')); - exit; -} -$sharewith = $_GET['sharewith']; -$sharetype = strip_tags($_GET['sharetype']); -switch($sharetype){ - case 'user': - case 'group': - case 'public': - break; - default: - OC_JSON::error(array('message'=>'unexspected parameter')); - exit; -} -if($sharetype == 'user' && !OC_User::userExists($sharewith)){ - OC_JSON::error(array('message'=>'user not found')); - exit; -} -if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ - OC_JSON::error(array('message'=>'group not found')); - exit; -} -if($sharetype == 'user' && OC_User::getUser() == $sharewith){ - OC_JSON::error(array('meesage'=>'you can not share with yourself')); -} -$success = OC_Calendar_Share::share(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); -if($success){ - if($sharetype == 'public'){ - OC_JSON::success(array('message'=>$success)); - }else{ - OC_JSON::success(array('message'=>'shared')); - } -}else{ - OC_JSON::error(array('message'=>'can not share')); - exit; -} \ No newline at end of file diff --git a/apps/calendar/ajax/timeformat.php b/apps/calendar/ajax/timeformat.php deleted file mode 100644 index 3533adcf8e0..00000000000 --- a/apps/calendar/ajax/timeformat.php +++ /dev/null @@ -1,12 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -OC_JSON::checkLoggedIn(); -$timeformat = OC_Preferences::getValue( OC_User::getUser(), 'calendar', 'timeformat', "24"); -OC_JSON::encodedPrint(array("timeformat" => $timeformat)); -?> diff --git a/apps/calendar/ajax/timezonedetection.php b/apps/calendar/ajax/timezonedetection.php deleted file mode 100644 index 77e4c4f6ebe..00000000000 --- a/apps/calendar/ajax/timezonedetection.php +++ /dev/null @@ -1,17 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once ("../../../lib/base.php"); -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); -if($_POST['timezonedetection'] == 'on'){ - OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezonedetection', 'true'); -}else{ - OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezonedetection', 'false'); -} -OC_JSON::success(); - diff --git a/apps/calendar/ajax/unshare.php b/apps/calendar/ajax/unshare.php deleted file mode 100644 index f69295fd075..00000000000 --- a/apps/calendar/ajax/unshare.php +++ /dev/null @@ -1,44 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -require_once('../../../lib/base.php'); -$id = strip_tags($_GET['id']); -$idtype = strip_tags($_GET['idtype']); -switch($idtype){ - case 'calendar': - case 'event': - break; - default: - OC_JSON::error(array('message'=>'unexspected parameter')); - exit; -} -$sharewith = $_GET['sharewith']; -$sharetype = strip_tags($_GET['sharetype']); -switch($sharetype){ - case 'user': - case 'group': - case 'public': - break; - default: - OC_JSON::error(array('message'=>'unexspected parameter')); - exit; -} -if($sharetype == 'user' && !OC_User::userExists($sharewith)){ - OC_JSON::error(array('message'=>'user not found')); - exit; -} -if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ - OC_JSON::error(array('message'=>'group not found')); - exit; -} -$success = OC_Calendar_Share::unshare(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); -if($success){ - OC_JSON::success(); -}else{ - OC_JSON::error(array('message'=>'can not unshare')); - exit; -} \ No newline at end of file diff --git a/apps/calendar/ajax/updatecalendar.php b/apps/calendar/ajax/updatecalendar.php deleted file mode 100644 index 5add6d92bfa..00000000000 --- a/apps/calendar/ajax/updatecalendar.php +++ /dev/null @@ -1,38 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -require_once('../../../lib/base.php'); - -// Check if we are a user -OC_JSON::checkLoggedIn(); -OC_JSON::checkAppEnabled('calendar'); - -if(trim($_POST['name']) == ''){ - OC_JSON::error(array('message'=>'empty')); - exit; -} -$calendars = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); -foreach($calendars as $cal){ - if($cal['displayname'] == $_POST['name'] && $cal['id'] != $_POST['id']){ - OC_JSON::error(array('message'=>'namenotavailable')); - exit; - } -} - -$calendarid = $_POST['id']; -$calendar = OC_Calendar_App::getCalendar($calendarid);//access check -OC_Calendar_Calendar::editCalendar($calendarid, strip_tags($_POST['name']), null, null, null, $_POST['color']); -OC_Calendar_Calendar::setCalendarActive($calendarid, $_POST['active']); - -$calendar = OC_Calendar_App::getCalendar($calendarid); -$tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields'); -$tmpl->assign('calendar', $calendar); -OC_JSON::success(array( - 'page' => $tmpl->fetchPage(), - 'eventSource' => OC_Calendar_Calendar::getEventSourceInfo($calendar), -)); -- GitLab From 8dff0fb58de75b05540782ea6b33b19f24be2f17 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:26:22 +0100 Subject: [PATCH 024/430] add moved files to clean up ajax folder --- apps/calendar/ajax/calendar/activation.php | 19 ++ apps/calendar/ajax/calendar/delete.php | 21 ++ apps/calendar/ajax/calendar/edit.form.php | 20 ++ apps/calendar/ajax/calendar/edit.php | 20 ++ apps/calendar/ajax/calendar/new.form.php | 24 ++ apps/calendar/ajax/calendar/new.php | 37 +++ apps/calendar/ajax/calendar/overview.php | 15 ++ .../calendar/ajax/calendar/updatecalendar.php | 38 +++ apps/calendar/ajax/event/delete.php | 19 ++ apps/calendar/ajax/event/edit.form.php | 248 ++++++++++++++++++ apps/calendar/ajax/event/edit.php | 33 +++ apps/calendar/ajax/event/move.php | 43 +++ apps/calendar/ajax/event/new.form.php | 76 ++++++ apps/calendar/ajax/event/new.php | 27 ++ apps/calendar/ajax/event/resize.php | 32 +++ apps/calendar/ajax/import/dialog.php | 17 ++ apps/calendar/ajax/import/import.php | 120 +++++++++ .../ajax/settings/gettimezonedetection.php | 11 + apps/calendar/ajax/settings/guesstimezone.php | 48 ++++ apps/calendar/ajax/settings/settimeformat.php | 17 ++ apps/calendar/ajax/settings/settimezone.php | 27 ++ apps/calendar/ajax/settings/timeformat.php | 12 + .../ajax/settings/timezonedetection.php | 17 ++ apps/calendar/ajax/share/changepermission.php | 40 +++ apps/calendar/ajax/share/dropdown.php | 18 ++ apps/calendar/ajax/share/share.php | 51 ++++ apps/calendar/ajax/share/unshare.php | 44 ++++ 27 files changed, 1094 insertions(+) create mode 100644 apps/calendar/ajax/calendar/activation.php create mode 100644 apps/calendar/ajax/calendar/delete.php create mode 100644 apps/calendar/ajax/calendar/edit.form.php create mode 100644 apps/calendar/ajax/calendar/edit.php create mode 100644 apps/calendar/ajax/calendar/new.form.php create mode 100644 apps/calendar/ajax/calendar/new.php create mode 100644 apps/calendar/ajax/calendar/overview.php create mode 100644 apps/calendar/ajax/calendar/updatecalendar.php create mode 100644 apps/calendar/ajax/event/delete.php create mode 100644 apps/calendar/ajax/event/edit.form.php create mode 100644 apps/calendar/ajax/event/edit.php create mode 100644 apps/calendar/ajax/event/move.php create mode 100644 apps/calendar/ajax/event/new.form.php create mode 100644 apps/calendar/ajax/event/new.php create mode 100644 apps/calendar/ajax/event/resize.php create mode 100644 apps/calendar/ajax/import/dialog.php create mode 100644 apps/calendar/ajax/import/import.php create mode 100644 apps/calendar/ajax/settings/gettimezonedetection.php create mode 100755 apps/calendar/ajax/settings/guesstimezone.php create mode 100644 apps/calendar/ajax/settings/settimeformat.php create mode 100644 apps/calendar/ajax/settings/settimezone.php create mode 100644 apps/calendar/ajax/settings/timeformat.php create mode 100644 apps/calendar/ajax/settings/timezonedetection.php create mode 100644 apps/calendar/ajax/share/changepermission.php create mode 100644 apps/calendar/ajax/share/dropdown.php create mode 100644 apps/calendar/ajax/share/share.php create mode 100644 apps/calendar/ajax/share/unshare.php diff --git a/apps/calendar/ajax/calendar/activation.php b/apps/calendar/ajax/calendar/activation.php new file mode 100644 index 00000000000..7677d85aff3 --- /dev/null +++ b/apps/calendar/ajax/calendar/activation.php @@ -0,0 +1,19 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +$calendarid = $_POST['calendarid']; +$calendar = OC_Calendar_App::getCalendar($calendarid);//access check +OC_Calendar_Calendar::setCalendarActive($calendarid, $_POST['active']); +$calendar = OC_Calendar_App::getCalendar($calendarid); +OC_JSON::success(array( + 'active' => $calendar['active'], + 'eventSource' => OC_Calendar_Calendar::getEventSourceInfo($calendar), +)); diff --git a/apps/calendar/ajax/calendar/delete.php b/apps/calendar/ajax/calendar/delete.php new file mode 100644 index 00000000000..a2f5311731c --- /dev/null +++ b/apps/calendar/ajax/calendar/delete.php @@ -0,0 +1,21 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); + +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$cal = $_POST["calendarid"]; +$calendar = OC_Calendar_App::getCalendar($cal); +$del = OC_Calendar_Calendar::deleteCalendar($cal); +if($del == true){ + OC_JSON::success(); +}else{ + OC_JSON::error(array('error'=>'dberror')); +} +?> diff --git a/apps/calendar/ajax/calendar/edit.form.php b/apps/calendar/ajax/calendar/edit.form.php new file mode 100644 index 00000000000..8922b3eba4e --- /dev/null +++ b/apps/calendar/ajax/calendar/edit.form.php @@ -0,0 +1,20 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$calendarcolor_options = OC_Calendar_Calendar::getCalendarColorOptions(); +$calendar = OC_Calendar_App::getCalendar($_GET['calendarid']); +$tmpl = new OC_Template("calendar", "part.editcalendar"); +$tmpl->assign('new', false); +$tmpl->assign('calendarcolor_options', $calendarcolor_options); +$tmpl->assign('calendar', $calendar); +$tmpl->printPage(); +?> diff --git a/apps/calendar/ajax/calendar/edit.php b/apps/calendar/ajax/calendar/edit.php new file mode 100644 index 00000000000..8922b3eba4e --- /dev/null +++ b/apps/calendar/ajax/calendar/edit.php @@ -0,0 +1,20 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$calendarcolor_options = OC_Calendar_Calendar::getCalendarColorOptions(); +$calendar = OC_Calendar_App::getCalendar($_GET['calendarid']); +$tmpl = new OC_Template("calendar", "part.editcalendar"); +$tmpl->assign('new', false); +$tmpl->assign('calendarcolor_options', $calendarcolor_options); +$tmpl->assign('calendar', $calendar); +$tmpl->printPage(); +?> diff --git a/apps/calendar/ajax/calendar/new.form.php b/apps/calendar/ajax/calendar/new.form.php new file mode 100644 index 00000000000..6e7423cbe92 --- /dev/null +++ b/apps/calendar/ajax/calendar/new.form.php @@ -0,0 +1,24 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +$l10n = new OC_L10N('calendar'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +$calendarcolor_options = OC_Calendar_Calendar::getCalendarColorOptions(); +$calendar = array( + 'id' => 'new', + 'displayname' => '', + 'calendarcolor' => '', +); +$tmpl = new OC_Template('calendar', 'part.editcalendar'); +$tmpl->assign('new', true); +$tmpl->assign('calendarcolor_options', $calendarcolor_options); +$tmpl->assign('calendar', $calendar); +$tmpl->printPage(); +?> diff --git a/apps/calendar/ajax/calendar/new.php b/apps/calendar/ajax/calendar/new.php new file mode 100644 index 00000000000..228e6247724 --- /dev/null +++ b/apps/calendar/ajax/calendar/new.php @@ -0,0 +1,37 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); + +// Check if we are a user +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +if(trim($_POST['name']) == ''){ + OC_JSON::error(array('message'=>'empty')); + exit; +} +$calendars = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +foreach($calendars as $cal){ + if($cal['displayname'] == $_POST['name']){ + OC_JSON::error(array('message'=>'namenotavailable')); + exit; + } +} + +$userid = OC_User::getUser(); +$calendarid = OC_Calendar_Calendar::addCalendar($userid, strip_tags($_POST['name']), 'VEVENT,VTODO,VJOURNAL', null, 0, $_POST['color']); +OC_Calendar_Calendar::setCalendarActive($calendarid, 1); + +$calendar = OC_Calendar_Calendar::find($calendarid); +$tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields'); +$tmpl->assign('calendar', $calendar); +OC_JSON::success(array( + 'page' => $tmpl->fetchPage(), + 'eventSource' => OC_Calendar_Calendar::getEventSourceInfo($calendar), +)); diff --git a/apps/calendar/ajax/calendar/overview.php b/apps/calendar/ajax/calendar/overview.php new file mode 100644 index 00000000000..2f73f5d0710 --- /dev/null +++ b/apps/calendar/ajax/calendar/overview.php @@ -0,0 +1,15 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +$l10n = new OC_L10N('calendar'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +$output = new OC_TEMPLATE("calendar", "part.choosecalendar"); +$output -> printpage(); +?> diff --git a/apps/calendar/ajax/calendar/updatecalendar.php b/apps/calendar/ajax/calendar/updatecalendar.php new file mode 100644 index 00000000000..f400c8c14b4 --- /dev/null +++ b/apps/calendar/ajax/calendar/updatecalendar.php @@ -0,0 +1,38 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); + +// Check if we are a user +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +if(trim($_POST['name']) == ''){ + OC_JSON::error(array('message'=>'empty')); + exit; +} +$calendars = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +foreach($calendars as $cal){ + if($cal['displayname'] == $_POST['name'] && $cal['id'] != $_POST['id']){ + OC_JSON::error(array('message'=>'namenotavailable')); + exit; + } +} + +$calendarid = $_POST['id']; +$calendar = OC_Calendar_App::getCalendar($calendarid);//access check +OC_Calendar_Calendar::editCalendar($calendarid, strip_tags($_POST['name']), null, null, null, $_POST['color']); +OC_Calendar_Calendar::setCalendarActive($calendarid, $_POST['active']); + +$calendar = OC_Calendar_App::getCalendar($calendarid); +$tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields'); +$tmpl->assign('calendar', $calendar); +OC_JSON::success(array( + 'page' => $tmpl->fetchPage(), + 'eventSource' => OC_Calendar_Calendar::getEventSourceInfo($calendar), +)); diff --git a/apps/calendar/ajax/event/delete.php b/apps/calendar/ajax/event/delete.php new file mode 100644 index 00000000000..862dec6bf5b --- /dev/null +++ b/apps/calendar/ajax/event/delete.php @@ -0,0 +1,19 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); + +$l10n = new OC_L10N('calendar'); + +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$id = $_POST['id']; +$event_object = OC_Calendar_App::getEventObject($id); +$result = OC_Calendar_Object::delete($id); +OC_JSON::success(); +?> diff --git a/apps/calendar/ajax/event/edit.form.php b/apps/calendar/ajax/event/edit.form.php new file mode 100644 index 00000000000..837edbbbf05 --- /dev/null +++ b/apps/calendar/ajax/event/edit.form.php @@ -0,0 +1,248 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); + +if(!OC_USER::isLoggedIn()) { + die(''); +} +OC_JSON::checkAppEnabled('calendar'); + +$id = $_GET['id']; +$data = OC_Calendar_App::getEventObject($id); +$object = OC_VObject::parse($data['calendardata']); +$vevent = $object->VEVENT; + +$dtstart = $vevent->DTSTART; +$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); +switch($dtstart->getDateType()) { + case Sabre_VObject_Element_DateTime::LOCALTZ: + case Sabre_VObject_Element_DateTime::LOCAL: + $startdate = $dtstart->getDateTime()->format('d-m-Y'); + $starttime = $dtstart->getDateTime()->format('H:i'); + $enddate = $dtend->getDateTime()->format('d-m-Y'); + $endtime = $dtend->getDateTime()->format('H:i'); + $allday = false; + break; + case Sabre_VObject_Element_DateTime::DATE: + $startdate = $dtstart->getDateTime()->format('d-m-Y'); + $starttime = ''; + $dtend->getDateTime()->modify('-1 day'); + $enddate = $dtend->getDateTime()->format('d-m-Y'); + $endtime = ''; + $allday = true; + break; +} + +$summary = $vevent->getAsString('SUMMARY'); +$location = $vevent->getAsString('LOCATION'); +$categories = $vevent->getAsArray('CATEGORIES'); +$description = $vevent->getAsString('DESCRIPTION'); +foreach($categories as $category){ + if (!in_array($category, $category_options)){ + array_unshift($category_options, $category); + } +} +$last_modified = $vevent->__get('LAST-MODIFIED'); +if ($last_modified){ + $lastmodified = $last_modified->getDateTime()->format('U'); +}else{ + $lastmodified = 0; +} +if($data['repeating'] == 1){ + $rrule = explode(';', $vevent->getAsString('RRULE')); + $rrulearr = array(); + foreach($rrule as $rule){ + list($attr, $val) = explode('=', $rule); + $rrulearr[$attr] = $val; + } + if(!isset($rrulearr['INTERVAL']) || $rrulearr['INTERVAL'] == ''){ + $rrulearr['INTERVAL'] = 1; + } + if(array_key_exists('BYDAY', $rrulearr)){ + if(substr_count($rrulearr['BYDAY'], ',') == 0){ + if(strlen($rrulearr['BYDAY']) == 2){ + $repeat['weekdays'] = array($rrulearr['BYDAY']); + }elseif(strlen($rrulearr['BYDAY']) == 3){ + $repeat['weekofmonth'] = substr($rrulearr['BYDAY'], 0, 1); + $repeat['weekdays'] = array(substr($rrulearr['BYDAY'], 1, 2)); + }elseif(strlen($rrulearr['BYDAY']) == 4){ + $repeat['weekofmonth'] = substr($rrulearr['BYDAY'], 0, 2); + $repeat['weekdays'] = array(substr($rrulearr['BYDAY'], 2, 2)); + } + }else{ + $byday_days = explode(',', $rrulearr['BYDAY']); + foreach($byday_days as $byday_day){ + if(strlen($byday_day) == 2){ + $repeat['weekdays'][] = $byday_day; + }elseif(strlen($byday_day) == 3){ + $repeat['weekofmonth'] = substr($byday_day , 0, 1); + $repeat['weekdays'][] = substr($byday_day , 1, 2); + }elseif(strlen($byday_day) == 4){ + $repeat['weekofmonth'] = substr($byday_day , 0, 2); + $repeat['weekdays'][] = substr($byday_day , 2, 2); + } + } + } + } + if(array_key_exists('BYMONTHDAY', $rrulearr)){ + if(substr_count($rrulearr['BYMONTHDAY'], ',') == 0){ + $repeat['bymonthday'][] = $rrulearr['BYMONTHDAY']; + }else{ + $bymonthdays = explode(',', $rrulearr['BYMONTHDAY']); + foreach($bymonthdays as $bymonthday){ + $repeat['bymonthday'][] = $bymonthday; + } + } + } + if(array_key_exists('BYYEARDAY', $rrulearr)){ + if(substr_count($rrulearr['BYYEARDAY'], ',') == 0){ + $repeat['byyearday'][] = $rrulearr['BYYEARDAY']; + }else{ + $byyeardays = explode(',', $rrulearr['BYYEARDAY']); + foreach($byyeardays as $yearday){ + $repeat['byyearday'][] = $yearday; + } + } + } + if(array_key_exists('BYWEEKNO', $rrulearr)){ + if(substr_count($rrulearr['BYWEEKNO'], ',') == 0){ + $repeat['byweekno'][] = (string) $rrulearr['BYWEEKNO']; + }else{ + $byweekno = explode(',', $rrulearr['BYWEEKNO']); + foreach($byweekno as $weekno){ + $repeat['byweekno'][] = (string) $weekno; + } + } + } + if(array_key_exists('BYMONTH', $rrulearr)){ + $months = OC_Calendar_App::getByMonthOptions(); + if(substr_count($rrulearr['BYMONTH'], ',') == 0){ + $repeat['bymonth'][] = $months[$month]; + }else{ + $bymonth = explode(',', $rrulearr['BYMONTH']); + foreach($bymonth as $month){ + $repeat['bymonth'][] = $months[$month]; + } + } + } + switch($rrulearr['FREQ']){ + case 'DAILY': + $repeat['repeat'] = 'daily'; + break; + case 'WEEKLY': + if($rrulearr['INTERVAL'] % 2 == 0){ + $repeat['repeat'] = 'biweekly'; + $rrulearr['INTERVAL'] = $rrulearr['INTERVAL'] / 2; + }elseif($rrulearr['BYDAY'] == 'MO,TU,WE,TH,FR'){ + $repeat['repeat'] = 'weekday'; + }else{ + $repeat['repeat'] = 'weekly'; + } + break; + case 'MONTHLY': + $repeat['repeat'] = 'monthly'; + if(array_key_exists('BYDAY', $rrulearr)){ + $repeat['month'] = 'weekday'; + }else{ + $repeat['month'] = 'monthday'; + } + break; + case 'YEARLY': + $repeat['repeat'] = 'yearly'; + if(array_key_exists('BYMONTH', $rrulearr)){ + $repeat['year'] = 'bydaymonth'; + }elseif(array_key_exists('BYWEEKNO', $rrulearr)){ + $repeat['year'] = 'byweekno'; + }else{ + $repeat['year'] = 'byyearday'; + } + } + $repeat['interval'] = $rrulearr['INTERVAL']; + if(array_key_exists('COUNT', $rrulearr)){ + $repeat['end'] = 'count'; + $repeat['count'] = $rrulearr['COUNT']; + }elseif(array_key_exists('UNTIL', $rrulearr)){ + $repeat['end'] = 'date'; + $endbydate_day = substr($rrulearr['UNTIL'], 6, 2); + $endbydate_month = substr($rrulearr['UNTIL'], 4, 2); + $endbydate_year = substr($rrulearr['UNTIL'], 0, 4); + $repeat['date'] = $endbydate_day . '-' . $endbydate_month . '-' . $endbydate_year; + }else{ + $repeat['end'] = 'never'; + } + if(array_key_exists('weekdays', $repeat)){ + $repeat_weekdays_ = array(); + $days = OC_Calendar_App::getWeeklyOptions(); + foreach($repeat['weekdays'] as $weekday){ + $repeat_weekdays_[] = $days[$weekday]; + } + $repeat['weekdays'] = $repeat_weekdays_; + } +}else{ + $repeat['repeat'] = 'doesnotrepeat'; +} + +$calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +$category_options = OC_Calendar_App::getCategoryOptions(); +$repeat_options = OC_Calendar_App::getRepeatOptions(); +$repeat_end_options = OC_Calendar_App::getEndOptions(); +$repeat_month_options = OC_Calendar_App::getMonthOptions(); +$repeat_year_options = OC_Calendar_App::getYearOptions(); +$repeat_weekly_options = OC_Calendar_App::getWeeklyOptions(); +$repeat_weekofmonth_options = OC_Calendar_App::getWeekofMonth(); +$repeat_byyearday_options = OC_Calendar_App::getByYearDayOptions(); +$repeat_bymonth_options = OC_Calendar_App::getByMonthOptions(); +$repeat_byweekno_options = OC_Calendar_App::getByWeekNoOptions(); +$repeat_bymonthday_options = OC_Calendar_App::getByMonthDayOptions(); + +$tmpl = new OC_Template('calendar', 'part.editevent'); +$tmpl->assign('id', $id); +$tmpl->assign('lastmodified', $lastmodified); +$tmpl->assign('calendar_options', $calendar_options); +$tmpl->assign('category_options', $category_options); +$tmpl->assign('repeat_options', $repeat_options); +$tmpl->assign('repeat_month_options', $repeat_month_options); +$tmpl->assign('repeat_weekly_options', $repeat_weekly_options); +$tmpl->assign('repeat_end_options', $repeat_end_options); +$tmpl->assign('repeat_year_options', $repeat_year_options); +$tmpl->assign('repeat_byyearday_options', $repeat_byyearday_options); +$tmpl->assign('repeat_bymonth_options', $repeat_bymonth_options); +$tmpl->assign('repeat_byweekno_options', $repeat_byweekno_options); +$tmpl->assign('repeat_bymonthday_options', $repeat_bymonthday_options); +$tmpl->assign('repeat_weekofmonth_options', $repeat_weekofmonth_options); + +$tmpl->assign('title', $summary); +$tmpl->assign('location', $location); +$tmpl->assign('categories', $categories); +$tmpl->assign('calendar', $data['calendarid']); +$tmpl->assign('allday', $allday); +$tmpl->assign('startdate', $startdate); +$tmpl->assign('starttime', $starttime); +$tmpl->assign('enddate', $enddate); +$tmpl->assign('endtime', $endtime); +$tmpl->assign('description', $description); + +$tmpl->assign('repeat', $repeat['repeat']); +if($repeat['repeat'] != 'doesnotrepeat'){ + $tmpl->assign('repeat_month', $repeat['month']); + $tmpl->assign('repeat_weekdays', $repeat['weekdays']); + $tmpl->assign('repeat_interval', $repeat['interval']); + $tmpl->assign('repeat_end', $repeat['end']); + $tmpl->assign('repeat_count', $repeat['count']); + $tmpl->assign('repeat_weekofmonth', $repeat['weekofmonth']); + $tmpl->assign('repeat_date', $repeat['date']); + $tmpl->assign('repeat_year', $repeat['year']); + $tmpl->assign('repeat_byyearday', $repeat['byyearday']); + $tmpl->assign('repeat_bymonthday', $repeat['bymonthday']); + $tmpl->assign('repeat_bymonth', $repeat['bymonth']); + $tmpl->assign('repeat_byweekno', $repeat['byweekno']); +} +$tmpl->printpage(); + +?> \ No newline at end of file diff --git a/apps/calendar/ajax/event/edit.php b/apps/calendar/ajax/event/edit.php new file mode 100644 index 00000000000..64daffddef0 --- /dev/null +++ b/apps/calendar/ajax/event/edit.php @@ -0,0 +1,33 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$errarr = OC_Calendar_Object::validateRequest($_POST); +if($errarr){ + //show validate errors + OC_JSON::error($errarr); + exit; +}else{ + $id = $_POST['id']; + $cal = $_POST['calendar']; + $data = OC_Calendar_App::getEventObject($id); + $vcalendar = OC_VObject::parse($data['calendardata']); + + OC_Calendar_App::isNotModified($vcalendar->VEVENT, $_POST['lastmodified']); + OC_Calendar_Object::updateVCalendarFromRequest($_POST, $vcalendar); + + $result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); + if ($data['calendarid'] != $cal) { + OC_Calendar_Object::moveToCalendar($id, $cal); + } + OC_JSON::success(); +} +?> diff --git a/apps/calendar/ajax/event/move.php b/apps/calendar/ajax/event/move.php new file mode 100644 index 00000000000..8150fdbaa32 --- /dev/null +++ b/apps/calendar/ajax/event/move.php @@ -0,0 +1,43 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); + +$id = $_POST['id']; + +$vcalendar = OC_Calendar_App::getVCalendar($id); +$vevent = $vcalendar->VEVENT; + +$allday = $_POST['allDay']; +$delta = new DateInterval('P0D'); +$delta->d = $_POST['dayDelta']; +$delta->i = $_POST['minuteDelta']; + +OC_Calendar_App::isNotModified($vevent, $_POST['lastmodified']); + +$dtstart = $vevent->DTSTART; +$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); +$start_type = $dtstart->getDateType(); +$end_type = $dtend->getDateType(); +if ($allday && $start_type != Sabre_VObject_Element_DateTime::DATE){ + $start_type = $end_type = Sabre_VObject_Element_DateTime::DATE; + $dtend->setDateTime($dtend->getDateTime()->modify('+1 day'), $end_type); +} +if (!$allday && $start_type == Sabre_VObject_Element_DateTime::DATE){ + $start_type = $end_type = Sabre_VObject_Element_DateTime::LOCALTZ; +} +$dtstart->setDateTime($dtstart->getDateTime()->add($delta), $start_type); +$dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); +unset($vevent->DURATION); + +$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); +$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); + +$result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); +$lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); +OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); diff --git a/apps/calendar/ajax/event/new.form.php b/apps/calendar/ajax/event/new.form.php new file mode 100644 index 00000000000..c19928a727e --- /dev/null +++ b/apps/calendar/ajax/event/new.form.php @@ -0,0 +1,76 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); + +if(!OC_USER::isLoggedIn()) { + die(''); +} +OC_JSON::checkAppEnabled('calendar'); + +if (!isset($_POST['start'])){ + OC_JSON::error(); + die; +} +$start = $_POST['start']; +$end = $_POST['end']; +$allday = $_POST['allday']; + +if (!$end){ + $duration = OC_Preferences::getValue( OC_User::getUser(), 'calendar', 'duration', '60'); + $end = $start + ($duration * 60); +} +$start = new DateTime('@'.$start); +$end = new DateTime('@'.$end); +$timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); +$start->setTimezone(new DateTimeZone($timezone)); +$end->setTimezone(new DateTimeZone($timezone)); + +$calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +$category_options = OC_Calendar_App::getCategoryOptions(); +$repeat_options = OC_Calendar_App::getRepeatOptions(); +$repeat_end_options = OC_Calendar_App::getEndOptions(); +$repeat_month_options = OC_Calendar_App::getMonthOptions(); +$repeat_year_options = OC_Calendar_App::getYearOptions(); +$repeat_weekly_options = OC_Calendar_App::getWeeklyOptions(); +$repeat_weekofmonth_options = OC_Calendar_App::getWeekofMonth(); +$repeat_byyearday_options = OC_Calendar_App::getByYearDayOptions(); +$repeat_bymonth_options = OC_Calendar_App::getByMonthOptions(); +$repeat_byweekno_options = OC_Calendar_App::getByWeekNoOptions(); +$repeat_bymonthday_options = OC_Calendar_App::getByMonthDayOptions(); + +$tmpl = new OC_Template('calendar', 'part.newevent'); +$tmpl->assign('calendar_options', $calendar_options); +$tmpl->assign('category_options', $category_options); +$tmpl->assign('repeat_options', $repeat_options); +$tmpl->assign('repeat_month_options', $repeat_month_options); +$tmpl->assign('repeat_weekly_options', $repeat_weekly_options); +$tmpl->assign('repeat_end_options', $repeat_end_options); +$tmpl->assign('repeat_year_options', $repeat_year_options); +$tmpl->assign('repeat_byyearday_options', $repeat_byyearday_options); +$tmpl->assign('repeat_bymonth_options', $repeat_bymonth_options); +$tmpl->assign('repeat_byweekno_options', $repeat_byweekno_options); +$tmpl->assign('repeat_bymonthday_options', $repeat_bymonthday_options); +$tmpl->assign('repeat_weekofmonth_options', $repeat_weekofmonth_options); + +$tmpl->assign('startdate', $start->format('d-m-Y')); +$tmpl->assign('starttime', $start->format('H:i')); +$tmpl->assign('enddate', $end->format('d-m-Y')); +$tmpl->assign('endtime', $end->format('H:i')); +$tmpl->assign('allday', $allday); +$tmpl->assign('repeat', 'doesnotrepeat'); +$tmpl->assign('repeat_month', 'monthday'); +$tmpl->assign('repeat_weekdays', array()); +$tmpl->assign('repeat_interval', 1); +$tmpl->assign('repeat_end', 'never'); +$tmpl->assign('repeat_count', '10'); +$tmpl->assign('repeat_weekofmonth', 'auto'); +$tmpl->assign('repeat_date', ''); +$tmpl->assign('repeat_year', 'bydate'); +$tmpl->printpage(); +?> diff --git a/apps/calendar/ajax/event/new.php b/apps/calendar/ajax/event/new.php new file mode 100644 index 00000000000..59fda79da73 --- /dev/null +++ b/apps/calendar/ajax/event/new.php @@ -0,0 +1,27 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); + +$l10n = new OC_L10N('calendar'); + +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +$errarr = OC_Calendar_Object::validateRequest($_POST); +if($errarr){ + //show validate errors + OC_JSON::error($errarr); + exit; +}else{ + $cal = $_POST['calendar']; + $vcalendar = OC_Calendar_Object::createVCalendarFromRequest($_POST); + $result = OC_Calendar_Object::add($cal, $vcalendar->serialize()); + OC_JSON::success(); +} +?> diff --git a/apps/calendar/ajax/event/resize.php b/apps/calendar/ajax/event/resize.php new file mode 100644 index 00000000000..aa2d420e77d --- /dev/null +++ b/apps/calendar/ajax/event/resize.php @@ -0,0 +1,32 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); + +$id = $_POST['id']; + +$vcalendar = OC_Calendar_App::getVCalendar($id); +$vevent = $vcalendar->VEVENT; + +$delta = new DateInterval('P0D'); +$delta->d = $_POST['dayDelta']; +$delta->i = $_POST['minuteDelta']; + +OC_Calendar_App::isNotModified($vevent, $_POST['lastmodified']); + +$dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); +$end_type = $dtend->getDateType(); +$dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); +unset($vevent->DURATION); + +$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); +$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); + +$result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); +$lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); +OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); diff --git a/apps/calendar/ajax/import/dialog.php b/apps/calendar/ajax/import/dialog.php new file mode 100644 index 00000000000..2e002092150 --- /dev/null +++ b/apps/calendar/ajax/import/dialog.php @@ -0,0 +1,17 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_Util::checkAppEnabled('calendar'); +$l10n = new OC_L10N('calendar'); +$tmpl = new OC_Template('calendar', 'part.import'); +$tmpl->assign('path', $_POST['path']); +$tmpl->assign('filename', $_POST['filename']); +$tmpl->printpage(); +?> diff --git a/apps/calendar/ajax/import/import.php b/apps/calendar/ajax/import/import.php new file mode 100644 index 00000000000..96d7af48341 --- /dev/null +++ b/apps/calendar/ajax/import/import.php @@ -0,0 +1,120 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +//check for calendar rights or create new one +ob_start(); +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_Util::checkAppEnabled('calendar'); +$nl = "\n"; +$progressfile = OC::$SERVERROOT . '/apps/calendar/import_tmp/' . md5(session_id()) . '.txt'; +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '10'); + fclose($progressfopen); +} +$file = OC_Filesystem::file_get_contents($_POST['path'] . '/' . $_POST['file']); +if($_POST['method'] == 'new'){ + $id = OC_Calendar_Calendar::addCalendar(OC_User::getUser(), $_POST['calname']); + OC_Calendar_Calendar::setCalendarActive($id, 1); +}else{ + $calendar = OC_Calendar_App::getCalendar($_POST['id']); + if($calendar['userid'] != OC_USER::getUser()){ + OC_JSON::error(); + exit(); + } + $id = $_POST['id']; +} +//analyse the calendar file +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '20'); + fclose($progressfopen); +} +$searchfor = array('VEVENT', 'VTODO', 'VJOURNAL'); +$parts = $searchfor; +$filearr = explode($nl, $file); +$inelement = false; +$parts = array(); +$i = 0; +foreach($filearr as $line){ + foreach($searchfor as $search){ + if(substr_count($line, $search) == 1){ + list($attr, $val) = explode(':', $line); + if($attr == 'BEGIN'){ + $parts[]['begin'] = $i; + $inelement = true; + } + if($attr == 'END'){ + $parts[count($parts) - 1]['end'] = $i; + $inelement = false; + } + } + } + $i++; +} +//import the calendar +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '40'); + fclose($progressfopen); +} +$start = ''; +for ($i = 0; $i < $parts[0]['begin']; $i++) { + if($i == 0){ + $start = $filearr[0]; + }else{ + $start .= $nl . $filearr[$i]; + } +} +$end = ''; +for($i = $parts[count($parts) - 1]['end'] + 1;$i <= count($filearr) - 1; $i++){ + if($i == $parts[count($parts) - 1]['end'] + 1){ + $end = $filearr[$parts[count($parts) - 1]['end'] + 1]; + }else{ + $end .= $nl . $filearr[$i]; + } +} +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '50'); + fclose($progressfopen); +} +$importready = array(); +foreach($parts as $part){ + for($i = $part['begin']; $i <= $part['end'];$i++){ + if($i == $part['begin']){ + $content = $filearr[$i]; + }else{ + $content .= $nl . $filearr[$i]; + } + } + $importready[] = $start . $nl . $content . $nl . $end; +} +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '70'); + fclose($progressfopen); +} +if(count($parts) == 1){ + OC_Calendar_Object::add($id, $file); +}else{ + foreach($importready as $import){ + OC_Calendar_Object::add($id, $import); + } +} +//done the import +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '100'); + fclose($progressfopen); +} +sleep(3); +if(is_writable('import_tmp/')){ + unlink($progressfile); +} +OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/ajax/settings/gettimezonedetection.php b/apps/calendar/ajax/settings/gettimezonedetection.php new file mode 100644 index 00000000000..11255fe8ef3 --- /dev/null +++ b/apps/calendar/ajax/settings/gettimezonedetection.php @@ -0,0 +1,11 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +OC_JSON::success(array('detection' => OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezonedetection'))); \ No newline at end of file diff --git a/apps/calendar/ajax/settings/guesstimezone.php b/apps/calendar/ajax/settings/guesstimezone.php new file mode 100755 index 00000000000..cfa92e1aee8 --- /dev/null +++ b/apps/calendar/ajax/settings/guesstimezone.php @@ -0,0 +1,48 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +function make_array_out_of_xml ($xml){ + $returnarray = array(); + $xml = (array)$xml ; + foreach ($xml as $property => $value){ + $value = (array)$value; + if(!isset($value[0])){ + $returnarray[$property] = make_array_out_of_xml($value); + }else{ + $returnarray[$property] = trim($value[0]); + } + } + return $returnarray; +} +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +$l = new OC_L10N('calendar'); +$lat = $_GET['lat']; +$long = $_GET['long']; +if(OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'position') == $lat . '-' . $long && OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone') != null){ + OC_JSON::success(); + exit; +} +OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'position', $lat . '-' . $long); +$geolocation = file_get_contents('http://ws.geonames.org/timezone?lat=' . $lat . '&lng=' . $long); +//Information are by Geonames (http://www.geonames.org) and licensed under the Creative Commons Attribution 3.0 License +$geoxml = simplexml_load_string($geolocation); +$geoarray = make_array_out_of_xml($geoxml); +if($geoarray['timezone']['timezoneId'] == OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone')){ + OC_JSON::success(); + exit; +} +if(in_array($geoarray['timezone']['timezoneId'], DateTimeZone::listIdentifiers())){ + OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezone', $geoarray['timezone']['timezoneId']); + $message = array('message'=> $l->t('New Timezone:') . $geoarray['timezone']['timezoneId']); + OC_JSON::success($message); +}else{ + OC_JSON::error(); +} + +?> diff --git a/apps/calendar/ajax/settings/settimeformat.php b/apps/calendar/ajax/settings/settimeformat.php new file mode 100644 index 00000000000..8f65447065c --- /dev/null +++ b/apps/calendar/ajax/settings/settimeformat.php @@ -0,0 +1,17 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +if(isset($_POST["timeformat"])){ + OC_Preferences::setValue(OC_User::getUser(), 'calendar', 'timeformat', $_POST["timeformat"]); + OC_JSON::success(); +}else{ + OC_JSON::error(); +} +?> + diff --git a/apps/calendar/ajax/settings/settimezone.php b/apps/calendar/ajax/settings/settimezone.php new file mode 100644 index 00000000000..c639753fe2f --- /dev/null +++ b/apps/calendar/ajax/settings/settimezone.php @@ -0,0 +1,27 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +// Init owncloud +require_once('../../../../lib/base.php'); + +$l=new OC_L10N('calendar'); + +// Check if we are a user +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); + +// Get data +if( isset( $_POST['timezone'] ) ){ + $timezone=$_POST['timezone']; + OC_Preferences::setValue( OC_User::getUser(), 'calendar', 'timezone', $timezone ); + OC_JSON::success(array('data' => array( 'message' => $l->t('Timezone changed') ))); +}else{ + OC_JSON::error(array('data' => array( 'message' => $l->t('Invalid request') ))); +} + +?> diff --git a/apps/calendar/ajax/settings/timeformat.php b/apps/calendar/ajax/settings/timeformat.php new file mode 100644 index 00000000000..e0dbe8d3cd7 --- /dev/null +++ b/apps/calendar/ajax/settings/timeformat.php @@ -0,0 +1,12 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +$timeformat = OC_Preferences::getValue( OC_User::getUser(), 'calendar', 'timeformat', "24"); +OC_JSON::encodedPrint(array("timeformat" => $timeformat)); +?> diff --git a/apps/calendar/ajax/settings/timezonedetection.php b/apps/calendar/ajax/settings/timezonedetection.php new file mode 100644 index 00000000000..f67bab901e7 --- /dev/null +++ b/apps/calendar/ajax/settings/timezonedetection.php @@ -0,0 +1,17 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('calendar'); +if($_POST['timezonedetection'] == 'on'){ + OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezonedetection', 'true'); +}else{ + OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'timezonedetection', 'false'); +} +OC_JSON::success(); + diff --git a/apps/calendar/ajax/share/changepermission.php b/apps/calendar/ajax/share/changepermission.php new file mode 100644 index 00000000000..d91f87b613f --- /dev/null +++ b/apps/calendar/ajax/share/changepermission.php @@ -0,0 +1,40 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +$permission = (int) strip_tags($_GET['permission']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +$success = OC_Calendar_Share::changepermission($sharewith, $sharetype, $id, $permission, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/ajax/share/dropdown.php b/apps/calendar/ajax/share/dropdown.php new file mode 100644 index 00000000000..eb396d38fd9 --- /dev/null +++ b/apps/calendar/ajax/share/dropdown.php @@ -0,0 +1,18 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +$user = OC_USER::getUser(); +$calid = $_GET['calid']; +$calendar = OC_Calendar_Calendar::find($calid); +if($calendar['userid'] != $user){ + OC_JSON::error(); + exit; +} +$tmpl = new OC_Template('calendar', 'share.dropdown'); +$tmpl->assign('calid', $calid); +$tmpl->printPage(); \ No newline at end of file diff --git a/apps/calendar/ajax/share/share.php b/apps/calendar/ajax/share/share.php new file mode 100644 index 00000000000..d892727701a --- /dev/null +++ b/apps/calendar/ajax/share/share.php @@ -0,0 +1,51 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +if($sharetype == 'user' && OC_User::getUser() == $sharewith){ + OC_JSON::error(array('meesage'=>'you can not share with yourself')); +} +$success = OC_Calendar_Share::share(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +if($success){ + if($sharetype == 'public'){ + OC_JSON::success(array('message'=>$success)); + }else{ + OC_JSON::success(array('message'=>'shared')); + } +}else{ + OC_JSON::error(array('message'=>'can not share')); + exit; +} \ No newline at end of file diff --git a/apps/calendar/ajax/share/unshare.php b/apps/calendar/ajax/share/unshare.php new file mode 100644 index 00000000000..ec3150a89aa --- /dev/null +++ b/apps/calendar/ajax/share/unshare.php @@ -0,0 +1,44 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$idtype = strip_tags($_GET['idtype']); +switch($idtype){ + case 'calendar': + case 'event': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +$sharewith = $_GET['sharewith']; +$sharetype = strip_tags($_GET['sharetype']); +switch($sharetype){ + case 'user': + case 'group': + case 'public': + break; + default: + OC_JSON::error(array('message'=>'unexspected parameter')); + exit; +} +if($sharetype == 'user' && !OC_User::userExists($sharewith)){ + OC_JSON::error(array('message'=>'user not found')); + exit; +} +if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ + OC_JSON::error(array('message'=>'group not found')); + exit; +} +$success = OC_Calendar_Share::unshare(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +if($success){ + OC_JSON::success(); +}else{ + OC_JSON::error(array('message'=>'can not unshare')); + exit; +} \ No newline at end of file -- GitLab From 1cf7fc261f1a6a9b7307735ee4808970ebff9073 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:26:43 +0100 Subject: [PATCH 025/430] better var name in changeview.php --- apps/calendar/ajax/changeview.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/calendar/ajax/changeview.php b/apps/calendar/ajax/changeview.php index df3e2827b7e..034c7129cab 100644 --- a/apps/calendar/ajax/changeview.php +++ b/apps/calendar/ajax/changeview.php @@ -9,16 +9,16 @@ require_once ('../../../lib/base.php'); OC_JSON::checkLoggedIn(); OC_JSON::checkAppEnabled('calendar'); -$currentview = $_GET['v']; -switch($currentview){ +$view = $_GET['v']; +switch($view){ case 'agendaWeek': case 'month'; case 'list': break; default: - OC_JSON::error(); + OC_JSON::error(array('message'=>'unexspected parameter: ' . $view)); exit; } -OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'currentview', $currentview); +OC_Preferences::setValue(OC_USER::getUser(), 'calendar', 'currentview', $view); OC_JSON::success(); ?> \ No newline at end of file -- GitLab From 3efa69bc848dc99754f788893cc82cd11fc4316f Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:27:25 +0100 Subject: [PATCH 026/430] update js files for new ajax pathes --- apps/calendar/js/calendar.js | 30 +++++++++++++++--------------- apps/calendar/js/geo.js | 2 +- apps/calendar/js/loader.js | 6 +++--- apps/calendar/js/settings.js | 10 +++++----- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index cf0bb079c88..e9c33f7c454 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -70,7 +70,7 @@ Calendar={ $('#event').dialog('destroy').remove(); }else{ Calendar.UI.loading(true); - $('#dialog_holder').load(OC.filePath('calendar', 'ajax', 'neweventform.php'), {start:start, end:end, allday:allday?1:0}, Calendar.UI.startEventDialog); + $('#dialog_holder').load(OC.filePath('calendar', 'ajax/event', 'new.form.php'), {start:start, end:end, allday:allday?1:0}, Calendar.UI.startEventDialog); } }, editEvent:function(calEvent, jsEvent, view){ @@ -80,7 +80,7 @@ Calendar={ $('#event').dialog('destroy').remove(); }else{ Calendar.UI.loading(true); - $('#dialog_holder').load(OC.filePath('calendar', 'ajax', 'editeventform.php') + '?id=' + id, Calendar.UI.startEventDialog); + $('#dialog_holder').load(OC.filePath('calendar', 'ajax/event', 'edit.form.php') + '?id=' + id, Calendar.UI.startEventDialog); } }, submitDeleteEventForm:function(url){ @@ -142,7 +142,7 @@ Calendar={ moveEvent:function(event, dayDelta, minuteDelta, allDay, revertFunc){ $('.tipsy').remove(); Calendar.UI.loading(true); - $.post(OC.filePath('calendar', 'ajax', 'moveevent.php'), { id: event.id, dayDelta: dayDelta, minuteDelta: minuteDelta, allDay: allDay?1:0, lastmodified: event.lastmodified}, + $.post(OC.filePath('calendar', 'ajax/event', 'move.php'), { id: event.id, dayDelta: dayDelta, minuteDelta: minuteDelta, allDay: allDay?1:0, lastmodified: event.lastmodified}, function(data) { Calendar.UI.loading(false); if (data.status == 'success'){ @@ -157,7 +157,7 @@ Calendar={ resizeEvent:function(event, dayDelta, minuteDelta, revertFunc){ $('.tipsy').remove(); Calendar.UI.loading(true); - $.post(OC.filePath('calendar', 'ajax', 'resizeevent.php'), { id: event.id, dayDelta: dayDelta, minuteDelta: minuteDelta, lastmodified: event.lastmodified}, + $.post(OC.filePath('calendar', 'ajax/event', 'resize.php'), { id: event.id, dayDelta: dayDelta, minuteDelta: minuteDelta, lastmodified: event.lastmodified}, function(data) { Calendar.UI.loading(false); if (data.status == 'success'){ @@ -374,7 +374,7 @@ Calendar={ $('#choosecalendar_dialog').dialog('moveToTop'); }else{ Calendar.UI.loading(true); - $('#dialog_holder').load(OC.filePath('calendar', 'ajax', 'choosecalendar.php'), function(){ + $('#dialog_holder').load(OC.filePath('calendar', 'ajax/calendar', 'overview.php'), function(){ $('#choosecalendar_dialog').dialog({ width : 600, close : function(event, ui) { @@ -388,7 +388,7 @@ Calendar={ activation:function(checkbox, calendarid) { Calendar.UI.loading(true); - $.post(OC.filePath('calendar', 'ajax', 'activation.php'), { calendarid: calendarid, active: checkbox.checked?1:0 }, + $.post(OC.filePath('calendar', 'ajax/calendar', 'activation.php'), { calendarid: calendarid, active: checkbox.checked?1:0 }, function(data) { Calendar.UI.loading(false); if (data.status == 'success'){ @@ -403,13 +403,13 @@ Calendar={ }, newCalendar:function(object){ var tr = $(document.createElement('tr')) - .load(OC.filePath('calendar', 'ajax', 'newcalendar.php'), + .load(OC.filePath('calendar', 'ajax/calendar', 'new.form.php'), function(){Calendar.UI.Calendar.colorPicker(this)}); $(object).closest('tr').after(tr).hide(); }, edit:function(object, calendarid){ var tr = $(document.createElement('tr')) - .load(OC.filePath('calendar', 'ajax', 'editcalendar.php') + "?calendarid="+calendarid, + .load(OC.filePath('calendar', 'ajax/calendar', 'edit.form.php') + "?calendarid="+calendarid, function(){Calendar.UI.Calendar.colorPicker(this)}); $(object).closest('tr').after(tr).hide(); }, @@ -418,7 +418,7 @@ Calendar={ if(check == false){ return false; }else{ - $.post(OC.filePath('calendar', 'ajax', 'deletecalendar.php'), { calendarid: calid}, + $.post(OC.filePath('calendar', 'ajax/calendar', 'delete.php'), { calendarid: calid}, function(data) { if (data.status == 'success'){ var url = 'ajax/events.php?calendar_id='+calid; @@ -443,9 +443,9 @@ Calendar={ var url; if (calendarid == 'new'){ - url = OC.filePath('calendar', 'ajax', 'createcalendar.php'); + url = OC.filePath('calendar', 'ajax/calendar', 'new.php'); }else{ - url = OC.filePath('calendar', 'ajax', 'updatecalendar.php'); + url = OC.filePath('calendar', 'ajax/calendar', 'update.php'); } $.post(url, { id: calendarid, name: displayname, active: active, description: description, color: calendarcolor }, function(data){ @@ -500,7 +500,7 @@ Calendar={ dropdown:function(userid, calid){ $('.calendar_share_dropdown').remove(); $('
      ').appendTo('#'+userid+'_'+calid); - $.get(OC.filePath('calendar', 'ajax', 'share.dropdown.php') + '?calid=' + calid, function(data){ + $.get(OC.filePath('calendar', 'ajax/share', 'dropdown.php') + '?calid=' + calid, function(data){ $('#'+userid+'_'+calid+' > .calendar_share_dropdown').html(data); $('#'+userid+'_'+calid+' > .calendar_share_dropdown').show('blind'); $('#share_user').chosen(); @@ -510,7 +510,7 @@ Calendar={ Calendar.UI.Share.idtype = 'calendar'; }, share:function(id, idtype, sharewith, sharetype){ - $.getJSON(OC.filePath('calendar', 'ajax', 'share.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(data){ + $.getJSON(OC.filePath('calendar', 'ajax/share', 'share.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(data){ if(sharetype == 'public'){ $('#public_token').val(OC.linkTo('calendar', 'share.php?t=' + data.message)); $('#public_token').css('display', 'block'); @@ -518,7 +518,7 @@ Calendar={ }); }, unshare:function(id, idtype, sharewith, sharetype){ - $.getJSON(OC.filePath('calendar', 'ajax', 'unshare.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(){ + $.getJSON(OC.filePath('calendar', 'ajax/share', 'unshare.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(){ if(sharetype == 'public'){ $('#public_token').val(''); $('#public_token').css('display', 'none'); @@ -526,7 +526,7 @@ Calendar={ }); }, changepermission:function(id, idtype, sharewith, sharetype, permission){ - $.getJSON(OC.filePath('calendar', 'ajax', 'changepermission.php'),{id:id, idtype:idtype, sharewith: sharewith, sharetype:sharetype, permission: (permission?1:0)}); + $.getJSON(OC.filePath('calendar', 'ajax/share', 'changepermission.php'),{id:id, idtype:idtype, sharewith: sharewith, sharetype:sharetype, permission: (permission?1:0)}); }, init:function(){ $('.calendar_share_dropdown').live('mouseleave', function(){ diff --git a/apps/calendar/js/geo.js b/apps/calendar/js/geo.js index ae6a971e938..c9cc5dd0955 100755 --- a/apps/calendar/js/geo.js +++ b/apps/calendar/js/geo.js @@ -6,7 +6,7 @@ */ if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { - $.getJSON(OC.filePath('calendar', 'ajax', 'guesstimezone.php?lat=' + position.coords.latitude + '&long=' + position.coords.longitude + ''), + $.getJSON(OC.filePath('calendar', 'ajax/settings', 'guesstimezone.php?lat=' + position.coords.latitude + '&long=' + position.coords.longitude + ''), function(data){ if (data.status == 'success' && typeof(data.message) != 'undefined'){ $('#notification').html(data.message); diff --git a/apps/calendar/js/loader.js b/apps/calendar/js/loader.js index 4e483f9864e..54003879759 100644 --- a/apps/calendar/js/loader.js +++ b/apps/calendar/js/loader.js @@ -8,7 +8,7 @@ Calendar_Import={ importdialog: function(filename){ var path = $('#dir').val(); $('body').append('
      '); - $('#calendar_import').load(OC.filePath('calendar', 'ajax', 'importdialog.php'), {filename:filename, path:path}, function(){Calendar_Import.initdialog(filename);}); + $('#calendar_import').load(OC.filePath('calendar', 'ajax/import', 'dialog.php'), {filename:filename, path:path}, function(){Calendar_Import.initdialog(filename);}); }, initdialog: function(filename){ $('#calendar_import_dialog').dialog({ @@ -68,7 +68,7 @@ Calendar_Import={ if(percent < 100){ window.setTimeout('Calendar_Import.getimportstatus(\'' + progressfile + '\')', 500); }else{ - $('#import_done').css('display', 'block'); + $('#import_done').css('display', 'block'); } }); } @@ -78,4 +78,4 @@ $(document).ready(function(){ FileActions.register('text/calendar','importcal', '', Calendar_Import.importdialog); FileActions.setDefault('text/calendar','importcal'); }; -}); \ No newline at end of file +}); diff --git a/apps/calendar/js/settings.js b/apps/calendar/js/settings.js index 73300885565..fcbfc423db3 100644 --- a/apps/calendar/js/settings.js +++ b/apps/calendar/js/settings.js @@ -3,7 +3,7 @@ $(document).ready(function(){ OC.msg.startSaving('#calendar .msg') // Serialize the data var post = $( '#timezone' ).serialize(); - $.post( OC.filePath('calendar', 'ajax', 'settimezone.php'), post, function(data){ + $.post( OC.filePath('calendar', 'ajax/settings', 'settimezone.php'), post, function(data){ //OC.msg.finishedSaving('#calendar .msg', data); }); return false; @@ -11,7 +11,7 @@ $(document).ready(function(){ $('#timezone').chosen(); $('#timeformat').change( function(){ var data = $('#timeformat').serialize(); - $.post( OC.filePath('calendar', 'ajax', 'settimeformat.php'), data, function(data){ + $.post( OC.filePath('calendar', 'ajax/settings', 'settimeformat.php'), data, function(data){ if(data == 'error'){ console.log('saving timeformat failed'); } @@ -19,15 +19,15 @@ $(document).ready(function(){ }); $('#timezonedetection').change( function(){ var post = $('#timezonedetection').serialize(); - $.post( OC.filePath('calendar', 'ajax', 'timezonedetection.php'), post, function(data){ + $.post( OC.filePath('calendar', 'ajax/settings', 'timezonedetection.php'), post, function(data){ }); }); - $.getJSON(OC.filePath('calendar', 'ajax', 'timeformat.php'), function(jsondata, status) { + $.getJSON(OC.filePath('calendar', 'ajax/settings', 'timeformat.php'), function(jsondata, status) { $('#' + jsondata.timeformat).attr('selected',true); $('#timeformat').chosen(); }); - $.getJSON(OC.filePath('calendar', 'ajax', 'gettimezonedetection.php'), function(jsondata, status){ + $.getJSON(OC.filePath('calendar', 'ajax/settings', 'gettimezonedetection.php'), function(jsondata, status){ if(jsondata.detection == 'true'){ $('#timezonedetection').attr('checked', 'checked'); } -- GitLab From 548a2e6263121b63102bffb8e2558763a9234eba Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:28:20 +0100 Subject: [PATCH 027/430] add readonly calendar to the eventsources --- apps/calendar/index.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/calendar/index.php b/apps/calendar/index.php index 3a7d09c98a8..9f8a4955791 100644 --- a/apps/calendar/index.php +++ b/apps/calendar/index.php @@ -19,7 +19,8 @@ $eventSources = array(); foreach($calendars as $calendar){ $eventSources[] = OC_Calendar_Calendar::getEventSourceInfo($calendar); } -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'false'); +$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_readwrite', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); +$eventSources[] = array('url' => 'ajax/events.php?calendar_id=calendar_readonly, 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); //Fix currentview for fullcalendar if(OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'currentview', 'month') == "oneweekview"){ OC_Preferences::setValue(OC_USER::getUser(), "calendar", "currentview", "agendaWeek"); -- GitLab From 619c62e681307b769af4aca56acb117de9768995 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:31:41 +0100 Subject: [PATCH 028/430] change parameter names for shared calendars --- apps/calendar/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/index.php b/apps/calendar/index.php index 9f8a4955791..117272ebc4c 100644 --- a/apps/calendar/index.php +++ b/apps/calendar/index.php @@ -19,8 +19,8 @@ $eventSources = array(); foreach($calendars as $calendar){ $eventSources[] = OC_Calendar_Calendar::getEventSourceInfo($calendar); } -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_readwrite', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=calendar_readonly, 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); +$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_rw', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); +$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_r, 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); //Fix currentview for fullcalendar if(OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'currentview', 'month') == "oneweekview"){ OC_Preferences::setValue(OC_USER::getUser(), "calendar", "currentview", "agendaWeek"); -- GitLab From ec7ed3c88228063af3221ccbdfe9add28eac0422 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:35:19 +0100 Subject: [PATCH 029/430] add rw and r to events.php --- apps/calendar/ajax/events.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 96ee6775f7f..1747b2ac1a8 100755 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -13,8 +13,8 @@ OC_JSON::checkAppEnabled('calendar'); $start = DateTime::createFromFormat('U', $_GET['start']); $end = DateTime::createFromFormat('U', $_GET['end']); -if($_GET['calendar_id'] == 'shared'){ - $calendars = OC_Calendar_Share::allSharedwithuser(OC_USER::getUser(), OC_Calendar_Share::CALENDAR, 1); +if($_GET['calendar_id'] == 'shared_rw' || $_GET['calendar_id'] == 'shared_r'){ + $calendars = OC_Calendar_Share::allSharedwithuser(OC_USER::getUser(), OC_Calendar_Share::CALENDAR, 1, ($_GET['calendar_id'] == 'shared_rw')?'rw':'r'); $events = array(); foreach($calendars as $calendar){ $calendarevents = OC_Calendar_Object::allInPeriod($calendar['calendarid'], $start, $end); @@ -80,4 +80,4 @@ foreach($events as $event){ } } OC_JSON::encodedPrint($return); -?> \ No newline at end of file +?> -- GitLab From a069d83f4438ddbbde05bc80f9790be7b0781957 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:46:10 +0100 Subject: [PATCH 030/430] fix unexspected T-String in calendars index.php --- apps/calendar/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/calendar/index.php b/apps/calendar/index.php index 117272ebc4c..e3f108afc0e 100644 --- a/apps/calendar/index.php +++ b/apps/calendar/index.php @@ -20,7 +20,7 @@ foreach($calendars as $calendar){ $eventSources[] = OC_Calendar_Calendar::getEventSourceInfo($calendar); } $eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_rw', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_r, 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); +$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_r', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); //Fix currentview for fullcalendar if(OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'currentview', 'month') == "oneweekview"){ OC_Preferences::setValue(OC_USER::getUser(), "calendar", "currentview", "agendaWeek"); -- GitLab From 0ae2e250f5179991b58c2ebff94e206e5a628e73 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 20 Feb 2012 11:52:19 +0100 Subject: [PATCH 031/430] change pathes in calendar/templates/* files to make them work with the new folder structure in /calendar/ajax --- apps/calendar/templates/part.editevent.php | 2 +- apps/calendar/templates/part.newevent.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/templates/part.editevent.php b/apps/calendar/templates/part.editevent.php index b3acfc4a072..7631d298bef 100644 --- a/apps/calendar/templates/part.editevent.php +++ b/apps/calendar/templates/part.editevent.php @@ -5,7 +5,7 @@ inc("part.eventform"); ?>
      - " onclick="Calendar.UI.validateEventForm('ajax/editevent.php');"> + " onclick="Calendar.UI.validateEventForm('ajax/events/edit.php');"> " onclick="Calendar.UI.submitDeleteEventForm('ajax/deleteevent.php');"> " onclick="window.location='export.php?eventid=';"> diff --git a/apps/calendar/templates/part.newevent.php b/apps/calendar/templates/part.newevent.php index b1e2a5eab84..85cce802876 100644 --- a/apps/calendar/templates/part.newevent.php +++ b/apps/calendar/templates/part.newevent.php @@ -3,7 +3,7 @@ inc("part.eventform"); ?>
      - " onclick="Calendar.UI.validateEventForm('ajax/newevent.php');"> + " onclick="Calendar.UI.validateEventForm('ajax/events/new.php');"> -- GitLab From 70a369e16d9499ed76e3bf18713beb0176a528fd Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 21 Feb 2012 19:16:14 +0100 Subject: [PATCH 032/430] change links in the event form for the new ajax folders --- apps/calendar/templates/part.editevent.php | 4 ++-- apps/calendar/templates/part.newevent.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/calendar/templates/part.editevent.php b/apps/calendar/templates/part.editevent.php index 7631d298bef..6e319e1b4e0 100644 --- a/apps/calendar/templates/part.editevent.php +++ b/apps/calendar/templates/part.editevent.php @@ -5,8 +5,8 @@ inc("part.eventform"); ?>
      - " onclick="Calendar.UI.validateEventForm('ajax/events/edit.php');"> - " onclick="Calendar.UI.submitDeleteEventForm('ajax/deleteevent.php');"> + " onclick="Calendar.UI.validateEventForm('ajax/event/edit.php');"> + " onclick="Calendar.UI.submitDeleteEventForm('ajax/event/delete.php');"> " onclick="window.location='export.php?eventid=';"> diff --git a/apps/calendar/templates/part.newevent.php b/apps/calendar/templates/part.newevent.php index 85cce802876..11416260344 100644 --- a/apps/calendar/templates/part.newevent.php +++ b/apps/calendar/templates/part.newevent.php @@ -3,7 +3,7 @@ inc("part.eventform"); ?>
      - " onclick="Calendar.UI.validateEventForm('ajax/events/new.php');"> + " onclick="Calendar.UI.validateEventForm('ajax/event/new.php');"> -- GitLab From 236d2aa5b8d1cf7700d2996b11ec8e3bd4c153c3 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 21 Feb 2012 19:42:48 +0100 Subject: [PATCH 033/430] rename updatecalendar to update --- apps/calendar/ajax/calendar/{updatecalendar.php => update.php} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename apps/calendar/ajax/calendar/{updatecalendar.php => update.php} (100%) diff --git a/apps/calendar/ajax/calendar/updatecalendar.php b/apps/calendar/ajax/calendar/update.php similarity index 100% rename from apps/calendar/ajax/calendar/updatecalendar.php rename to apps/calendar/ajax/calendar/update.php -- GitLab From 3d8d6d718b65a972648ce7678cda13b2e1117272 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 21 Feb 2012 20:10:52 +0100 Subject: [PATCH 034/430] add 'permissions' as a sql condition in allSharedwithuser --- apps/calendar/lib/share.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index d66095b9771..be2b440c647 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -17,7 +17,7 @@ class OC_Calendar_Share{ * @param: (string) $type - use const self::CALENDAR or self::EVENT * @return: (array) $return - information about calendars */ - public static function allSharedwithuser($userid, $type, $active=null){ + public static function allSharedwithuser($userid, $type, $active=null, $permission=null){ $group_where = ''; $groups = OC_Group::getUserGroups($userid); $i = 0; @@ -30,7 +30,12 @@ class OC_Calendar_Share{ $group_where .= ' (share = \'' . $group . '\' AND sharetype = \'group\') '; $i++; } - $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = \'user\') ' . $group_where . ') AND owner <> ?' . ((!is_null($active) && $active)?' AND active = 1)':')')); + $permission_where = ''; + if(!is_null($permission)){ + $permission_where = 'AND permissions = '; + $permission_where .= ($permission=='rw')?'1':'0'; + } + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = \'user\') ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . ((!is_null($active) && $active)?' AND active = 1)':')')); $result = $stmt->execute(array($userid, $userid)); $return = array(); while( $row = $result->fetchRow()){ -- GitLab From d20b8399c395605da8a5c908c21963f1f4bdca97 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 22 Feb 2012 10:20:58 +0100 Subject: [PATCH 035/430] clean up sql commands in OC_Calendar_Share --- apps/calendar/lib/share.php | 54 ++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index be2b440c647..621ff8ce217 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -18,24 +18,10 @@ class OC_Calendar_Share{ * @return: (array) $return - information about calendars */ public static function allSharedwithuser($userid, $type, $active=null, $permission=null){ - $group_where = ''; - $groups = OC_Group::getUserGroups($userid); - $i = 0; - foreach($groups as $group){ - if($i == 0){ - $group_where = 'OR ('; - }else{ - $group_where .= ' OR '; - } - $group_where .= ' (share = \'' . $group . '\' AND sharetype = \'group\') '; - $i++; - } - $permission_where = ''; - if(!is_null($permission)){ - $permission_where = 'AND permissions = '; - $permission_where .= ($permission=='rw')?'1':'0'; - } - $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = \'user\') ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . ((!is_null($active) && $active)?' AND active = 1)':')')); + $group_where = self::group_sql(OC_Group::getUserGroups($userid)); + $permission_where = self::permission_sql($permission); + $active_where = self::active_sql($active); + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . $active_where . ')'); $result = $stmt->execute(array($userid, $userid)); $return = array(); while( $row = $result->fetchRow()){ @@ -157,7 +143,7 @@ class OC_Calendar_Share{ * @param: (string) $type - use const self::CALENDAR or self::EVENT * @return (bool) */ - private static function is_already_shared($owner, $share, $sharetype, $id, $type){ + public static function is_already_shared($owner, $share, $sharetype, $id, $type){ $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE owner = ? AND share = ? AND sharetype = ? AND ' . $type . 'id = ?'); $result = $stmt->execute(array($owner, $share, $sharetype, $id)); if($result->numRows() > 0){ @@ -165,4 +151,34 @@ class OC_Calendar_Share{ } return false; } + private static function group_sql($groups){ + $group_where = ''; + $i = 0; + foreach($groups as $group){ + if($i == 0){ + $group_where = 'OR ('; + }else{ + $group_where .= ' OR '; + } + $group_where .= ' (share = "' . $group . '" AND sharetype = "group") '; + $i++; + } + return $group_where; + } + private static function permission_sql($permission = null){ + $permission_where = ''; + if(!is_null($permission)){ + $permission_where = 'AND permissions = '; + $permission_where .= ($permission=='rw')?'1':'0'; + } + return $permission_where; + } + private static function active_sql($active = null){ + $active_where = ''; + if(!is_null($active)){ + $active_where = 'AND active = '; + $active_where .= (!is_null($active) && $active)?'1':'0'; + } + return $active_where; + } } \ No newline at end of file -- GitLab From 48f42176cdc1d75f2b9cd7b5c6d0cc4ee9050ced Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 22 Feb 2012 10:41:16 +0100 Subject: [PATCH 036/430] add is_editing_allowed function to OC_Calendar_Share --- apps/calendar/lib/share.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index 621ff8ce217..a5ca0a6e738 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -181,4 +181,21 @@ class OC_Calendar_Share{ } return $active_where; } + /* + * @brief: checks the permission for editing an event + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (bool) + */ + public static function is_editing_allowed($share, $id, $type){ + $group_where = self::group_sql(OC_Group::getUserGroups($share)); + $permission_where = self::permission_sql('rw'); + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') ' . $permission_where . ')'); + $result = $stmt->execute(array($share)); + if($result->numRows() == 1){ + return true; + } + return false; + } } \ No newline at end of file -- GitLab From 0ae088a50a42fa73b2afb87d0fe80dea2129c430 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 22 Feb 2012 10:42:01 +0100 Subject: [PATCH 037/430] add getowner function to OC_Calendar_Object --- apps/calendar/lib/object.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/calendar/lib/object.php b/apps/calendar/lib/object.php index cbb1badf802..a7ee5bd1081 100644 --- a/apps/calendar/lib/object.php +++ b/apps/calendar/lib/object.php @@ -816,4 +816,9 @@ class OC_Calendar_Object{ return $vcalendar; } + public static function getowner($id){ + $event = self::find($id); + $cal = OC_Calendar_Calendar::find($event['calendarid']); + return $cal['userid']; + } } \ No newline at end of file -- GitLab From cff0ac2bf99c9655f0ff792ec16bc0c624b07194 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 22 Feb 2012 10:42:33 +0100 Subject: [PATCH 038/430] better permission check in resize.php --- apps/calendar/ajax/event/resize.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/calendar/ajax/event/resize.php b/apps/calendar/ajax/event/resize.php index aa2d420e77d..1136273b706 100644 --- a/apps/calendar/ajax/event/resize.php +++ b/apps/calendar/ajax/event/resize.php @@ -10,6 +10,11 @@ OC_JSON::checkLoggedIn(); $id = $_POST['id']; +if(!OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::EVENT) && OC_Calendar_Object::getowner($id) != OC_User::getUser()){ + OC_JSON::error(array('message'=>'permissiondenied')); + exit; +} + $vcalendar = OC_Calendar_App::getVCalendar($id); $vevent = $vcalendar->VEVENT; -- GitLab From 9460c9e907f1dd80e4978e23911975bc775e7260 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 22 Feb 2012 11:53:28 +0100 Subject: [PATCH 039/430] remove old import.php --- apps/calendar/import.php | 120 --------------------------------------- 1 file changed, 120 deletions(-) delete mode 100644 apps/calendar/import.php diff --git a/apps/calendar/import.php b/apps/calendar/import.php deleted file mode 100644 index b1c6f91df84..00000000000 --- a/apps/calendar/import.php +++ /dev/null @@ -1,120 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -//check for calendar rights or create new one -ob_start(); -require_once ('../../lib/base.php'); -OC_JSON::checkLoggedIn(); -OC_Util::checkAppEnabled('calendar'); -$nl = "\n"; -$progressfile = 'import_tmp/' . md5(session_id()) . '.txt'; -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '10'); - fclose($progressfopen); -} -$file = OC_Filesystem::file_get_contents($_POST['path'] . '/' . $_POST['file']); -if($_POST['method'] == 'new'){ - $id = OC_Calendar_Calendar::addCalendar(OC_User::getUser(), $_POST['calname']); - OC_Calendar_Calendar::setCalendarActive($id, 1); -}else{ - $calendar = OC_Calendar_App::getCalendar($_POST['id']); - if($calendar['userid'] != OC_USER::getUser()){ - OC_JSON::error(); - exit(); - } - $id = $_POST['id']; -} -//analyse the calendar file -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '20'); - fclose($progressfopen); -} -$searchfor = array('VEVENT', 'VTODO', 'VJOURNAL'); -$parts = $searchfor; -$filearr = explode($nl, $file); -$inelement = false; -$parts = array(); -$i = 0; -foreach($filearr as $line){ - foreach($searchfor as $search){ - if(substr_count($line, $search) == 1){ - list($attr, $val) = explode(':', $line); - if($attr == 'BEGIN'){ - $parts[]['begin'] = $i; - $inelement = true; - } - if($attr == 'END'){ - $parts[count($parts) - 1]['end'] = $i; - $inelement = false; - } - } - } - $i++; -} -//import the calendar -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '40'); - fclose($progressfopen); -} -$start = ''; -for ($i = 0; $i < $parts[0]['begin']; $i++) { - if($i == 0){ - $start = $filearr[0]; - }else{ - $start .= $nl . $filearr[$i]; - } -} -$end = ''; -for($i = $parts[count($parts) - 1]['end'] + 1;$i <= count($filearr) - 1; $i++){ - if($i == $parts[count($parts) - 1]['end'] + 1){ - $end = $filearr[$parts[count($parts) - 1]['end'] + 1]; - }else{ - $end .= $nl . $filearr[$i]; - } -} -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '50'); - fclose($progressfopen); -} -$importready = array(); -foreach($parts as $part){ - for($i = $part['begin']; $i <= $part['end'];$i++){ - if($i == $part['begin']){ - $content = $filearr[$i]; - }else{ - $content .= $nl . $filearr[$i]; - } - } - $importready[] = $start . $nl . $content . $nl . $end; -} -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '70'); - fclose($progressfopen); -} -if(count($parts) == 1){ - OC_Calendar_Object::add($id, $file); -}else{ - foreach($importready as $import){ - OC_Calendar_Object::add($id, $import); - } -} -//done the import -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '100'); - fclose($progressfopen); -} -sleep(3); -if(is_writable('import_tmp/')){ - unlink($progressfile); -} -OC_JSON::success(); \ No newline at end of file -- GitLab From 95fe15991429f915dbb66be53562f9f540a8b1be Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 23 Feb 2012 17:20:03 +0100 Subject: [PATCH 040/430] make lib/vobject.php work with sabredav 1.6 --- lib/vobject.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/vobject.php b/lib/vobject.php index e3479fc6d36..2b1f6534cc4 100644 --- a/lib/vobject.php +++ b/lib/vobject.php @@ -41,7 +41,7 @@ class OC_VObject{ */ public static function parse($data){ try { - Sabre_VObject_Reader::$elementMap['LAST-MODIFIED'] = 'Sabre_VObject_Element_DateTime'; + Sabre_VObject_Property::$classMap['LAST-MODIFIED'] = 'Sabre_VObject_Element_DateTime'; $vobject = Sabre_VObject_Reader::read($data); if ($vobject instanceof Sabre_VObject_Component){ $vobject = new OC_VObject($vobject); -- GitLab From 1d1dfcbc1a528314b39322d0b8145e05072cd5ff Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Fri, 24 Feb 2012 22:20:40 +0100 Subject: [PATCH 041/430] replace Sabre_VObject_Element_DateTime with Sabre_VObject_Property_DateTime --- apps/calendar/ajax/event/edit.form.php | 6 +++--- apps/calendar/ajax/event/move.php | 12 ++++++------ apps/calendar/ajax/event/resize.php | 4 ++-- apps/calendar/ajax/events.php | 2 +- apps/calendar/lib/object.php | 18 +++++++++--------- apps/calendar/lib/search.php | 2 +- lib/vobject.php | 6 +++--- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/apps/calendar/ajax/event/edit.form.php b/apps/calendar/ajax/event/edit.form.php index 837edbbbf05..7371577dcfe 100644 --- a/apps/calendar/ajax/event/edit.form.php +++ b/apps/calendar/ajax/event/edit.form.php @@ -21,15 +21,15 @@ $vevent = $object->VEVENT; $dtstart = $vevent->DTSTART; $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); switch($dtstart->getDateType()) { - case Sabre_VObject_Element_DateTime::LOCALTZ: - case Sabre_VObject_Element_DateTime::LOCAL: + case Sabre_VObject_Property_DateTime::LOCALTZ: + case Sabre_VObject_Property_DateTime::LOCAL: $startdate = $dtstart->getDateTime()->format('d-m-Y'); $starttime = $dtstart->getDateTime()->format('H:i'); $enddate = $dtend->getDateTime()->format('d-m-Y'); $endtime = $dtend->getDateTime()->format('H:i'); $allday = false; break; - case Sabre_VObject_Element_DateTime::DATE: + case Sabre_VObject_Property_DateTime::DATE: $startdate = $dtstart->getDateTime()->format('d-m-Y'); $starttime = ''; $dtend->getDateTime()->modify('-1 day'); diff --git a/apps/calendar/ajax/event/move.php b/apps/calendar/ajax/event/move.php index 8150fdbaa32..37420e2a876 100644 --- a/apps/calendar/ajax/event/move.php +++ b/apps/calendar/ajax/event/move.php @@ -24,19 +24,19 @@ $dtstart = $vevent->DTSTART; $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); $start_type = $dtstart->getDateType(); $end_type = $dtend->getDateType(); -if ($allday && $start_type != Sabre_VObject_Element_DateTime::DATE){ - $start_type = $end_type = Sabre_VObject_Element_DateTime::DATE; +if ($allday && $start_type != Sabre_VObject_Property_DateTime::DATE){ + $start_type = $end_type = Sabre_VObject_Property_DateTime::DATE; $dtend->setDateTime($dtend->getDateTime()->modify('+1 day'), $end_type); } -if (!$allday && $start_type == Sabre_VObject_Element_DateTime::DATE){ - $start_type = $end_type = Sabre_VObject_Element_DateTime::LOCALTZ; +if (!$allday && $start_type == Sabre_VObject_Property_DateTime::DATE){ + $start_type = $end_type = Sabre_VObject_Property_DateTime::LOCALTZ; } $dtstart->setDateTime($dtstart->getDateTime()->add($delta), $start_type); $dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); unset($vevent->DURATION); -$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); -$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); +$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Property_DateTime::UTC); +$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Property_DateTime::UTC); $result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); $lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); diff --git a/apps/calendar/ajax/event/resize.php b/apps/calendar/ajax/event/resize.php index aa2d420e77d..a8d8f49ae0a 100644 --- a/apps/calendar/ajax/event/resize.php +++ b/apps/calendar/ajax/event/resize.php @@ -24,8 +24,8 @@ $end_type = $dtend->getDateType(); $dtend->setDateTime($dtend->getDateTime()->add($delta), $end_type); unset($vevent->DURATION); -$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); -$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); +$vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Property_DateTime::UTC); +$vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Property_DateTime::UTC); $result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); $lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 1436f634316..6ea556a7abf 100755 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -47,7 +47,7 @@ foreach($events as $event){ $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); $start_dt = $dtstart->getDateTime(); $end_dt = $dtend->getDateTime(); - if ($dtstart->getDateType() == Sabre_VObject_Element_DateTime::DATE){ + if ($dtstart->getDateType() == Sabre_VObject_Property_DateTime::DATE){ $return_event['allDay'] = true; }else{ $return_event['allDay'] = false; diff --git a/apps/calendar/lib/object.php b/apps/calendar/lib/object.php index 230c610d35a..0b2cbb38157 100644 --- a/apps/calendar/lib/object.php +++ b/apps/calendar/lib/object.php @@ -625,7 +625,7 @@ class OC_Calendar_Object{ $vevent = new OC_VObject('VEVENT'); $vcalendar->add($vevent); - $vevent->setDateTime('CREATED', 'now', Sabre_VObject_Element_DateTime::UTC); + $vevent->setDateTime('CREATED', 'now', Sabre_VObject_Property_DateTime::UTC); $vevent->setUID(); return self::updateVCalendarFromRequest($request, $vcalendar); @@ -786,24 +786,24 @@ class OC_Calendar_Object{ } - $vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Element_DateTime::UTC); - $vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); + $vevent->setDateTime('LAST-MODIFIED', 'now', Sabre_VObject_Property_DateTime::UTC); + $vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Property_DateTime::UTC); $vevent->setString('SUMMARY', $title); - $dtstart = new Sabre_VObject_Element_DateTime('DTSTART'); - $dtend = new Sabre_VObject_Element_DateTime('DTEND'); + $dtstart = new Sabre_VObject_Property_DateTime('DTSTART'); + $dtend = new Sabre_VObject_Property_DateTime('DTEND'); if($allday){ $start = new DateTime($from); $end = new DateTime($to.' +1 day'); - $vevent->setDateTime('DTSTART', $start, Sabre_VObject_Element_DateTime::DATE); - $vevent->setDateTime('DTEND', $end, Sabre_VObject_Element_DateTime::DATE); + $vevent->setDateTime('DTSTART', $start, Sabre_VObject_Property_DateTime::DATE); + $vevent->setDateTime('DTEND', $end, Sabre_VObject_Property_DateTime::DATE); }else{ $timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); $timezone = new DateTimeZone($timezone); $start = new DateTime($from.' '.$fromtime, $timezone); $end = new DateTime($to.' '.$totime, $timezone); - $vevent->setDateTime('DTSTART', $start, Sabre_VObject_Element_DateTime::LOCALTZ); - $vevent->setDateTime('DTEND', $end, Sabre_VObject_Element_DateTime::LOCALTZ); + $vevent->setDateTime('DTSTART', $start, Sabre_VObject_Property_DateTime::LOCALTZ); + $vevent->setDateTime('DTEND', $end, Sabre_VObject_Property_DateTime::LOCALTZ); } unset($vevent->DURATION); diff --git a/apps/calendar/lib/search.php b/apps/calendar/lib/search.php index 0016751a66a..79c8dba0f4d 100644 --- a/apps/calendar/lib/search.php +++ b/apps/calendar/lib/search.php @@ -26,7 +26,7 @@ class OC_Search_Provider_Calendar extends OC_Search_Provider{ $start_dt->setTimezone(new DateTimeZone($user_timezone)); $end_dt = $dtend->getDateTime(); $end_dt->setTimezone(new DateTimeZone($user_timezone)); - if ($dtstart->getDateType() == Sabre_VObject_Element_DateTime::DATE){ + if ($dtstart->getDateType() == Sabre_VObject_Property_DateTime::DATE){ $end_dt->modify('-1 sec'); if($start_dt->format('d.m.Y') != $end_dt->format('d.m.Y')){ $info = $l->t('Date') . ': ' . $start_dt->format('d.m.Y') . ' - ' . $end_dt->format('d.m.Y'); diff --git a/lib/vobject.php b/lib/vobject.php index 2b1f6534cc4..ec80e1d605a 100644 --- a/lib/vobject.php +++ b/lib/vobject.php @@ -41,7 +41,7 @@ class OC_VObject{ */ public static function parse($data){ try { - Sabre_VObject_Property::$classMap['LAST-MODIFIED'] = 'Sabre_VObject_Element_DateTime'; + Sabre_VObject_Property::$classMap['LAST-MODIFIED'] = 'Sabre_VObject_Property_DateTime'; $vobject = Sabre_VObject_Reader::read($data); if ($vobject instanceof Sabre_VObject_Component){ $vobject = new OC_VObject($vobject); @@ -150,12 +150,12 @@ class OC_VObject{ * @param int $dateType * @return void */ - public function setDateTime($name, $datetime, $dateType=Sabre_VObject_Element_DateTime::LOCALTZ){ + public function setDateTime($name, $datetime, $dateType=Sabre_VObject_Property_DateTime::LOCALTZ){ if ($datetime == 'now'){ $datetime = new DateTime(); } if ($datetime instanceof DateTime){ - $datetime_element = new Sabre_VObject_Element_DateTime($name); + $datetime_element = new Sabre_VObject_Property_DateTime($name); $datetime_element->setDateTime($datetime, $dateType); $this->vobject->__set($name, $datetime_element); }else{ -- GitLab From cc1585238641a78ff3a0b311a29b92070e3766a7 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 25 Feb 2012 09:35:35 +0100 Subject: [PATCH 042/430] replace Sabre_DAV_Exception_FileNotFound with Sabre_DAV_Exception_NotFound --- lib/connector/sabre/directory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/connector/sabre/directory.php b/lib/connector/sabre/directory.php index bb03851e39d..d1cb55ce130 100644 --- a/lib/connector/sabre/directory.php +++ b/lib/connector/sabre/directory.php @@ -50,7 +50,7 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa $path = $this->path . '/' . $name; - if (!OC_Filesystem::file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); + if (!OC_Filesystem::file_exists($path)) throw new Sabre_DAV_Exception_NotFound('File with name ' . $path . ' could not be located'); if (OC_Filesystem::is_dir($path)) { -- GitLab From 0d2f1688e4ade41b2937572b28f711186660bd9e Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 25 Feb 2012 16:26:47 +0100 Subject: [PATCH 043/430] add empty methods updatePrincipal and searchPrincipals and change method getPrincipalByPath to work with sabredav 1.6 --- lib/connector/sabre/principal.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/connector/sabre/principal.php b/lib/connector/sabre/principal.php index 72e180c65c0..6cfb3449e1a 100644 --- a/lib/connector/sabre/principal.php +++ b/lib/connector/sabre/principal.php @@ -90,7 +90,7 @@ class OC_Connector_Sabre_Principal implements Sabre_DAVACL_IPrincipalBackend { * @return array */ public function getPrincipalByPath($path) { - list($prefix,$name) = Sabre_DAV_URLUtil::splitPath($path); + list($prefix,$name) = explode('/', $path); if ($prefix == 'principals' && OC_User::userExists($name)) { return array( @@ -159,4 +159,6 @@ class OC_Connector_Sabre_Principal implements Sabre_DAVACL_IPrincipalBackend { public function setGroupMemberSet($principal, array $members) { throw new Sabre_DAV_Exception('Setting members of the group is not supported yet'); } + function updatePrincipal($path, $mutations){return 0;} + function searchPrincipals($prefixPath, array $searchProperties){return 0;} } -- GitLab From 45c9f1978ec6221b7f302f0722b0e6795fa91804 Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Fri, 16 Mar 2012 00:03:23 +0100 Subject: [PATCH 044/430] Initial version of drag&drop file upload support --- files/index.php | 1 + files/js/files.js | 83 ++++ files/js/jquery.fileupload.js | 866 ++++++++++++++++++++++++++++++++++ 3 files changed, 950 insertions(+) create mode 100644 files/js/jquery.fileupload.js diff --git a/files/index.php b/files/index.php index 79261e495be..a625d3cdf9f 100644 --- a/files/index.php +++ b/files/index.php @@ -30,6 +30,7 @@ OC_Util::checkLoggedIn(); // Load the files we need OC_Util::addStyle( "files", "files" ); +OC_Util::addScript( "files", "jquery.fileupload" ); OC_Util::addScript( "files", "files" ); OC_Util::addScript( 'files', 'filelist' ); OC_Util::addScript( 'files', 'fileactions' ); diff --git a/files/js/files.js b/files/js/files.js index a678e12cc2d..a129b853b67 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -150,6 +150,7 @@ $(document).ready(function() { return false; }); + /* $('.file_upload_start').live('change',function(){ var form=$(this).closest('form'); var that=this; @@ -228,6 +229,88 @@ $(document).ready(function() { form.hide(); } }); +*/ + + // drag&drop support using jquery.fileupload + $(function() { + $('.file_upload_start').fileupload({ + //dropZone: $('#content'), // restrict dropZone to content div + add: function(e, data) { + var files = data.files; + var totalSize=0; + if(files){ + for(var i=0;i$('#max_upload').val()){ + $( "#uploadsize-message" ).dialog({ + modal: true, + buttons: { + Close: function() { + $( this ).dialog( "close" ); + } + } + }); + }else{ + data.submit(); + var date=new Date(); + if(files){ + for(var i=0;i0){ + var size=files[i].size; + }else{ + var size=t('files','Pending'); + } + if(files){ + FileList.addFile(files[i].name,size,date,true); + } + } + }else{ + var filename=this.value.split('\\').pop(); //ie prepends C:\fakepath\ in front of the filename + FileList.addFile(filename,'Pending',date,true); + } + } + }, + done: function(e, data) { + var response=jQuery.parseJSON(data.result); + if(response[0] != undefined && response[0].status == 'success') { + for(var i=0;i0){ + var size=file.size; + }else{ + var size=t('files','Pending'); + } + $('tr').filterAttr('data-file',file.name).data('mime',file.mime); + if(size=='Pending'){ + $('tr').filterAttr('data-file',file.name).find('td.filesize').text(file.size); + } + FileList.loadingDone(file.name); + } + } else { + $('#notification').text(t('files', response.data.message)); + $('#notification').fadeIn(); + $('#fileList > tr').not('[data-mime]').fadeOut(); + $('#fileList > tr').not('[data-mime]').remove(); + } + }, + fail: function(e, data) { + console.debug("Fail", data); + // TODO: cancel upload & display error notification + }, + progress: function(e, data) { + } + }) + }); + + //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used) if(navigator.userAgent.search(/konqueror/i)==-1){ diff --git a/files/js/jquery.fileupload.js b/files/js/jquery.fileupload.js new file mode 100644 index 00000000000..a89e9dc2c44 --- /dev/null +++ b/files/js/jquery.fileupload.js @@ -0,0 +1,866 @@ +/* + * jQuery File Upload Plugin 5.9 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/*jslint nomen: true, unparam: true, regexp: true */ +/*global define, window, document, Blob, FormData, location */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + 'jquery.ui.widget' + ], factory); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // The FileReader API is not actually used, but works as feature detection, + // as e.g. Safari supports XHR file uploads via the FormData API, + // but not non-multipart XHR file uploads: + $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); + $.support.xhrFormDataFileUpload = !!window.FormData; + + // The fileupload widget listens for change events on file input fields defined + // via fileInput setting and paste or drop events of the given dropZone. + // In addition to the default jQuery Widget methods, the fileupload widget + // exposes the "add" and "send" methods, to add or directly send files using + // the fileupload API. + // By default, files added via file input selection, paste, drag & drop or + // "add" method are uploaded immediately, but it is possible to override + // the "add" callback option to queue file uploads. + $.widget('blueimp.fileupload', { + + options: { + // The namespace used for event handler binding on the dropZone and + // fileInput collections. + // If not set, the name of the widget ("fileupload") is used. + namespace: undefined, + // The drop target collection, by the default the complete document. + // Set to null or an empty collection to disable drag & drop support: + dropZone: $(document), + // The file input field collection, that is listened for change events. + // If undefined, it is set to the file input fields inside + // of the widget element on plugin initialization. + // Set to null or an empty collection to disable the change listener. + fileInput: undefined, + // By default, the file input field is replaced with a clone after + // each input field change event. This is required for iframe transport + // queues and allows change events to be fired for the same file + // selection, but can be disabled by setting the following option to false: + replaceFileInput: true, + // The parameter name for the file form data (the request argument name). + // If undefined or empty, the name property of the file input field is + // used, or "files[]" if the file input name property is also empty: + paramName: undefined, + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads: true, + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads: undefined, + // Set the following option to true to issue all file upload requests + // in a sequential order: + sequentialUploads: false, + // To limit the number of concurrent uploads, + // set the following option to an integer greater than 0: + limitConcurrentUploads: undefined, + // Set the following option to true to force iframe transport uploads: + forceIframeTransport: false, + // Set the following option to the location of a redirect url on the + // origin server, for cross-domain iframe transport uploads: + redirect: undefined, + // The parameter name for the redirect url, sent as part of the form + // data and set to 'redirect' if this option is empty: + redirectParamName: undefined, + // Set the following option to the location of a postMessage window, + // to enable postMessage transport uploads: + postMessage: undefined, + // By default, XHR file uploads are sent as multipart/form-data. + // The iframe transport is always using multipart/form-data. + // Set to false to enable non-multipart XHR uploads: + multipart: true, + // To upload large files in smaller chunks, set the following option + // to a preferred maximum chunk size. If set to 0, null or undefined, + // or the browser does not support the required Blob API, files will + // be uploaded as a whole. + maxChunkSize: undefined, + // When a non-multipart upload or a chunked multipart upload has been + // aborted, this option can be used to resume the upload by setting + // it to the size of the already uploaded bytes. This option is most + // useful when modifying the options object inside of the "add" or + // "send" callbacks, as the options are cloned for each file upload. + uploadedBytes: undefined, + // By default, failed (abort or error) file uploads are removed from the + // global progress calculation. Set the following option to false to + // prevent recalculating the global progress data: + recalculateProgress: true, + + // Additional form data to be sent along with the file uploads can be set + // using this option, which accepts an array of objects with name and + // value properties, a function returning such an array, a FormData + // object (for XHR file uploads), or a simple object. + // The form of the first fileInput is given as parameter to the function: + formData: function (form) { + return form.serializeArray(); + }, + + // The add callback is invoked as soon as files are added to the fileupload + // widget (via file input selection, drag & drop, paste or add API call). + // If the singleFileUploads option is enabled, this callback will be + // called once for each file in the selection for XHR file uplaods, else + // once for each file selection. + // The upload starts when the submit method is invoked on the data parameter. + // The data object contains a files property holding the added files + // and allows to override plugin options as well as define ajax settings. + // Listeners for this callback can also be bound the following way: + // .bind('fileuploadadd', func); + // data.submit() returns a Promise object and allows to attach additional + // handlers using jQuery's Deferred callbacks: + // data.submit().done(func).fail(func).always(func); + add: function (e, data) { + data.submit(); + }, + + // Other callbacks: + // Callback for the submit event of each file upload: + // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); + // Callback for the start of each file upload request: + // send: function (e, data) {}, // .bind('fileuploadsend', func); + // Callback for successful uploads: + // done: function (e, data) {}, // .bind('fileuploaddone', func); + // Callback for failed (abort or error) uploads: + // fail: function (e, data) {}, // .bind('fileuploadfail', func); + // Callback for completed (success, abort or error) requests: + // always: function (e, data) {}, // .bind('fileuploadalways', func); + // Callback for upload progress events: + // progress: function (e, data) {}, // .bind('fileuploadprogress', func); + // Callback for global upload progress events: + // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); + // Callback for uploads start, equivalent to the global ajaxStart event: + // start: function (e) {}, // .bind('fileuploadstart', func); + // Callback for uploads stop, equivalent to the global ajaxStop event: + // stop: function (e) {}, // .bind('fileuploadstop', func); + // Callback for change events of the fileInput collection: + // change: function (e, data) {}, // .bind('fileuploadchange', func); + // Callback for paste events to the dropZone collection: + // paste: function (e, data) {}, // .bind('fileuploadpaste', func); + // Callback for drop events of the dropZone collection: + // drop: function (e, data) {}, // .bind('fileuploaddrop', func); + // Callback for dragover events of the dropZone collection: + // dragover: function (e) {}, // .bind('fileuploaddragover', func); + + // The plugin options are used as settings object for the ajax calls. + // The following are jQuery ajax settings required for the file uploads: + processData: false, + contentType: false, + cache: false + }, + + // A list of options that require a refresh after assigning a new value: + _refreshOptionsList: [ + 'namespace', + 'dropZone', + 'fileInput', + 'multipart', + 'forceIframeTransport' + ], + + _isXHRUpload: function (options) { + return !options.forceIframeTransport && + ((!options.multipart && $.support.xhrFileUpload) || + $.support.xhrFormDataFileUpload); + }, + + _getFormData: function (options) { + var formData; + if (typeof options.formData === 'function') { + return options.formData(options.form); + } else if ($.isArray(options.formData)) { + return options.formData; + } else if (options.formData) { + formData = []; + $.each(options.formData, function (name, value) { + formData.push({name: name, value: value}); + }); + return formData; + } + return []; + }, + + _getTotal: function (files) { + var total = 0; + $.each(files, function (index, file) { + total += file.size || 1; + }); + return total; + }, + + _onProgress: function (e, data) { + if (e.lengthComputable) { + var total = data.total || this._getTotal(data.files), + loaded = parseInt( + e.loaded / e.total * (data.chunkSize || total), + 10 + ) + (data.uploadedBytes || 0); + this._loaded += loaded - (data.loaded || data.uploadedBytes || 0); + data.lengthComputable = true; + data.loaded = loaded; + data.total = total; + // Trigger a custom progress event with a total data property set + // to the file size(s) of the current upload and a loaded data + // property calculated accordingly: + this._trigger('progress', e, data); + // Trigger a global progress event for all current file uploads, + // including ajax calls queued for sequential file uploads: + this._trigger('progressall', e, { + lengthComputable: true, + loaded: this._loaded, + total: this._total + }); + } + }, + + _initProgressListener: function (options) { + var that = this, + xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); + // Accesss to the native XHR object is required to add event listeners + // for the upload progress event: + if (xhr.upload) { + $(xhr.upload).bind('progress', function (e) { + var oe = e.originalEvent; + // Make sure the progress event properties get copied over: + e.lengthComputable = oe.lengthComputable; + e.loaded = oe.loaded; + e.total = oe.total; + that._onProgress(e, options); + }); + options.xhr = function () { + return xhr; + }; + } + }, + + _initXHRData: function (options) { + var formData, + file = options.files[0], + // Ignore non-multipart setting if not supported: + multipart = options.multipart || !$.support.xhrFileUpload; + if (!multipart || options.blob) { + // For non-multipart uploads and chunked uploads, + // file meta data is not part of the request body, + // so we transmit this data as part of the HTTP headers. + // For cross domain requests, these headers must be allowed + // via Access-Control-Allow-Headers or removed using + // the beforeSend callback: + options.headers = $.extend(options.headers, { + 'X-File-Name': file.name, + 'X-File-Type': file.type, + 'X-File-Size': file.size + }); + if (!options.blob) { + // Non-chunked non-multipart upload: + options.contentType = file.type; + options.data = file; + } else if (!multipart) { + // Chunked non-multipart upload: + options.contentType = 'application/octet-stream'; + options.data = options.blob; + } + } + if (multipart && $.support.xhrFormDataFileUpload) { + if (options.postMessage) { + // window.postMessage does not allow sending FormData + // objects, so we just add the File/Blob objects to + // the formData array and let the postMessage window + // create the FormData object out of this array: + formData = this._getFormData(options); + if (options.blob) { + formData.push({ + name: options.paramName, + value: options.blob + }); + } else { + $.each(options.files, function (index, file) { + formData.push({ + name: options.paramName, + value: file + }); + }); + } + } else { + if (options.formData instanceof FormData) { + formData = options.formData; + } else { + formData = new FormData(); + $.each(this._getFormData(options), function (index, field) { + formData.append(field.name, field.value); + }); + } + if (options.blob) { + formData.append(options.paramName, options.blob, file.name); + } else { + $.each(options.files, function (index, file) { + // File objects are also Blob instances. + // This check allows the tests to run with + // dummy objects: + if (file instanceof Blob) { + formData.append(options.paramName, file, file.name); + } + }); + } + } + options.data = formData; + } + // Blob reference is not needed anymore, free memory: + options.blob = null; + }, + + _initIframeSettings: function (options) { + // Setting the dataType to iframe enables the iframe transport: + options.dataType = 'iframe ' + (options.dataType || ''); + // The iframe transport accepts a serialized array as form data: + options.formData = this._getFormData(options); + // Add redirect url to form data on cross-domain uploads: + if (options.redirect && $('').prop('href', options.url) + .prop('host') !== location.host) { + options.formData.push({ + name: options.redirectParamName || 'redirect', + value: options.redirect + }); + } + }, + + _initDataSettings: function (options) { + if (this._isXHRUpload(options)) { + if (!this._chunkedUpload(options, true)) { + if (!options.data) { + this._initXHRData(options); + } + this._initProgressListener(options); + } + if (options.postMessage) { + // Setting the dataType to postmessage enables the + // postMessage transport: + options.dataType = 'postmessage ' + (options.dataType || ''); + } + } else { + this._initIframeSettings(options, 'iframe'); + } + }, + + _initFormSettings: function (options) { + // Retrieve missing options from the input field and the + // associated form, if available: + if (!options.form || !options.form.length) { + options.form = $(options.fileInput.prop('form')); + } + if (!options.paramName) { + options.paramName = options.fileInput.prop('name') || + 'files[]'; + } + if (!options.url) { + options.url = options.form.prop('action') || location.href; + } + // The HTTP request method must be "POST" or "PUT": + options.type = (options.type || options.form.prop('method') || '') + .toUpperCase(); + if (options.type !== 'POST' && options.type !== 'PUT') { + options.type = 'POST'; + } + }, + + _getAJAXSettings: function (data) { + var options = $.extend({}, this.options, data); + this._initFormSettings(options); + this._initDataSettings(options); + return options; + }, + + // Maps jqXHR callbacks to the equivalent + // methods of the given Promise object: + _enhancePromise: function (promise) { + promise.success = promise.done; + promise.error = promise.fail; + promise.complete = promise.always; + return promise; + }, + + // Creates and returns a Promise object enhanced with + // the jqXHR methods abort, success, error and complete: + _getXHRPromise: function (resolveOrReject, context, args) { + var dfd = $.Deferred(), + promise = dfd.promise(); + context = context || this.options.context || promise; + if (resolveOrReject === true) { + dfd.resolveWith(context, args); + } else if (resolveOrReject === false) { + dfd.rejectWith(context, args); + } + promise.abort = dfd.promise; + return this._enhancePromise(promise); + }, + + // Uploads a file in multiple, sequential requests + // by splitting the file up in multiple blob chunks. + // If the second parameter is true, only tests if the file + // should be uploaded in chunks, but does not invoke any + // upload requests: + _chunkedUpload: function (options, testOnly) { + var that = this, + file = options.files[0], + fs = file.size, + ub = options.uploadedBytes = options.uploadedBytes || 0, + mcs = options.maxChunkSize || fs, + // Use the Blob methods with the slice implementation + // according to the W3C Blob API specification: + slice = file.webkitSlice || file.mozSlice || file.slice, + upload, + n, + jqXHR, + pipe; + if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || + options.data) { + return false; + } + if (testOnly) { + return true; + } + if (ub >= fs) { + file.error = 'uploadedBytes'; + return this._getXHRPromise( + false, + options.context, + [null, 'error', file.error] + ); + } + // n is the number of blobs to upload, + // calculated via filesize, uploaded bytes and max chunk size: + n = Math.ceil((fs - ub) / mcs); + // The chunk upload method accepting the chunk number as parameter: + upload = function (i) { + if (!i) { + return that._getXHRPromise(true, options.context); + } + // Upload the blobs in sequential order: + return upload(i -= 1).pipe(function () { + // Clone the options object for each chunk upload: + var o = $.extend({}, options); + o.blob = slice.call( + file, + ub + i * mcs, + ub + (i + 1) * mcs + ); + // Store the current chunk size, as the blob itself + // will be dereferenced after data processing: + o.chunkSize = o.blob.size; + // Process the upload data (the blob and potential form data): + that._initXHRData(o); + // Add progress listeners for this chunk upload: + that._initProgressListener(o); + jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context)) + .done(function () { + // Create a progress event if upload is done and + // no progress event has been invoked for this chunk: + if (!o.loaded) { + that._onProgress($.Event('progress', { + lengthComputable: true, + loaded: o.chunkSize, + total: o.chunkSize + }), o); + } + options.uploadedBytes = o.uploadedBytes += + o.chunkSize; + }); + return jqXHR; + }); + }; + // Return the piped Promise object, enhanced with an abort method, + // which is delegated to the jqXHR object of the current upload, + // and jqXHR callbacks mapped to the equivalent Promise methods: + pipe = upload(n); + pipe.abort = function () { + return jqXHR.abort(); + }; + return this._enhancePromise(pipe); + }, + + _beforeSend: function (e, data) { + if (this._active === 0) { + // the start callback is triggered when an upload starts + // and no other uploads are currently running, + // equivalent to the global ajaxStart event: + this._trigger('start'); + } + this._active += 1; + // Initialize the global progress values: + this._loaded += data.uploadedBytes || 0; + this._total += this._getTotal(data.files); + }, + + _onDone: function (result, textStatus, jqXHR, options) { + if (!this._isXHRUpload(options)) { + // Create a progress event for each iframe load: + this._onProgress($.Event('progress', { + lengthComputable: true, + loaded: 1, + total: 1 + }), options); + } + options.result = result; + options.textStatus = textStatus; + options.jqXHR = jqXHR; + this._trigger('done', null, options); + }, + + _onFail: function (jqXHR, textStatus, errorThrown, options) { + options.jqXHR = jqXHR; + options.textStatus = textStatus; + options.errorThrown = errorThrown; + this._trigger('fail', null, options); + if (options.recalculateProgress) { + // Remove the failed (error or abort) file upload from + // the global progress calculation: + this._loaded -= options.loaded || options.uploadedBytes || 0; + this._total -= options.total || this._getTotal(options.files); + } + }, + + _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { + this._active -= 1; + options.textStatus = textStatus; + if (jqXHRorError && jqXHRorError.always) { + options.jqXHR = jqXHRorError; + options.result = jqXHRorResult; + } else { + options.jqXHR = jqXHRorResult; + options.errorThrown = jqXHRorError; + } + this._trigger('always', null, options); + if (this._active === 0) { + // The stop callback is triggered when all uploads have + // been completed, equivalent to the global ajaxStop event: + this._trigger('stop'); + // Reset the global progress values: + this._loaded = this._total = 0; + } + }, + + _onSend: function (e, data) { + var that = this, + jqXHR, + slot, + pipe, + options = that._getAJAXSettings(data), + send = function (resolve, args) { + that._sending += 1; + jqXHR = jqXHR || ( + (resolve !== false && + that._trigger('send', e, options) !== false && + (that._chunkedUpload(options) || $.ajax(options))) || + that._getXHRPromise(false, options.context, args) + ).done(function (result, textStatus, jqXHR) { + that._onDone(result, textStatus, jqXHR, options); + }).fail(function (jqXHR, textStatus, errorThrown) { + that._onFail(jqXHR, textStatus, errorThrown, options); + }).always(function (jqXHRorResult, textStatus, jqXHRorError) { + that._sending -= 1; + that._onAlways( + jqXHRorResult, + textStatus, + jqXHRorError, + options + ); + if (options.limitConcurrentUploads && + options.limitConcurrentUploads > that._sending) { + // Start the next queued upload, + // that has not been aborted: + var nextSlot = that._slots.shift(); + while (nextSlot) { + if (!nextSlot.isRejected()) { + nextSlot.resolve(); + break; + } + nextSlot = that._slots.shift(); + } + } + }); + return jqXHR; + }; + this._beforeSend(e, options); + if (this.options.sequentialUploads || + (this.options.limitConcurrentUploads && + this.options.limitConcurrentUploads <= this._sending)) { + if (this.options.limitConcurrentUploads > 1) { + slot = $.Deferred(); + this._slots.push(slot); + pipe = slot.pipe(send); + } else { + pipe = (this._sequence = this._sequence.pipe(send, send)); + } + // Return the piped Promise object, enhanced with an abort method, + // which is delegated to the jqXHR object of the current upload, + // and jqXHR callbacks mapped to the equivalent Promise methods: + pipe.abort = function () { + var args = [undefined, 'abort', 'abort']; + if (!jqXHR) { + if (slot) { + slot.rejectWith(args); + } + return send(false, args); + } + return jqXHR.abort(); + }; + return this._enhancePromise(pipe); + } + return send(); + }, + + _onAdd: function (e, data) { + var that = this, + result = true, + options = $.extend({}, this.options, data), + limit = options.limitMultiFileUploads, + fileSet, + i; + if (!(options.singleFileUploads || limit) || + !this._isXHRUpload(options)) { + fileSet = [data.files]; + } else if (!options.singleFileUploads && limit) { + fileSet = []; + for (i = 0; i < data.files.length; i += limit) { + fileSet.push(data.files.slice(i, i + limit)); + } + } + data.originalFiles = data.files; + $.each(fileSet || data.files, function (index, element) { + var files = fileSet ? element : [element], + newData = $.extend({}, data, {files: files}); + newData.submit = function () { + newData.jqXHR = this.jqXHR = + (that._trigger('submit', e, this) !== false) && + that._onSend(e, this); + return this.jqXHR; + }; + return (result = that._trigger('add', e, newData)); + }); + return result; + }, + + // File Normalization for Gecko 1.9.1 (Firefox 3.5) support: + _normalizeFile: function (index, file) { + if (file.name === undefined && file.size === undefined) { + file.name = file.fileName; + file.size = file.fileSize; + } + }, + + _replaceFileInput: function (input) { + var inputClone = input.clone(true); + $('
      ').append(inputClone)[0].reset(); + // Detaching allows to insert the fileInput on another form + // without loosing the file input value: + input.after(inputClone).detach(); + // Avoid memory leaks with the detached file input: + $.cleanData(input.unbind('remove')); + // Replace the original file input element in the fileInput + // collection with the clone, which has been copied including + // event handlers: + this.options.fileInput = this.options.fileInput.map(function (i, el) { + if (el === input[0]) { + return inputClone[0]; + } + return el; + }); + // If the widget has been initialized on the file input itself, + // override this.element with the file input clone: + if (input[0] === this.element[0]) { + this.element = inputClone; + } + }, + + _onChange: function (e) { + var that = e.data.fileupload, + data = { + files: $.each($.makeArray(e.target.files), that._normalizeFile), + fileInput: $(e.target), + form: $(e.target.form) + }; + if (!data.files.length) { + // If the files property is not available, the browser does not + // support the File API and we add a pseudo File object with + // the input value as name with path information removed: + data.files = [{name: e.target.value.replace(/^.*\\/, '')}]; + } + if (that.options.replaceFileInput) { + that._replaceFileInput(data.fileInput); + } + if (that._trigger('change', e, data) === false || + that._onAdd(e, data) === false) { + return false; + } + }, + + _onPaste: function (e) { + var that = e.data.fileupload, + cbd = e.originalEvent.clipboardData, + items = (cbd && cbd.items) || [], + data = {files: []}; + $.each(items, function (index, item) { + var file = item.getAsFile && item.getAsFile(); + if (file) { + data.files.push(file); + } + }); + if (that._trigger('paste', e, data) === false || + that._onAdd(e, data) === false) { + return false; + } + }, + + _onDrop: function (e) { + var that = e.data.fileupload, + dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer, + data = { + files: $.each( + $.makeArray(dataTransfer && dataTransfer.files), + that._normalizeFile + ) + }; + if (that._trigger('drop', e, data) === false || + that._onAdd(e, data) === false) { + return false; + } + e.preventDefault(); + }, + + _onDragOver: function (e) { + var that = e.data.fileupload, + dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer; + if (that._trigger('dragover', e) === false) { + return false; + } + if (dataTransfer) { + dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy'; + } + e.preventDefault(); + }, + + _initEventHandlers: function () { + var ns = this.options.namespace; + if (this._isXHRUpload(this.options)) { + this.options.dropZone + .bind('dragover.' + ns, {fileupload: this}, this._onDragOver) + .bind('drop.' + ns, {fileupload: this}, this._onDrop) + .bind('paste.' + ns, {fileupload: this}, this._onPaste); + } + this.options.fileInput + .bind('change.' + ns, {fileupload: this}, this._onChange); + }, + + _destroyEventHandlers: function () { + var ns = this.options.namespace; + this.options.dropZone + .unbind('dragover.' + ns, this._onDragOver) + .unbind('drop.' + ns, this._onDrop) + .unbind('paste.' + ns, this._onPaste); + this.options.fileInput + .unbind('change.' + ns, this._onChange); + }, + + _setOption: function (key, value) { + var refresh = $.inArray(key, this._refreshOptionsList) !== -1; + if (refresh) { + this._destroyEventHandlers(); + } + $.Widget.prototype._setOption.call(this, key, value); + if (refresh) { + this._initSpecialOptions(); + this._initEventHandlers(); + } + }, + + _initSpecialOptions: function () { + var options = this.options; + if (options.fileInput === undefined) { + options.fileInput = this.element.is('input:file') ? + this.element : this.element.find('input:file'); + } else if (!(options.fileInput instanceof $)) { + options.fileInput = $(options.fileInput); + } + if (!(options.dropZone instanceof $)) { + options.dropZone = $(options.dropZone); + } + }, + + _create: function () { + var options = this.options, + dataOpts = $.extend({}, this.element.data()); + dataOpts[this.widgetName] = undefined; + $.extend(options, dataOpts); + options.namespace = options.namespace || this.widgetName; + this._initSpecialOptions(); + this._slots = []; + this._sequence = this._getXHRPromise(true); + this._sending = this._active = this._loaded = this._total = 0; + this._initEventHandlers(); + }, + + destroy: function () { + this._destroyEventHandlers(); + $.Widget.prototype.destroy.call(this); + }, + + enable: function () { + $.Widget.prototype.enable.call(this); + this._initEventHandlers(); + }, + + disable: function () { + this._destroyEventHandlers(); + $.Widget.prototype.disable.call(this); + }, + + // This method is exposed to the widget API and allows adding files + // using the fileupload API. The data parameter accepts an object which + // must have a files property and can contain additional options: + // .fileupload('add', {files: filesList}); + add: function (data) { + if (!data || this.options.disabled) { + return; + } + data.files = $.each($.makeArray(data.files), this._normalizeFile); + this._onAdd(null, data); + }, + + // This method is exposed to the widget API and allows sending files + // using the fileupload API. The data parameter accepts an object which + // must have a files property and can contain additional options: + // .fileupload('send', {files: filesList}); + // The method returns a Promise object for the file upload call. + send: function (data) { + if (data && !this.options.disabled) { + data.files = $.each($.makeArray(data.files), this._normalizeFile); + if (data.files.length) { + return this._onSend(null, data); + } + } + return this._getXHRPromise(false, data && data.context); + } + + }); + +})); -- GitLab From b949619d0409d6caca169707bae42037b1145a47 Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Fri, 16 Mar 2012 00:11:50 +0100 Subject: [PATCH 045/430] coding guidelines --- files/js/files.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/files/js/files.js b/files/js/files.js index a129b853b67..e5e97c01b95 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -250,11 +250,11 @@ $(document).ready(function() { } } if(totalSize>$('#max_upload').val()){ - $( "#uploadsize-message" ).dialog({ + $( '#uploadsize-message' ).dialog({ modal: true, buttons: { Close: function() { - $( this ).dialog( "close" ); + $( this ).dialog( 'close' ); } } }); @@ -302,7 +302,7 @@ $(document).ready(function() { } }, fail: function(e, data) { - console.debug("Fail", data); + console.debug('Fail', data); // TODO: cancel upload & display error notification }, progress: function(e, data) { -- GitLab From 9377b753507f6d47640d2815f1d61bd5fefd3b3e Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Fri, 16 Mar 2012 19:58:28 +0100 Subject: [PATCH 046/430] Support for legacy browsers --- files/index.php | 1 + files/js/files.js | 112 +++---------------- files/js/jquery.iframe-transport.js | 165 ++++++++++++++++++++++++++++ 3 files changed, 183 insertions(+), 95 deletions(-) create mode 100644 files/js/jquery.iframe-transport.js diff --git a/files/index.php b/files/index.php index a625d3cdf9f..9604f118c4b 100644 --- a/files/index.php +++ b/files/index.php @@ -30,6 +30,7 @@ OC_Util::checkLoggedIn(); // Load the files we need OC_Util::addStyle( "files", "files" ); +OC_Util::addScript( "files", "jquery.iframe-transport" ); OC_Util::addScript( "files", "jquery.fileupload" ); OC_Util::addScript( "files", "files" ); OC_Util::addScript( 'files', 'filelist' ); diff --git a/files/js/files.js b/files/js/files.js index e5e97c01b95..a09bb9abe98 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -150,87 +150,6 @@ $(document).ready(function() { return false; }); - /* - $('.file_upload_start').live('change',function(){ - var form=$(this).closest('form'); - var that=this; - var uploadId=form.attr('data-upload-id'); - var files=this.files; - var target=form.children('iframe'); - var totalSize=0; - if(files){ - for(var i=0;i$('#max_upload').val()){ - $( "#uploadsize-message" ).dialog({ - modal: true, - buttons: { - Close: function() { - $( this ).dialog( "close" ); - } - } - }); - }else{ - target.load(function(){ - var response=jQuery.parseJSON(target.contents().find('body').text()); - //set mimetype and if needed filesize - if(response){ - if(response[0] != undefined && response[0].status == 'success'){ - for(var i=0;i tr').not('[data-mime]').fadeOut(); - $('#fileList > tr').not('[data-mime]').remove(); - } - } - }); - form.submit(); - var date=new Date(); - if(files){ - for(var i=0;i0){ - var size=files[i].size; - }else{ - var size=t('files','Pending'); - } - if(files){ - FileList.addFile(files[i].name,size,date,true); - } - } - }else{ - var filename=this.value.split('\\').pop(); //ie prepends C:\fakepath\ in front of the filename - FileList.addFile(filename,'Pending',date,true); - } - - //clone the upload form and hide the new one to allow users to start a new upload while the old one is still uploading - var clone=form.clone(); - uploadId++; - clone.attr('data-upload-id',uploadId); - clone.attr('target','file_upload_target_'+uploadId); - clone.children('iframe').attr('name','file_upload_target_'+uploadId) - clone.insertBefore(form); - form.hide(); - } - }); -*/ - // drag&drop support using jquery.fileupload $(function() { $('.file_upload_start').fileupload({ @@ -279,21 +198,24 @@ $(document).ready(function() { } }, done: function(e, data) { - var response=jQuery.parseJSON(data.result); + var response; + if(data.dataType == 'iframe ') { + response = jQuery.parseJSON(data.result[0].body.innerText); + } else { + response=jQuery.parseJSON(data.result); + } if(response[0] != undefined && response[0].status == 'success') { - for(var i=0;i0){ - var size=file.size; - }else{ - var size=t('files','Pending'); - } - $('tr').filterAttr('data-file',file.name).data('mime',file.mime); - if(size=='Pending'){ - $('tr').filterAttr('data-file',file.name).find('td.filesize').text(file.size); - } - FileList.loadingDone(file.name); + var file=response[0]; + if(file.size>0){ + var size=file.size; + }else{ + var size=t('files','Pending'); + } + $('tr').filterAttr('data-file',file.name).data('mime',file.type); + if(size=='Pending'){ + $('tr').filterAttr('data-file',file.name).find('td.filesize').text(file.size); } + FileList.loadingDone(file.name); } else { $('#notification').text(t('files', response.data.message)); $('#notification').fadeIn(); @@ -302,10 +224,10 @@ $(document).ready(function() { } }, fail: function(e, data) { - console.debug('Fail', data); // TODO: cancel upload & display error notification }, progress: function(e, data) { + // TODO: show nice progress bar } }) }); diff --git a/files/js/jquery.iframe-transport.js b/files/js/jquery.iframe-transport.js new file mode 100644 index 00000000000..d85c0c11297 --- /dev/null +++ b/files/js/jquery.iframe-transport.js @@ -0,0 +1,165 @@ +/* + * jQuery Iframe Transport Plugin 1.3 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/*jslint unparam: true, nomen: true */ +/*global define, window, document */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define(['jquery'], factory); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // Helper variable to create unique names for the transport iframes: + var counter = 0; + + // The iframe transport accepts three additional options: + // options.fileInput: a jQuery collection of file input fields + // options.paramName: the parameter name for the file form data, + // overrides the name property of the file input field(s) + // options.formData: an array of objects with name and value properties, + // equivalent to the return data of .serializeArray(), e.g.: + // [{name: 'a', value: 1}, {name: 'b', value: 2}] + $.ajaxTransport('iframe', function (options) { + if (options.async && (options.type === 'POST' || options.type === 'GET')) { + var form, + iframe; + return { + send: function (_, completeCallback) { + form = $('
      '); + // javascript:false as initial iframe src + // prevents warning popups on HTTPS in IE6. + // IE versions below IE8 cannot set the name property of + // elements that have already been added to the DOM, + // so we set the name along with the iframe HTML markup: + iframe = $( + '' + ).bind('load', function () { + var fileInputClones; + iframe + .unbind('load') + .bind('load', function () { + var response; + // Wrap in a try/catch block to catch exceptions thrown + // when trying to access cross-domain iframe contents: + try { + response = iframe.contents(); + // Google Chrome and Firefox do not throw an + // exception when calling iframe.contents() on + // cross-domain requests, so we unify the response: + if (!response.length || !response[0].firstChild) { + throw new Error(); + } + } catch (e) { + response = undefined; + } + // The complete callback returns the + // iframe content document as response object: + completeCallback( + 200, + 'success', + {'iframe': response} + ); + // Fix for IE endless progress bar activity bug + // (happens on form submits to iframe targets): + $('') + .appendTo(form); + form.remove(); + }); + form + .prop('target', iframe.prop('name')) + .prop('action', options.url) + .prop('method', options.type); + if (options.formData) { + $.each(options.formData, function (index, field) { + $('') + .prop('name', field.name) + .val(field.value) + .appendTo(form); + }); + } + if (options.fileInput && options.fileInput.length && + options.type === 'POST') { + fileInputClones = options.fileInput.clone(); + // Insert a clone for each file input field: + options.fileInput.after(function (index) { + return fileInputClones[index]; + }); + if (options.paramName) { + options.fileInput.each(function () { + $(this).prop('name', options.paramName); + }); + } + // Appending the file input fields to the hidden form + // removes them from their original location: + form + .append(options.fileInput) + .prop('enctype', 'multipart/form-data') + // enctype must be set as encoding for IE: + .prop('encoding', 'multipart/form-data'); + } + form.submit(); + // Insert the file input fields at their original location + // by replacing the clones with the originals: + if (fileInputClones && fileInputClones.length) { + options.fileInput.each(function (index, input) { + var clone = $(fileInputClones[index]); + $(input).prop('name', clone.prop('name')); + clone.replaceWith(input); + }); + } + }); + form.append(iframe).appendTo(document.body); + }, + abort: function () { + if (iframe) { + // javascript:false as iframe src aborts the request + // and prevents warning popups on HTTPS in IE6. + // concat is used to avoid the "Script URL" JSLint error: + iframe + .unbind('load') + .prop('src', 'javascript'.concat(':false;')); + } + if (form) { + form.remove(); + } + } + }; + } + }); + + // The iframe transport returns the iframe content document as response. + // The following adds converters from iframe to text, json, html, and script: + $.ajaxSetup({ + converters: { + 'iframe text': function (iframe) { + return $(iframe[0].body).text(); + }, + 'iframe json': function (iframe) { + return $.parseJSON($(iframe[0].body).text()); + }, + 'iframe html': function (iframe) { + return $(iframe[0].body).html(); + }, + 'iframe script': function (iframe) { + return $.globalEval($(iframe[0].body).text()); + } + } + }); + +})); -- GitLab From 38072e1900b2f3b5d0d9d0d7bd78658026a8ab23 Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Sat, 17 Mar 2012 13:56:33 +0100 Subject: [PATCH 047/430] Fixed upload of undeleted file and size information --- files/js/files.js | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/files/js/files.js b/files/js/files.js index a09bb9abe98..666e0c7602f 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -162,7 +162,7 @@ $(document).ready(function() { totalSize+=files[i].size; if(FileList.deleteFiles && FileList.deleteFiles.indexOf(files[i].name)!=-1){//finish delete if we are uploading a deleted file FileList.finishDelete(function(){ - $(that).change(); + $('.file_upload_start').change(); }); return; } @@ -206,13 +206,9 @@ $(document).ready(function() { } if(response[0] != undefined && response[0].status == 'success') { var file=response[0]; - if(file.size>0){ - var size=file.size; - }else{ - var size=t('files','Pending'); - } $('tr').filterAttr('data-file',file.name).data('mime',file.type); - if(size=='Pending'){ + var size = $('tr').filterAttr('data-file',file.name).find('td.filesize').text(); + if(size==t('files','Pending')){ $('tr').filterAttr('data-file',file.name).find('td.filesize').text(file.size); } FileList.loadingDone(file.name); -- GitLab From b1a33110fc44d2cf20ab6de6aa68031054ec0761 Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Sat, 17 Mar 2012 22:20:39 +0100 Subject: [PATCH 048/430] Added global progressbar for all uploads --- files/css/files.css | 1 + files/js/files.js | 14 +++++++++++++- files/templates/index.php | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/files/css/files.css b/files/css/files.css index 512e462cb6f..60851b6f57e 100644 --- a/files/css/files.css +++ b/files/css/files.css @@ -30,6 +30,7 @@ .file_upload_filename { position: relative; z-index:100; padding-left: 0.8em; padding-right: 0.8em; cursor:pointer; border-top-left-radius:0; border-bottom-left-radius:0; } .file_upload_filename img { position: absolute; top: 0.4em; left: 0.4em; } +#uploadprogressbar { position:absolute; right:14.5em; display:inline-block; width:10em; height:1.5em; top:.4em; } .file_upload_form, .file_upload_wrapper, .file_upload_start, .file_upload_filename, #file_upload_submit { cursor:pointer; } diff --git a/files/js/files.js b/files/js/files.js index 666e0c7602f..5f61bdd2ac3 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -223,7 +223,19 @@ $(document).ready(function() { // TODO: cancel upload & display error notification }, progress: function(e, data) { - // TODO: show nice progress bar + // TODO: show nice progress bar in file row + }, + progressall: function(e, data) { + var progress = (data.loaded/data.total)*100; + $('#uploadprogressbar').progressbar('value',progress); + }, + start: function(e, data) { + $('#uploadprogressbar').progressbar({value:0}); + $('#uploadprogressbar').fadeIn(); + }, + stop: function(e, data) { + $('#uploadprogressbar').progressbar('value',100); + $('#uploadprogressbar').fadeOut(); } }) }); diff --git a/files/templates/index.php b/files/templates/index.php index 7fc51c288e1..abcbd269211 100644 --- a/files/templates/index.php +++ b/files/templates/index.php @@ -21,6 +21,7 @@ +
      -- GitLab From b7a5ae38c58cc9a1973febfce40c5f076ff5d772 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 09:48:58 +0200 Subject: [PATCH 049/430] fix sql command in calendar's share lib --- apps/calendar/lib/share.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index a5ca0a6e738..def1026c5e1 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -21,7 +21,7 @@ class OC_Calendar_Share{ $group_where = self::group_sql(OC_Group::getUserGroups($userid)); $permission_where = self::permission_sql($permission); $active_where = self::active_sql($active); - $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . $active_where . ')'); + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . $active_where); $result = $stmt->execute(array($userid, $userid)); $return = array(); while( $row = $result->fetchRow()){ @@ -168,8 +168,8 @@ class OC_Calendar_Share{ private static function permission_sql($permission = null){ $permission_where = ''; if(!is_null($permission)){ - $permission_where = 'AND permissions = '; - $permission_where .= ($permission=='rw')?'1':'0'; + $permission_where = ' AND permissions = '; + $permission_where .= ($permission=='rw')?'"1"':'"0"'; } return $permission_where; } -- GitLab From 71b32f7ad4684360f460726977fb3d803f7bb48a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 15:24:43 +0200 Subject: [PATCH 050/430] add read only 'form' for shared events --- apps/calendar/ajax/event/edit.form.php | 18 +- apps/calendar/lib/app.php | 25 ++- apps/calendar/lib/share.php | 26 ++- apps/calendar/templates/part.eventform.php | 1 + apps/calendar/templates/part.showevent.php | 249 +++++++++++++++++++++ 5 files changed, 308 insertions(+), 11 deletions(-) create mode 100644 apps/calendar/templates/part.showevent.php diff --git a/apps/calendar/ajax/event/edit.form.php b/apps/calendar/ajax/event/edit.form.php index 837edbbbf05..ab77a747f1c 100644 --- a/apps/calendar/ajax/event/edit.form.php +++ b/apps/calendar/ajax/event/edit.form.php @@ -18,6 +18,12 @@ $data = OC_Calendar_App::getEventObject($id); $object = OC_VObject::parse($data['calendardata']); $vevent = $object->VEVENT; +$access = OC_Calendar_App::check_access($id); +if(!$access){ + OC_JSON::error(array('data' => array('message' => self::$l10n->t('Wrong calendar')))); + exit; +} + $dtstart = $vevent->DTSTART; $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); switch($dtstart->getDateType()) { @@ -187,8 +193,9 @@ if($data['repeating'] == 1){ }else{ $repeat['repeat'] = 'doesnotrepeat'; } - -$calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +if($access == 'owner'){ + $calendar_options = OC_Calendar_Calendar::allCalendars(OC_User::getUser()); +} $category_options = OC_Calendar_App::getCategoryOptions(); $repeat_options = OC_Calendar_App::getRepeatOptions(); $repeat_end_options = OC_Calendar_App::getEndOptions(); @@ -201,7 +208,12 @@ $repeat_bymonth_options = OC_Calendar_App::getByMonthOptions(); $repeat_byweekno_options = OC_Calendar_App::getByWeekNoOptions(); $repeat_bymonthday_options = OC_Calendar_App::getByMonthDayOptions(); -$tmpl = new OC_Template('calendar', 'part.editevent'); +if($access == 'owner' || $access == 'rw'){ + $tmpl = new OC_Template('calendar', 'part.editevent'); +}elseif($access == 'r'){ + $tmpl = new OC_Template('calendar', 'part.showevent'); +} + $tmpl->assign('id', $id); $tmpl->assign('lastmodified', $lastmodified); $tmpl->assign('calendar_options', $calendar_options); diff --git a/apps/calendar/lib/app.php b/apps/calendar/lib/app.php index f50c65ab4f7..b4d9f844c19 100644 --- a/apps/calendar/lib/app.php +++ b/apps/calendar/lib/app.php @@ -14,12 +14,7 @@ class OC_Calendar_App{ public static $l10n; public static function getCalendar($id){ - $calendar = OC_Calendar_Calendar::find( $id ); - if( $calendar === false || $calendar['userid'] != OC_User::getUser()){ - OC_JSON::error(array('data' => array('message' => self::$l10n->t('Wrong calendar')))); - exit(); - } - return $calendar; + return OC_Calendar_Calendar::find( $id ); } public static function getEventObject($id){ @@ -29,10 +24,26 @@ class OC_Calendar_App{ exit(); } - self::getCalendar( $event_object['calendarid'] );//access check + //self::getCalendar( $event_object['calendarid'] );//access check return $event_object; } + public static function check_access($id){ + $event_object = self::getEventObject($id); + $calendar = self::getCalendar($event_object['calendarid']); + if($calendar['userid'] == OC_User::getUser()){ + return 'owner'; + } + if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ + if(OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ + return 'rw'; + }else{ + return 'r'; + } + } + return false; + } + public static function getVCalendar($id){ $event_object = self::getEventObject( $id ); diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index def1026c5e1..7117607ebbd 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -191,11 +191,35 @@ class OC_Calendar_Share{ public static function is_editing_allowed($share, $id, $type){ $group_where = self::group_sql(OC_Group::getUserGroups($share)); $permission_where = self::permission_sql('rw'); - $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') ' . $permission_where . ')'); + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') ' . $permission_where); $result = $stmt->execute(array($share)); if($result->numRows() == 1){ return true; } + if($type == self::EVENT){ + $calendar == OC_Calendar_App::getCalendar($id); + return self::is_editing_allowed($share, $calendar['id'], self::CALENDAR); + } + return false; + } + /* + * @brief: checks the access of + * @param: (string) $share - userid (if $sharetype == user) / groupid (if $sharetype == group) / token (if $sharetype == public) + * @param: (string) $id - id of the calendar / event + * @param: (string) $type - use const self::CALENDAR or self::EVENT + * @return (bool) + */ + public static function check_access($share, $id, $type){ + $group_where = self::group_sql(OC_Group::getUserGroups($share)); + $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ')'); + $result = $stmt->execute(array($share)); + if($result->numRows() > 0){ + return true; + } + if($type == self::EVENT){ + $calendar == OC_Calendar_App::getCalendar($id); + return self::check_access($share, $calendar['id'], self::CALENDAR); + } return false; } } \ No newline at end of file diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index b67f8c02c39..c87e1ec9de7 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -217,6 +217,7 @@ diff --git a/apps/calendar/templates/part.showevent.php b/apps/calendar/templates/part.showevent.php new file mode 100644 index 00000000000..1be13bf1f66 --- /dev/null +++ b/apps/calendar/templates/part.showevent.php @@ -0,0 +1,249 @@ +
      "> + +
      + + + + + +
      t("Title");?>: + +
      + + + + + + + + + +
      t("Category");?>: + t('No categories selected'); + }else{ + echo ''; + } + ?> +    t("Calendar");?>: + +   + +
      +
      + + + + + + + + + + + + + +
      + id="allday_checkbox" name="allday" disabled="disabled"> + t("All Day Event");?> +
      t("From");?>: + +    t('at'):''; ?>    + +
      t("To");?>: + +    t('at'):''; ?>    + +
      + " onclick="Calendar.UI.showadvancedoptions();" id="advanced_options_button"> + +
      +
      + + + + + + +
      t("Repeat");?>: + " onclick="Calendar.UI.showadvancedoptionsforrepeating();" id="advanced_options_button">
      + +
      +
      //Alarm
      +
      //Attendees
      +
      //Share
      + +
      \ No newline at end of file -- GitLab From 179bf15dafcd322354b4cdb4a8d044598b6e89a9 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 15:30:04 +0200 Subject: [PATCH 051/430] fix group sql generator in calendar's share lib --- apps/calendar/lib/share.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index 7117607ebbd..42dfc8a3101 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -155,11 +155,7 @@ class OC_Calendar_Share{ $group_where = ''; $i = 0; foreach($groups as $group){ - if($i == 0){ - $group_where = 'OR ('; - }else{ - $group_where .= ' OR '; - } + $group_where .= ' OR '; $group_where .= ' (share = "' . $group . '" AND sharetype = "group") '; $i++; } -- GitLab From 8b9d439841e8f74d4efebfdec24d515782ce8d9a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 15:37:47 +0200 Subject: [PATCH 052/430] Calendar: fix address for import file --- apps/calendar/js/loader.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/calendar/js/loader.js b/apps/calendar/js/loader.js index 54003879759..60d92f448ee 100644 --- a/apps/calendar/js/loader.js +++ b/apps/calendar/js/loader.js @@ -44,7 +44,7 @@ Calendar_Import={ $('#newcalendar').attr('readonly', 'readonly'); $('#calendar').attr('disabled', 'disabled'); var progressfile = $('#progressfile').val(); - $.post(OC.filePath('calendar', '', 'import.php'), {method: String (method), calname: String (calname), path: String (path), file: String (filename), id: String (calid)}, function(data){ + $.post(OC.filePath('calendar', 'ajax/import', 'import.php'), {method: String (method), calname: String (calname), path: String (path), file: String (filename), id: String (calid)}, function(data){ if(data.status == 'success'){ $('#progressbar').progressbar('option', 'value', 100); $('#import_done').css('display', 'block'); -- GitLab From 10ef01b04be2bb6dd15303c9d641647d515e5556 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 15:44:24 +0200 Subject: [PATCH 053/430] fix displayed username of person who shares --- apps/calendar/templates/part.showevent.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/calendar/templates/part.showevent.php b/apps/calendar/templates/part.showevent.php index 1be13bf1f66..d8443bd06e2 100644 --- a/apps/calendar/templates/part.showevent.php +++ b/apps/calendar/templates/part.showevent.php @@ -35,7 +35,7 @@ -- GitLab From f479105f5e50ba915b9dbed3dd049f08e35fa591 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 26 Mar 2012 16:01:55 +0200 Subject: [PATCH 054/430] optimize choosecalendar dialog for shared calendars --- apps/calendar/templates/part.choosecalendar.php | 1 + .../calendar/templates/part.choosecalendar.rowfields.shared.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/calendar/templates/part.choosecalendar.php b/apps/calendar/templates/part.choosecalendar.php index 21da5dd7cd9..3c6799d892e 100644 --- a/apps/calendar/templates/part.choosecalendar.php +++ b/apps/calendar/templates/part.choosecalendar.php @@ -28,6 +28,7 @@ for($i = 0; $i < count($option_calendars); $i++){ $share = OC_Calendar_Share::allSharedwithuser(OC_User::getUser(), OC_Calendar_Share::CALENDAR); $count = count($share); for($i = 0; $i < $count; $i++){ + $share[$i]['calendar'] = OC_Calendar_App::getCalendar($share[$i]['calendarid']); echo ''; $tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields.shared'); $tmpl->assign('share', $share[$i]); diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.shared.php b/apps/calendar/templates/part.choosecalendar.rowfields.shared.php index 2e1210415bf..a23266da0c3 100644 --- a/apps/calendar/templates/part.choosecalendar.rowfields.shared.php +++ b/apps/calendar/templates/part.choosecalendar.rowfields.shared.php @@ -1,4 +1,4 @@ '; echo ''; -echo '' . $l->t('shared with you by') . ' ' . $_['share']['owner'] . ''; \ No newline at end of file +echo '' . $l->t('shared with you by') . ' ' . $_['share']['owner'] . ''; \ No newline at end of file -- GitLab From c384e3ba4f01718af35a47e8470a7458424be954 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 27 Mar 2012 09:24:55 +0200 Subject: [PATCH 055/430] fix width of dropdown to select monthdays - bugfix oc-354 --- apps/calendar/templates/part.eventform.php | 2 +- apps/calendar/templates/part.showevent.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index c87e1ec9de7..c4c3ae1c1e2 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -144,7 +144,7 @@ - "> true)); diff --git a/apps/calendar/templates/part.showevent.php b/apps/calendar/templates/part.showevent.php index d8443bd06e2..ae3d55e074a 100644 --- a/apps/calendar/templates/part.showevent.php +++ b/apps/calendar/templates/part.showevent.php @@ -147,7 +147,7 @@ - "> true)); -- GitLab From 4e89a0faf652f2f100cca47cca54a3b35e720aad Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Tue, 27 Mar 2012 21:38:55 +0200 Subject: [PATCH 056/430] Added uploading to folder and cancellable downloads --- files/css/files.css | 10 +- files/js/fileactions.js | 15 ++- files/js/filelist.js | 1 + files/js/files.js | 173 ++++++++++++++++++++++++++++------ files/templates/index.php | 6 +- files/templates/part.list.php | 4 + 6 files changed, 173 insertions(+), 36 deletions(-) diff --git a/files/css/files.css b/files/css/files.css index 60851b6f57e..8e3a767721e 100644 --- a/files/css/files.css +++ b/files/css/files.css @@ -30,7 +30,8 @@ .file_upload_filename { position: relative; z-index:100; padding-left: 0.8em; padding-right: 0.8em; cursor:pointer; border-top-left-radius:0; border-bottom-left-radius:0; } .file_upload_filename img { position: absolute; top: 0.4em; left: 0.4em; } -#uploadprogressbar { position:absolute; right:14.5em; display:inline-block; width:10em; height:1.5em; top:.4em; } +#upload { position:absolute; right:13.5em; top:0em; } +#upload #uploadprogressbar { position:relative; display:inline-block; width:10em; height:1.5em; top:.4em; } .file_upload_form, .file_upload_wrapper, .file_upload_start, .file_upload_filename, #file_upload_submit { cursor:pointer; } @@ -41,7 +42,7 @@ tbody tr:hover, tbody tr:active, tbody tr.selected { background-color:#f8f8f8; h tbody tr { background-color:#fff; } tbody tr.selected { background-color:#eee; } tbody a { color:#000; } -span.extention, td.date { color:#999; } +span.extention, span.uploading, td.date { color:#999; } span.extention { opacity:0; -webkit-transition:opacity 500ms; -moz-transition:opacity 500ms; -o-transition:opacity 500ms; transition:opacity 500ms; } tr:hover span.extention { opacity:1; } div.crumb { float:left; display:block; background:no-repeat right 0; padding:.75em 1.5em 0 1em; height:2.9em; } @@ -60,8 +61,9 @@ table td.filename a.name { display:block; height:1.5em; vertical-align:middle; m table tr[data-type="dir"] td.filename a.name {font-weight:bold; } table td.filename a.name input, table td.filename a.name form { width:100%; cursor:text; } table td.filename a, table td.login, table td.logout, table td.download, table td.upload, table td.create, table td.delete { padding:.2em .5em .5em 0; } -table td.filename .nametext, .modified { float:left; padding:.3em 0; } -table td.filename .nametext { width:60%; } +table td.filename .nametext, .uploadtext, .modified { float:left; padding:.3em 0; } +//table td.filename .nametext { width:60%; } +table td.filename .uploadtext { font-weight:normal; margin-left:.5em; } table td.filename form { float:left; font-size:.85em; } table thead.fixed tr{ position:fixed; top:6.5em; z-index:49; -moz-box-shadow:0 -3px 7px #ddd; -webkit-box-shadow:0 -3px 7px #ddd; box-shadow:0 -3px 7px #ddd; } table thead.fixed { height:2em; } diff --git a/files/js/fileactions.js b/files/js/fileactions.js index b5dd3982803..384ffc92cf2 100644 --- a/files/js/fileactions.js +++ b/files/js/fileactions.js @@ -133,7 +133,20 @@ FileActions.register('all','Download',function(){return OC.imagePath('core','act }); FileActions.register('all','Delete',function(){return OC.imagePath('core','actions/delete')},function(filename){ - FileList.do_delete(filename); + if(Files.cancelUpload(filename)) { + if(filename.substr){ + filename=[filename]; + } + $.each(filename,function(index,file){ + var filename = $('tr').filterAttr('data-file',file); + filename.hide(); + filename.find('input[type="checkbox"]').removeAttr('checked'); + filename.removeClass('selected'); + }); + procesSelection(); + }else{ + FileList.do_delete(filename); + } }); FileActions.register('all','Rename',function(){return OC.imagePath('core','actions/rename')},function(filename){ diff --git a/files/js/filelist.js b/files/js/filelist.js index 35847e06dfe..0faff08a73f 100644 --- a/files/js/filelist.js +++ b/files/js/filelist.js @@ -42,6 +42,7 @@ FileList={ td.append(''); var link_elem = $('').attr({ "class": "name", "href": "index.php?dir="+ encodeURIComponent($('#dir').val()+'/'+name).replace(/%2F/g, '/') }); link_elem.append($('').addClass('nametext').text(name)); + link_elem.append($('').attr({'class': 'uploadtext', 'currentUploads': 0})); td.append(link_elem); html.append(td); if(size!='Pending'){ diff --git a/files/js/files.js b/files/js/files.js index 5f61bdd2ac3..6eed25dfe99 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -1,3 +1,25 @@ +var uploadingFiles = {}; +Files={ + cancelUpload:function(filename) { + if(uploadingFiles[filename]) { + uploadingFiles[filename].abort(); + delete uploadingFiles[filename]; + return true; + } + return false; + }, + cancelUploads:function() { + $.each(uploadingFiles,function(index,file){ + file.abort(); + delete uploadingFiles[index]; + var filename = $('tr').filterAttr('data-file',index); + filename.hide(); + filename.find('input[type="checkbox"]').removeAttr('checked'); + filename.removeClass('selected'); + }); + procesSelection(); + } +} $(document).ready(function() { $('#fileList tr').each(function(){ //little hack to set unescape filenames in attribute @@ -151,9 +173,13 @@ $(document).ready(function() { }); // drag&drop support using jquery.fileupload + $(document).bind('drop dragover', function (e) { + e.preventDefault(); // prevent browser from doing anything, if file isn't dropped in dropZone + }); + $(function() { $('.file_upload_start').fileupload({ - //dropZone: $('#content'), // restrict dropZone to content div + dropZone: $('#content'), // restrict dropZone to content div add: function(e, data) { var files = data.files; var totalSize=0; @@ -178,7 +204,97 @@ $(document).ready(function() { } }); }else{ - data.submit(); + if($.support.xhrFileUpload) { + for(var i=0;i tr').not('[data-mime]').fadeOut(); + $('#fileList > tr').not('[data-mime]').remove(); + } + }) + .error(function(jqXHR, textStatus, errorThrown) { + if(errorThrown === 'abort') { + $('#notification').hide(); + $('#notification').text(t('files', 'Upload cancelled.')); + $('#notification').fadeIn(); + } + }); + } + uploadingFiles[files[i].name] = jqXHR; + } + }else{ + data.submit().success(function(data, status) { + response = jQuery.parseJSON(data[0].body.innerText); + if(response[0] != undefined && response[0].status == 'success') { + var file=response[0]; + delete uploadingFiles[file.name]; + $('tr').filterAttr('data-file',file.name).data('mime',file.mime); + var size = $('tr').filterAttr('data-file',file.name).find('td.filesize').text(); + if(size==t('files','Pending')){ + $('tr').filterAttr('data-file',file.name).find('td.filesize').text(file.size); + } + FileList.loadingDone(file.name); + } else { + $('#notification').text(t('files', response.data.message)); + $('#notification').fadeIn(); + $('#fileList > tr').not('[data-mime]').fadeOut(); + $('#fileList > tr').not('[data-mime]').remove(); + } + }); + } + var date=new Date(); if(files){ for(var i=0;i tr').not('[data-mime]').fadeOut(); - $('#fileList > tr').not('[data-mime]').remove(); - } - }, fail: function(e, data) { // TODO: cancel upload & display error notification }, @@ -230,17 +338,22 @@ $(document).ready(function() { $('#uploadprogressbar').progressbar('value',progress); }, start: function(e, data) { - $('#uploadprogressbar').progressbar({value:0}); - $('#uploadprogressbar').fadeIn(); + $('#uploadprogressbar').progressbar({value:0}); + $('#uploadprogressbar').fadeIn(); + if(data.dataType != 'iframe ') { + $('#upload input.stop').show(); + } }, stop: function(e, data) { - $('#uploadprogressbar').progressbar('value',100); - $('#uploadprogressbar').fadeOut(); + if(data.dataType != 'iframe ') { + $('#upload input.stop').hide(); + } + $('#uploadprogressbar').progressbar('value',100); + $('#uploadprogressbar').fadeOut(); } }) }); - //add multiply file upload attribute to all browsers except konqueror (which crashes when it's used) if(navigator.userAgent.search(/konqueror/i)==-1){ diff --git a/files/templates/index.php b/files/templates/index.php index abcbd269211..319c8c64a07 100644 --- a/files/templates/index.php +++ b/files/templates/index.php @@ -21,7 +21,11 @@ -
      +
      +
      + +
      +
      diff --git a/files/templates/part.list.php b/files/templates/part.list.php index b117d81a1a5..a86632bafc8 100644 --- a/files/templates/part.list.php +++ b/files/templates/part.list.php @@ -21,6 +21,10 @@ + + + + -- GitLab From a88305b4cbe6aa3772384a96f56b207996bfe960 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 13:11:30 +0200 Subject: [PATCH 057/430] remove share tab from read only event dialog --- apps/calendar/templates/part.showevent.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/calendar/templates/part.showevent.php b/apps/calendar/templates/part.showevent.php index ae3d55e074a..c0521830563 100644 --- a/apps/calendar/templates/part.showevent.php +++ b/apps/calendar/templates/part.showevent.php @@ -4,7 +4,6 @@
    • t('Repeating'); ?>
    • t('Alarm'); ?>
    • t('Attendees'); ?>
    • -
    • t('Share'); ?>
    @@ -244,6 +243,5 @@
    //Alarm
    //Attendees
    -
    //Share
    \ No newline at end of file -- GitLab From 1f8cf2d8f256535ca86d9e01afcf13114c6bd70b Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 13:37:44 +0200 Subject: [PATCH 058/430] fix name of constants --- apps/calendar/ajax/share/changepermission.php | 2 +- apps/calendar/ajax/share/share.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/ajax/share/changepermission.php b/apps/calendar/ajax/share/changepermission.php index d91f87b613f..41d49e7b521 100644 --- a/apps/calendar/ajax/share/changepermission.php +++ b/apps/calendar/ajax/share/changepermission.php @@ -36,5 +36,5 @@ if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ OC_JSON::error(array('message'=>'group not found')); exit; } -$success = OC_Calendar_Share::changepermission($sharewith, $sharetype, $id, $permission, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +$success = OC_Calendar_Share::changepermission($sharewith, $sharetype, $id, $permission, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::EVENT)); OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/ajax/share/share.php b/apps/calendar/ajax/share/share.php index d892727701a..92c3eb90d3b 100644 --- a/apps/calendar/ajax/share/share.php +++ b/apps/calendar/ajax/share/share.php @@ -38,7 +38,7 @@ if($sharetype == 'group' && !OC_Group::groupExists($sharewith)){ if($sharetype == 'user' && OC_User::getUser() == $sharewith){ OC_JSON::error(array('meesage'=>'you can not share with yourself')); } -$success = OC_Calendar_Share::share(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::Event)); +$success = OC_Calendar_Share::share(OC_User::getUser(), $sharewith, $sharetype, $id, (($idtype=='calendar') ? OC_Calendar_Share::CALENDAR : OC_Calendar_Share::EVENT)); if($success){ if($sharetype == 'public'){ OC_JSON::success(array('message'=>$success)); -- GitLab From 4b3f074309fe9075119a56c337d7e8ad30d2c73a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 17:27:30 +0100 Subject: [PATCH 059/430] add new parameters to export file --- apps/calendar/export.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/calendar/export.php b/apps/calendar/export.php index 2736eec96c2..e4caa1bde75 100644 --- a/apps/calendar/export.php +++ b/apps/calendar/export.php @@ -13,7 +13,7 @@ $cal = isset($_GET['calid']) ? $_GET['calid'] : NULL; $event = isset($_GET['eventid']) ? $_GET['eventid'] : NULL; $nl = "\n\r"; if(isset($cal)){ - $calendar = OC_Calendar_App::getCalendar($cal); + $calendar = OC_Calendar_App::getCalendar($cal, true); $calobjects = OC_Calendar_Object::all($cal); header('Content-Type: text/Calendar'); header('Content-Disposition: inline; filename=' . $calendar['displayname'] . '.ics'); @@ -21,11 +21,11 @@ if(isset($cal)){ echo $calobject['calendardata'] . $nl; } }elseif(isset($event)){ - $data = OC_Calendar_App::getEventObject($_GET['eventid']); + $data = OC_Calendar_App::getEventObject($_GET['eventid'], true); $calendarid = $data['calendarid']; $calendar = OC_Calendar_App::getCalendar($calendarid); header('Content-Type: text/Calendar'); header('Content-Disposition: inline; filename=' . $data['summary'] . '.ics'); echo $data['calendardata']; } -?> +?> \ No newline at end of file -- GitLab From cf26f8a6a7751bd32eeb449ef39b743248ae3d1a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 17:32:43 +0100 Subject: [PATCH 060/430] add public sharing for calendars and events --- apps/calendar/share.php | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/calendar/share.php b/apps/calendar/share.php index 8d1c8b69c3f..3e45fdeee15 100644 --- a/apps/calendar/share.php +++ b/apps/calendar/share.php @@ -1 +1,21 @@ - + Date: Sat, 31 Mar 2012 16:12:27 -0400 Subject: [PATCH 061/430] add public sharing fir calendars and events - add function in Share class --- apps/calendar/lib/share.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index 42dfc8a3101..3e03a2d7ccf 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -218,4 +218,27 @@ class OC_Calendar_Share{ } return false; } + /* + * @brief: returns the calendardata of an event or a calendar + * @param: (string) $token - token which should be searched + * @return: mixed - bool if false, array with type and id if true + */ + public static function getElementByToken($token){ + $stmt_calendar = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . OC_Calendar_Share::CALENDAR . ' WHERE sharetype = "public" AND share = ?'); + $result_calendar = $stmt_calendar->execute(array($token)); + $stmt_event = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . OC_Calendar_Share::EVENT . ' WHERE sharetype = "public" AND share = ?'); + $result_event = $stmt_calendar->execute(array($token)); + $return = array(); + if($result_calendar->numRows() == 0 && $result_event->numRows() == 0){ + return false; + }elseif($result_calendar->numRows() != 0){ + $return ['type'] = 'calendar'; + $calendar = $result_calendar->fetchRow(); + $return ['id'] = $calendar['calendarid']; + }else{ + $return ['type'] = 'event'; + $event = $result_event->fetchRow(); + $return ['id'] = $event['eventid']; + } + } } \ No newline at end of file -- GitLab From 70237f7eccebbc83c57df3e7bc3585e285e52579 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 16:13:04 -0400 Subject: [PATCH 062/430] rewrite OC_Calendar_APP class --- apps/calendar/lib/app.php | 219 +++++++++++++++++++++++++------------- 1 file changed, 143 insertions(+), 76 deletions(-) diff --git a/apps/calendar/lib/app.php b/apps/calendar/lib/app.php index b4d9f844c19..8bc416d2ce4 100644 --- a/apps/calendar/lib/app.php +++ b/apps/calendar/lib/app.php @@ -1,143 +1,210 @@ + * Copyright (c) 2012 Georg Ehrke * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. - */ - -/** + * * This class manages our app actions */ OC_Calendar_App::$l10n = new OC_L10N('calendar'); class OC_Calendar_App{ + /* + * @brief: language object for calendar app + */ public static $l10n; - public static function getCalendar($id){ - return OC_Calendar_Calendar::find( $id ); - } - - public static function getEventObject($id){ - $event_object = OC_Calendar_Object::find( $id ); - if( $event_object === false ){ - OC_JSON::error(); - exit(); + /* + * @brief: returns informations about a calendar + * @param: int $id - id of the calendar + * @param: bool $security - check access rights or not + * @param: bool $shared - check if the user got access via sharing + * @return: mixed - bool / array + */ + public static function getCalendar($id, $security = true, $shared = false){ + $calendar = OC_Calendar_Object::find($id); + if($shared === true){ + if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::CALENDAR)){ + return $calendar; + } } - - //self::getCalendar( $event_object['calendarid'] );//access check - return $event_object; + if($security === true){ + if($calendar['userid'] != OC_User::getUser()){ + return false; + } + } + if($calendar === false){ + return false; + } + return OC_Calendar_Calendar::find($id); } - - public static function check_access($id){ - $event_object = self::getEventObject($id); - $calendar = self::getCalendar($event_object['calendarid']); - if($calendar['userid'] == OC_User::getUser()){ - return 'owner'; + + /* + * @brief: returns informations about an event + * @param: int $id - id of the event + * @param: bool $security - check access rights or not + * @param: bool $shared - check if the user got access via sharing + * @return: mixed - bool / array + */ + public static function getEventObject($id, $security = true, $shared = false){ + $event = OC_Calendar_Object::find($id); + if($shared === true){ + if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ + return $calendar; + } } - if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ - if(OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ - return 'rw'; - }else{ - return 'r'; + if($security === true){ + $calendar = self::getCalendar($event['calendarid'], false); + if($calendar['userid'] != OC_User::getUser()){ + return false; } } - return false; + if($event === false){ + return false; + } + return $event; } - - public static function getVCalendar($id){ - $event_object = self::getEventObject( $id ); - - $vcalendar = OC_VObject::parse($event_object['calendardata']); - // Check if the vcalendar is valid - if(is_null($vcalendar)){ - OC_JSON::error(); - exit(); + + /* + * @brief: returns the parsed calendar data + * @param: int $id - id of the event + * @param: bool $security - check access rights or not + * @return: mixed - bool / object + */ + public static function getVCalendar($id, $security = true){ + $event_object = self::getEventObject($id, $security); + if($event_object === false){ + return false; + } + $vobject = OC_VObject::parse($event_object['calendardata']); + if(is_null($vobject)){ + return false; } - return $vcalendar; + return $vobject; } - - public static function isNotModified($vevent, $lastmodified) - { + + /* + * + */ + public static function isNotModified($vevent, $lastmodified){ $last_modified = $vevent->__get('LAST-MODIFIED'); if($last_modified && $lastmodified != $last_modified->getDateTime()->format('U')){ OC_JSON::error(array('modified'=>true)); exit; } } - - public static function getCategoryOptions() - { - return array( - self::$l10n->t('Birthday'), - self::$l10n->t('Business'), - self::$l10n->t('Call'), - self::$l10n->t('Clients'), - self::$l10n->t('Deliverer'), - self::$l10n->t('Holidays'), - self::$l10n->t('Ideas'), - self::$l10n->t('Journey'), - self::$l10n->t('Jubilee'), - self::$l10n->t('Meeting'), - self::$l10n->t('Other'), - self::$l10n->t('Personal'), - self::$l10n->t('Projects'), - self::$l10n->t('Questions'), - self::$l10n->t('Work'), - ); + /* + * THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED SOON + * @brief: returns the valid categories + * @return: array - categories + */ + public static function getCategoryOptions(){ + return OC_Calendar_Object::getCategoryOptions(self::$l10n); } - + + /* + * @brief: returns the options for an repeating event + * @return: array - valid inputs for repeating events + */ public static function getRepeatOptions(){ return OC_Calendar_Object::getRepeatOptions(self::$l10n); } - + + /* + * @brief: returns the options for the end of an repeating event + * @return: array - valid inputs for the end of an repeating events + */ public static function getEndOptions(){ return OC_Calendar_Object::getEndOptions(self::$l10n); } - + + /* + * @brief: returns the options for an monthly repeating event + * @return: array - valid inputs for monthly repeating events + */ public static function getMonthOptions(){ return OC_Calendar_Object::getMonthOptions(self::$l10n); } - + + /* + * @brief: returns the options for an weekly repeating event + * @return: array - valid inputs for weekly repeating events + */ public static function getWeeklyOptions(){ return OC_Calendar_Object::getWeeklyOptions(self::$l10n); } - + + /* + * @brief: returns the options for an yearly repeating event + * @return: array - valid inputs for yearly repeating events + */ public static function getYearOptions(){ return OC_Calendar_Object::getYearOptions(self::$l10n); } - + + /* + * @brief: returns the options for an yearly repeating event which occurs on specific days of the year + * @return: array - valid inputs for yearly repeating events + */ public static function getByYearDayOptions(){ return OC_Calendar_Object::getByYearDayOptions(); } - + + /* + * @brief: returns the options for an yearly repeating event which occurs on specific month of the year + * @return: array - valid inputs for yearly repeating events + */ public static function getByMonthOptions(){ return OC_Calendar_Object::getByMonthOptions(self::$l10n); } + /* + * @brief: returns the options for an yearly repeating event which occurs on specific week numbers of the year + * @return: array - valid inputs for yearly repeating events + */ public static function getByWeekNoOptions(){ return OC_Calendar_Object::getByWeekNoOptions(); } - + + /* + * @brief: returns the options for an yearly or monthly repeating event which occurs on specific days of the month + * @return: array - valid inputs for yearly or monthly repeating events + */ public static function getByMonthDayOptions(){ return OC_Calendar_Object::getByMonthDayOptions(); } + /* + * @brief: returns the options for an monthly repeating event which occurs on specific weeks of the month + * @return: array - valid inputs for monthly repeating events + */ public static function getWeekofMonth(){ return OC_Calendar_Object::getWeekofMonth(self::$l10n); } - public static function prepareForOutput($event, $vevent){ - $return_event = array(); - $return_event['id'] = (int)$event['id']; - $return_event['title'] = htmlspecialchars(($event['summary']!=NULL || $event['summary'] != '')?$event['summary']: self::$l10n->t('unnamed')); - $return_event['description'] = isset($vevent->DESCRIPTION)?htmlspecialchars($vevent->DESCRIPTION->value):''; - $last_modified = $vevent->__get('LAST-MODIFIED'); + /* + * @brief: returns the prepared output for the json calendar data + * @param: array $event - array with event informations (self::getEventObject) + * @return: array - prepared output + */ + public static function prepareForOutput($event){ + if(isset($event['calendardata'])){ + $object = self::getVCalendar($event['calendardata'], false); + $vevent = $object->VEVENT; + }else{ + $vevent = $event['vevent']; + }$last_modified = $vevent->__get('LAST-MODIFIED'); if ($last_modified){ $lastmodified = $last_modified->getDateTime()->format('U'); }else{ $lastmodified = 0; } - $return_event['lastmodified'] = (int)$lastmodified; - return $return_event; + $last_modified = ($vevent->__get('LAST-MODIFIED'))?$last_modified->getDateTime()->format('U'):0; + $return = array('id'=>(int)$event['id'], + 'title' => htmlspecialchars(($event['summary']!=NULL || $event['summary'] != '')?$event['summary']: self::$l10n->t('unnamed')), + 'description' => isset($vevent->DESCRIPTION)?htmlspecialchars($vevent->DESCRIPTION->value):'', + 'lastmodified'=>(int)$lastmodified); + return $return; } } -- GitLab From ca2c7001c49a01d00b7d2f9ab924aa82366ad1ba Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 16:15:04 -0400 Subject: [PATCH 063/430] remove unused code in OC_Calendar_App class --- apps/calendar/lib/app.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/calendar/lib/app.php b/apps/calendar/lib/app.php index 8bc416d2ce4..f8bdbd4a36e 100644 --- a/apps/calendar/lib/app.php +++ b/apps/calendar/lib/app.php @@ -194,11 +194,6 @@ class OC_Calendar_App{ $vevent = $object->VEVENT; }else{ $vevent = $event['vevent']; - }$last_modified = $vevent->__get('LAST-MODIFIED'); - if ($last_modified){ - $lastmodified = $last_modified->getDateTime()->format('U'); - }else{ - $lastmodified = 0; } $last_modified = ($vevent->__get('LAST-MODIFIED'))?$last_modified->getDateTime()->format('U'):0; $return = array('id'=>(int)$event['id'], -- GitLab From 0fd8b1a04430fc36bd62a0828530dc2bc3910e81 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 31 Mar 2012 16:16:34 -0400 Subject: [PATCH 064/430] fix events.php for rewritten OC_Caledar_App class --- apps/calendar/ajax/events.php | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 196b2c3394f..94c05f58088 100755 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -1,12 +1,13 @@ + * Copyright (c) 2011, 2012 Georg Ehrke * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ require_once ('../../../lib/base.php'); +//IS THERE A NATIVE SUPPORT IN SABREDAV ??? require_once('when/When.php'); OC_JSON::checkLoggedIn(); @@ -43,14 +44,7 @@ if($_GET['calendar_id'] == 'shared_rw' || $_GET['calendar_id'] == 'shared_r'){ $user_timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); $return = array(); foreach($events as $event){ - if (isset($event['calendardata'])) { - $object = OC_VObject::parse($event['calendardata']); - $vevent = $object->VEVENT; - } else { - $vevent = $event['vevent']; - } - - $return_event = OC_Calendar_App::prepareForOutput($event, $vevent); + $return_event = OC_Calendar_App::prepareForOutput($event); $dtstart = $vevent->DTSTART; $start_dt = $dtstart->getDateTime(); -- GitLab From d896c19011d1cb74440e78bf6ff2aca4a999dd7c Mon Sep 17 00:00:00 2001 From: Scott Shambarger Date: Sat, 31 Mar 2012 20:16:42 -0700 Subject: [PATCH 065/430] cal import should group events by uid, export should have correct newlines, fix for oc-384 --- apps/calendar/export.php | 2 +- apps/calendar/import.php | 128 +++++++++++++++++++++------------------ 2 files changed, 70 insertions(+), 60 deletions(-) diff --git a/apps/calendar/export.php b/apps/calendar/export.php index 2736eec96c2..db3a83c92e9 100644 --- a/apps/calendar/export.php +++ b/apps/calendar/export.php @@ -11,7 +11,7 @@ OC_Util::checkLoggedIn(); OC_Util::checkAppEnabled('calendar'); $cal = isset($_GET['calid']) ? $_GET['calid'] : NULL; $event = isset($_GET['eventid']) ? $_GET['eventid'] : NULL; -$nl = "\n\r"; +$nl = "\r\n"; if(isset($cal)){ $calendar = OC_Calendar_App::getCalendar($cal); $calobjects = OC_Calendar_Object::all($cal); diff --git a/apps/calendar/import.php b/apps/calendar/import.php index b1c6f91df84..e5a5f0837f4 100644 --- a/apps/calendar/import.php +++ b/apps/calendar/import.php @@ -10,7 +10,8 @@ ob_start(); require_once ('../../lib/base.php'); OC_JSON::checkLoggedIn(); OC_Util::checkAppEnabled('calendar'); -$nl = "\n"; +$nl="\r\n"; +$comps = array('VEVENT'=>true, 'VTODO'=>true, 'VJOURNAL'=>true); $progressfile = 'import_tmp/' . md5(session_id()) . '.txt'; if(is_writable('import_tmp/')){ $progressfopen = fopen($progressfile, 'w'); @@ -29,85 +30,94 @@ if($_POST['method'] == 'new'){ } $id = $_POST['id']; } -//analyse the calendar file if(is_writable('import_tmp/')){ $progressfopen = fopen($progressfile, 'w'); fwrite($progressfopen, '20'); fclose($progressfopen); } -$searchfor = array('VEVENT', 'VTODO', 'VJOURNAL'); -$parts = $searchfor; -$filearr = explode($nl, $file); -$inelement = false; -$parts = array(); +// normalize the newlines +$file = str_replace(array("\r","\n\n"), array("\n","\n"), $file); +$lines = explode("\n", $file); +unset($file); +if(is_writable('import_tmp/')){ + $progressfopen = fopen($progressfile, 'w'); + fwrite($progressfopen, '30'); + fclose($progressfopen); +} +// analyze the file, group components by uid, and keep refs to originating calendar object +// $cals is array calendar objects, keys are 1st line# $cal, ie array( $cal => $caldata ) +// $caldata is array( 'first' => 1st component line#, 'last' => last comp line#, 'end' => end line# ) +// $caldata is used to create prefix/suffix strings when building import text +// $uids is array of component arrays, keys are $uid, ie array( $uid => array( $beginlineno => $component ) ) +// $component is array( 'end' => end line#, 'cal'=> $cal ) +$comp=$uid=$cal=false; +$cals=$uids=array(); $i = 0; -foreach($filearr as $line){ - foreach($searchfor as $search){ - if(substr_count($line, $search) == 1){ - list($attr, $val) = explode(':', $line); - if($attr == 'BEGIN'){ - $parts[]['begin'] = $i; - $inelement = true; +foreach($lines as $line) { + + if(strpos($line, ':')!==false) { + list($attr, $val) = explode(':', strtoupper($line)); + if ($attr == 'BEGIN' && $val == 'VCALENDAR') { + $cal = $i; + $cals[$cal] = array('first'=>$i,'last'=>$i,'end'=>$i); + } elseif ($attr =='BEGIN' && $cal!==false && isset($comps[$val])) { + $comp = $val; + $beginNo = $i; + } elseif ($attr == 'END' && $cal!==false && $val == 'VCALENDAR') { + if($comp!==false) { + unset($cals[$cal]); // corrupt calendar, unset it + } else { + $cals[$cal]['end'] = $i; + } + $comp=$uid=$cal=false; // reset calendar + } elseif ($attr == 'END' && $comp!==false && $val == $comp) { + if(! $uid) { + $uid = OC_Calendar_Object::createUID(); } - if($attr == 'END'){ - $parts[count($parts) - 1]['end'] = $i; - $inelement = false; + $uids[$uid][$beginNo] = array('end'=>$i, 'cal'=>$cal); + if ($cals[$cal]['first'] == $cal) { + $cals[$cal]['first'] = $beginNo; } + $cals[$cal]['last'] = $i; + $comp=$uid=false; // reset component + } elseif ($attr =="UID" && $comp!==false) { + list($attr, $uid) = explode(':', $line); } } $i++; } -//import the calendar +// import the calendar if(is_writable('import_tmp/')){ $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '40'); + fwrite($progressfopen, '60'); fclose($progressfopen); } -$start = ''; -for ($i = 0; $i < $parts[0]['begin']; $i++) { - if($i == 0){ - $start = $filearr[0]; - }else{ - $start .= $nl . $filearr[$i]; - } -} -$end = ''; -for($i = $parts[count($parts) - 1]['end'] + 1;$i <= count($filearr) - 1; $i++){ - if($i == $parts[count($parts) - 1]['end'] + 1){ - $end = $filearr[$parts[count($parts) - 1]['end'] + 1]; - }else{ - $end .= $nl . $filearr[$i]; - } -} -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '50'); - fclose($progressfopen); -} -$importready = array(); -foreach($parts as $part){ - for($i = $part['begin']; $i <= $part['end'];$i++){ - if($i == $part['begin']){ - $content = $filearr[$i]; - }else{ - $content .= $nl . $filearr[$i]; +foreach($uids as $uid) { + + $prefix=$suffix=$content=array(); + foreach($uid as $begin=>$details) { + + $cal = $details['cal']; + if(!isset($cals[$cal])) { + continue; // from corrupt/incomplete calendar + } + $cdata = $cals[$cal]; + // if we have multiple components from different calendar objects, + // we should really merge their elements (enhancement?) -- 1st one wins for now. + if(! count($prefix)) { + $prefix = array_slice($lines, $cal, $cdata['first'] - $cal); } + if(! count($suffix)) { + $suffix = array_slice($lines, $cdata['last']+1, $cdata['end'] - $cdata['last']); + } + $content = array_merge($content, array_slice($lines, $begin, $details['end'] - $begin + 1)); } - $importready[] = $start . $nl . $content . $nl . $end; -} -if(is_writable('import_tmp/')){ - $progressfopen = fopen($progressfile, 'w'); - fwrite($progressfopen, '70'); - fclose($progressfopen); -} -if(count($parts) == 1){ - OC_Calendar_Object::add($id, $file); -}else{ - foreach($importready as $import){ + if(count($content)) { + $import = join($nl, array_merge($prefix, $content, $suffix)) . $nl; OC_Calendar_Object::add($id, $import); } } -//done the import +// finished import if(is_writable('import_tmp/')){ $progressfopen = fopen($progressfile, 'w'); fwrite($progressfopen, '100'); -- GitLab From 72a43b39291046637c17071c6bb48510ae1c7826 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 2 Apr 2012 08:32:27 -0400 Subject: [PATCH 066/430] revert 0fd8b1a04430fc36bd62a0828530dc2bc3910e81 --- apps/calendar/ajax/events.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 94c05f58088..196b2c3394f 100755 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -1,13 +1,12 @@ + * Copyright (c) 2011 Georg Ehrke * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ require_once ('../../../lib/base.php'); -//IS THERE A NATIVE SUPPORT IN SABREDAV ??? require_once('when/When.php'); OC_JSON::checkLoggedIn(); @@ -44,7 +43,14 @@ if($_GET['calendar_id'] == 'shared_rw' || $_GET['calendar_id'] == 'shared_r'){ $user_timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); $return = array(); foreach($events as $event){ - $return_event = OC_Calendar_App::prepareForOutput($event); + if (isset($event['calendardata'])) { + $object = OC_VObject::parse($event['calendardata']); + $vevent = $object->VEVENT; + } else { + $vevent = $event['vevent']; + } + + $return_event = OC_Calendar_App::prepareForOutput($event, $vevent); $dtstart = $vevent->DTSTART; $start_dt = $dtstart->getDateTime(); -- GitLab From e18c0d54f6f424614cc6e4da3beb704efaab702f Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:35:29 -0400 Subject: [PATCH 067/430] add output functions and access function to app.php of calendar --- apps/calendar/lib/app.php | 248 ++++++++++++++++++++++++++++++-------- 1 file changed, 196 insertions(+), 52 deletions(-) diff --git a/apps/calendar/lib/app.php b/apps/calendar/lib/app.php index f8bdbd4a36e..40de6deb432 100644 --- a/apps/calendar/lib/app.php +++ b/apps/calendar/lib/app.php @@ -8,22 +8,30 @@ * * This class manages our app actions */ -OC_Calendar_App::$l10n = new OC_L10N('calendar'); +self::$l10n = new OC_L10N('calendar'); +self::$tz = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); class OC_Calendar_App{ + const CALENDAR = 'calendar'; + const EVENT = 'event'; /* - * @brief: language object for calendar app + * @brief language object for calendar app */ public static $l10n; /* - * @brief: returns informations about a calendar - * @param: int $id - id of the calendar - * @param: bool $security - check access rights or not - * @param: bool $shared - check if the user got access via sharing - * @return: mixed - bool / array + * @brief timezone of the user + */ + public static $tz; + + /* + * @brief returns informations about a calendar + * @param int $id - id of the calendar + * @param bool $security - check access rights or not + * @param bool $shared - check if the user got access via sharing + * @return mixed - bool / array */ public static function getCalendar($id, $security = true, $shared = false){ - $calendar = OC_Calendar_Object::find($id); + $calendar = OC_Calendar_Calendar::find($id); if($shared === true){ if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::CALENDAR)){ return $calendar; @@ -41,17 +49,17 @@ class OC_Calendar_App{ } /* - * @brief: returns informations about an event - * @param: int $id - id of the event - * @param: bool $security - check access rights or not - * @param: bool $shared - check if the user got access via sharing - * @return: mixed - bool / array + * @brief returns informations about an event + * @param int $id - id of the event + * @param bool $security - check access rights or not + * @param bool $shared - check if the user got access via sharing + * @return mixed - bool / array */ public static function getEventObject($id, $security = true, $shared = false){ $event = OC_Calendar_Object::find($id); if($shared === true){ if(OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::EVENT)){ - return $calendar; + return $event; } } if($security === true){ @@ -67,10 +75,10 @@ class OC_Calendar_App{ } /* - * @brief: returns the parsed calendar data - * @param: int $id - id of the event - * @param: bool $security - check access rights or not - * @return: mixed - bool / object + * @brief returns the parsed calendar data + * @param int $id - id of the event + * @param bool $security - check access rights or not + * @return mixed - bool / object */ public static function getVCalendar($id, $security = true){ $event_object = self::getEventObject($id, $security); @@ -85,7 +93,10 @@ class OC_Calendar_App{ } /* - * + * @brief checks if an event was edited and dies if it was + * @param (object) $vevent - vevent object of the event + * @param (int) $lastmodified - time of last modification as unix timestamp + * @return (bool) */ public static function isNotModified($vevent, $lastmodified){ $last_modified = $vevent->__get('LAST-MODIFIED'); @@ -93,113 +104,246 @@ class OC_Calendar_App{ OC_JSON::error(array('modified'=>true)); exit; } + return true; } /* * THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED SOON - * @brief: returns the valid categories - * @return: array - categories + * @brief returns the valid categories + * @return array - categories */ public static function getCategoryOptions(){ return OC_Calendar_Object::getCategoryOptions(self::$l10n); } /* - * @brief: returns the options for an repeating event - * @return: array - valid inputs for repeating events + * @brief returns the options for an repeating event + * @return array - valid inputs for repeating events */ public static function getRepeatOptions(){ return OC_Calendar_Object::getRepeatOptions(self::$l10n); } /* - * @brief: returns the options for the end of an repeating event - * @return: array - valid inputs for the end of an repeating events + * @brief returns the options for the end of an repeating event + * @return array - valid inputs for the end of an repeating events */ public static function getEndOptions(){ return OC_Calendar_Object::getEndOptions(self::$l10n); } /* - * @brief: returns the options for an monthly repeating event - * @return: array - valid inputs for monthly repeating events + * @brief returns the options for an monthly repeating event + * @return array - valid inputs for monthly repeating events */ public static function getMonthOptions(){ return OC_Calendar_Object::getMonthOptions(self::$l10n); } /* - * @brief: returns the options for an weekly repeating event - * @return: array - valid inputs for weekly repeating events + * @brief returns the options for an weekly repeating event + * @return array - valid inputs for weekly repeating events */ public static function getWeeklyOptions(){ return OC_Calendar_Object::getWeeklyOptions(self::$l10n); } /* - * @brief: returns the options for an yearly repeating event - * @return: array - valid inputs for yearly repeating events + * @brief returns the options for an yearly repeating event + * @return array - valid inputs for yearly repeating events */ public static function getYearOptions(){ return OC_Calendar_Object::getYearOptions(self::$l10n); } /* - * @brief: returns the options for an yearly repeating event which occurs on specific days of the year - * @return: array - valid inputs for yearly repeating events + * @brief returns the options for an yearly repeating event which occurs on specific days of the year + * @return array - valid inputs for yearly repeating events */ public static function getByYearDayOptions(){ return OC_Calendar_Object::getByYearDayOptions(); } /* - * @brief: returns the options for an yearly repeating event which occurs on specific month of the year - * @return: array - valid inputs for yearly repeating events + * @brief returns the options for an yearly repeating event which occurs on specific month of the year + * @return array - valid inputs for yearly repeating events */ public static function getByMonthOptions(){ return OC_Calendar_Object::getByMonthOptions(self::$l10n); } /* - * @brief: returns the options for an yearly repeating event which occurs on specific week numbers of the year - * @return: array - valid inputs for yearly repeating events + * @brief returns the options for an yearly repeating event which occurs on specific week numbers of the year + * @return array - valid inputs for yearly repeating events */ public static function getByWeekNoOptions(){ return OC_Calendar_Object::getByWeekNoOptions(); } /* - * @brief: returns the options for an yearly or monthly repeating event which occurs on specific days of the month - * @return: array - valid inputs for yearly or monthly repeating events + * @brief returns the options for an yearly or monthly repeating event which occurs on specific days of the month + * @return array - valid inputs for yearly or monthly repeating events */ public static function getByMonthDayOptions(){ return OC_Calendar_Object::getByMonthDayOptions(); } /* - * @brief: returns the options for an monthly repeating event which occurs on specific weeks of the month - * @return: array - valid inputs for monthly repeating events + * @brief returns the options for an monthly repeating event which occurs on specific weeks of the month + * @return array - valid inputs for monthly repeating events */ public static function getWeekofMonth(){ return OC_Calendar_Object::getWeekofMonth(self::$l10n); } /* - * @brief: returns the prepared output for the json calendar data - * @param: array $event - array with event informations (self::getEventObject) - * @return: array - prepared output + * @brief checks the access for a calendar / an event + * @param (int) $id - id of the calendar / event + * @param (string) $type - type of the id (calendar/event) + * @return (string) $access - level of access + */ + public static function getaccess($id, $type){ + if($type == self::CALENDAR){ + $calendar = self::getCalendar($id, false, false); + if($calendar['userid'] == OC_User::getUser()){ + return 'owner'; + } + $isshared = OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::CALENDAR); + if($isshared){ + $writeaccess = OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::CALENDAR); + if($writeaccess){ + return 'rw'; + }else{ + return 'r'; + } + }else{ + return false; + } + }elseif($type == self::EVENT){ + if(OC_Calendar_Object::getowner($id) == OC_User::getUser()){ + return 'owner'; + } + $isshared = OC_Calendar_Share::check_access(OC_User::getUser(), $id, OC_Calendar_Share::EVENT); + if($isshared){ + $writeaccess = OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::EVENT); + if($writeaccess){ + return 'rw'; + }else{ + return 'r'; + } + }else{ + return false; + } + } + } + + /* + * @brief analyses the parameter for calendar parameter and returns the objects + * @param (string) $calendarid - calendarid + * @param (int) $start - unixtimestamp of start + * @param (int) $end - unixtimestamp of end + * @return (array) $events */ - public static function prepareForOutput($event){ - if(isset($event['calendardata'])){ - $object = self::getVCalendar($event['calendardata'], false); + public static function getrequestedEvents($calendarid, $start, $end){ + + $events = array(); + if($calendarid == 'shared_rw' || $_GET['calendar_id'] == 'shared_r'){ + $calendars = OC_Calendar_Share::allSharedwithuser(OC_USER::getUser(), OC_Calendar_Share::CALENDAR, 1, ($_GET['calendar_id'] == 'shared_rw')?'rw':'r'); + foreach($calendars as $calendar){ + $calendarevents = OC_Calendar_Object::allInPeriod($calendar['calendarid'], $start, $end); + $events = array_merge($events, $calendarevents); + } + $singleevents = OC_Calendar_Share::allSharedwithuser(OC_USER::getUser(), OC_Calendar_Share::EVENT, 1, ($_GET['calendar_id'] == 'shared_rw')?'rw':'r'); + foreach($singleevents as $singleevent){ + $event = OC_Calendar_Object::find($singleevent['eventid']); + $events = array_merge($events, $event); + } + }else{ + $calendar_id = $_GET['calendar_id']; + if (is_numeric($calendar_id)) { + $calendar = self::getCalendar($calendar_id); + OC_Response::enableCaching(0); + OC_Response::setETagHeader($calendar['ctag']); + $events = OC_Calendar_Object::allInPeriod($calendar_id, $start, $end); + } else { + OC_Hook::emit('OC_Calendar', 'getEvents', array('calendar_id' => $calendar_id, 'events' => &$events)); + } + } + return $events; + } + + /* + * @brief generates the output for an event which will be readable for our js + * @param (mixed) $event - event object / array + * @param (int) $start - unixtimestamp of start + * @param (int) $end - unixtimestamp of end + * @return (array) $output - readable output + */ + public static function generateEventOutput($event, $start, $end){ + $output = array(); + + if(array_key_exists('calendardata', $event)){ + $object = OC_VObject::parse($event['calendardata']); $vevent = $object->VEVENT; }else{ $vevent = $event['vevent']; } - $last_modified = ($vevent->__get('LAST-MODIFIED'))?$last_modified->getDateTime()->format('U'):0; - $return = array('id'=>(int)$event['id'], + + $last_modified = @$vevent->__get('LAST-MODIFIED'); + $lastmodified = ($last_modified)?$last_modified->getDateTime()->format('U'):0; + + $output = array('id'=>(int)$event['id'], 'title' => htmlspecialchars(($event['summary']!=NULL || $event['summary'] != '')?$event['summary']: self::$l10n->t('unnamed')), 'description' => isset($vevent->DESCRIPTION)?htmlspecialchars($vevent->DESCRIPTION->value):'', - 'lastmodified'=>(int)$lastmodified); - return $return; + 'lastmodified'=>$lastmodified); + + $dtstart = $vevent->DTSTART; + $start_dt = $dtstart->getDateTime(); + $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); + $end_dt = $dtend->getDateTime(); + + if ($dtstart->getDateType() == Sabre_VObject_Element_DateTime::DATE){ + $output['allDay'] = true; + }else{ + $output['allDay'] = false; + $start_dt->setTimezone(new DateTimeZone(self::$tz)); + $end_dt->setTimezone(new DateTimeZone(self::$tz)); + } + + if($event['repeating'] == 1){ + $duration = (double) $end_dt->format('U') - (double) $start_dt->format('U'); + $r = new When(); + $r->recur($start_dt)->rrule((string) $vevent->RRULE); + /*$r = new iCal_Repeat_Generator(array('RECUR' => $start_dt, + * 'RRULE' => (string)$vevent->RRULE + * 'RDATE' => (string)$vevent->RDATE + * 'EXRULE' => (string)$vevent->EXRULE + * 'EXDATE' => (string)$vevent->EXDATE));*/ + while($result = $r->next()){ + if($result < $start){ + continue; + } + if($result > $end){ + break; + } + if($output['allDay'] == true){ + $output['start'] = $result->format('Y-m-d'); + $output['end'] = date('Y-m-d', $result->format('U') + --$duration); + }else{ + $output['start'] = $result->format('Y-m-d H:i:s'); + $output['end'] = date('Y-m-d H:i:s', $result->format('U') + $duration); + } + $output[] = $output; + } + }else{ + if($output['allDay'] == true){ + $output['start'] = $start_dt->format('Y-m-d'); + $end_dt->modify('-1 sec'); + $output['end'] = $end_dt->format('Y-m-d'); + }else{ + $output['start'] = $start_dt->format('Y-m-d H:i:s'); + $output['end'] = $end_dt->format('Y-m-d H:i:s'); + } + $output[] = $output; + } } -} +} \ No newline at end of file -- GitLab From eef9a1e7ed63a3d6506afd0dbf84d16fbf8c1064 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:37:26 -0400 Subject: [PATCH 068/430] add access check to ajax files --- apps/calendar/ajax/event/delete.php | 11 ++++++----- apps/calendar/ajax/event/edit.form.php | 13 ++++++------- apps/calendar/ajax/event/edit.php | 9 ++++++++- apps/calendar/ajax/event/move.php | 9 ++++++--- apps/calendar/ajax/event/resize.php | 5 +++-- 5 files changed, 29 insertions(+), 18 deletions(-) diff --git a/apps/calendar/ajax/event/delete.php b/apps/calendar/ajax/event/delete.php index 862dec6bf5b..6307e1a0f27 100644 --- a/apps/calendar/ajax/event/delete.php +++ b/apps/calendar/ajax/event/delete.php @@ -7,13 +7,14 @@ */ require_once('../../../../lib/base.php'); -$l10n = new OC_L10N('calendar'); - OC_JSON::checkLoggedIn(); OC_JSON::checkAppEnabled('calendar'); $id = $_POST['id']; -$event_object = OC_Calendar_App::getEventObject($id); +$access = OC_Calendar_App::getaccess($id, OC_Calendar_App::EVENT); +if($access != 'owner' && $access != 'rw'){ + OC_JSON::error(array('message'=>'permission denied')); + exit; +} $result = OC_Calendar_Object::delete($id); -OC_JSON::success(); -?> +OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/ajax/event/edit.form.php b/apps/calendar/ajax/event/edit.form.php index ab77a747f1c..a2e3fe6163f 100644 --- a/apps/calendar/ajax/event/edit.form.php +++ b/apps/calendar/ajax/event/edit.form.php @@ -14,15 +14,14 @@ if(!OC_USER::isLoggedIn()) { OC_JSON::checkAppEnabled('calendar'); $id = $_GET['id']; -$data = OC_Calendar_App::getEventObject($id); -$object = OC_VObject::parse($data['calendardata']); -$vevent = $object->VEVENT; - -$access = OC_Calendar_App::check_access($id); -if(!$access){ +$data = OC_Calendar_App::getEventObject($id, true, true); +if(!$data){ OC_JSON::error(array('data' => array('message' => self::$l10n->t('Wrong calendar')))); exit; } +$access = OC_Calendar_App::getaccess($id, OC_Calendar_Share::EVENT); +$object = OC_VObject::parse($data['calendardata']); +$vevent = $object->VEVENT; $dtstart = $vevent->DTSTART; $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); @@ -214,7 +213,7 @@ if($access == 'owner' || $access == 'rw'){ $tmpl = new OC_Template('calendar', 'part.showevent'); } -$tmpl->assign('id', $id); +$tmpl->assign('eventid', $id); $tmpl->assign('lastmodified', $lastmodified); $tmpl->assign('calendar_options', $calendar_options); $tmpl->assign('category_options', $category_options); diff --git a/apps/calendar/ajax/event/edit.php b/apps/calendar/ajax/event/edit.php index 64daffddef0..8dd99b2b100 100644 --- a/apps/calendar/ajax/event/edit.php +++ b/apps/calendar/ajax/event/edit.php @@ -10,13 +10,20 @@ require_once('../../../../lib/base.php'); OC_JSON::checkLoggedIn(); OC_JSON::checkAppEnabled('calendar'); +$id = $_POST['id']; + +$access = OC_Calendar_App::getaccess($id, OC_Calendar_App::EVENT); +if($access != 'owner' && $access != 'rw'){ + OC_JSON::error(array('message'=>'permission denied')); + exit; +} + $errarr = OC_Calendar_Object::validateRequest($_POST); if($errarr){ //show validate errors OC_JSON::error($errarr); exit; }else{ - $id = $_POST['id']; $cal = $_POST['calendar']; $data = OC_Calendar_App::getEventObject($id); $vcalendar = OC_VObject::parse($data['calendardata']); diff --git a/apps/calendar/ajax/event/move.php b/apps/calendar/ajax/event/move.php index 8150fdbaa32..c6743e2354f 100644 --- a/apps/calendar/ajax/event/move.php +++ b/apps/calendar/ajax/event/move.php @@ -9,7 +9,11 @@ require_once('../../../../lib/base.php'); OC_JSON::checkLoggedIn(); $id = $_POST['id']; - +$access = OC_Calendar_App::getaccess($id, OC_Calendar_App::EVENT); +if($access != 'owner' && $access != 'rw'){ + OC_JSON::error(array('message'=>'permission denied')); + exit; +} $vcalendar = OC_Calendar_App::getVCalendar($id); $vevent = $vcalendar->VEVENT; @@ -17,7 +21,6 @@ $allday = $_POST['allDay']; $delta = new DateInterval('P0D'); $delta->d = $_POST['dayDelta']; $delta->i = $_POST['minuteDelta']; - OC_Calendar_App::isNotModified($vevent, $_POST['lastmodified']); $dtstart = $vevent->DTSTART; @@ -40,4 +43,4 @@ $vevent->setDateTime('DTSTAMP', 'now', Sabre_VObject_Element_DateTime::UTC); $result = OC_Calendar_Object::edit($id, $vcalendar->serialize()); $lastmodified = $vevent->__get('LAST-MODIFIED')->getDateTime(); -OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); +OC_JSON::success(array('lastmodified'=>(int)$lastmodified->format('U'))); \ No newline at end of file diff --git a/apps/calendar/ajax/event/resize.php b/apps/calendar/ajax/event/resize.php index 1136273b706..a2ae83111b8 100644 --- a/apps/calendar/ajax/event/resize.php +++ b/apps/calendar/ajax/event/resize.php @@ -10,8 +10,9 @@ OC_JSON::checkLoggedIn(); $id = $_POST['id']; -if(!OC_Calendar_Share::is_editing_allowed(OC_User::getUser(), $id, OC_Calendar_Share::EVENT) && OC_Calendar_Object::getowner($id) != OC_User::getUser()){ - OC_JSON::error(array('message'=>'permissiondenied')); +$access = OC_Calendar_App::getaccess($id, OC_Calendar_App::EVENT); +if($access != 'owner' && $access != 'rw'){ + OC_JSON::error(array('message'=>'permission denied')); exit; } -- GitLab From e940152bcef6394e3a4bc75d0d3054f6a18e0ce4 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:39:02 -0400 Subject: [PATCH 069/430] fix bugs in share lib of calendar --- apps/calendar/lib/share.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index 3e03a2d7ccf..b4abcc08dd9 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -20,7 +20,11 @@ class OC_Calendar_Share{ public static function allSharedwithuser($userid, $type, $active=null, $permission=null){ $group_where = self::group_sql(OC_Group::getUserGroups($userid)); $permission_where = self::permission_sql($permission); - $active_where = self::active_sql($active); + if($type == self::CALENDAR){ + $active_where = self::active_sql($active); + }else{ + $active_where = ''; + } $stmt = OC_DB::prepare('SELECT * FROM *PREFIX*calendar_share_' . $type . ' WHERE ((share = ? AND sharetype = "user") ' . $group_where . ') AND owner <> ? ' . $permission_where . ' ' . $active_where); $result = $stmt->execute(array($userid, $userid)); $return = array(); @@ -66,7 +70,7 @@ class OC_Calendar_Share{ return false; } if($sharetype == 'public'){ - $share = self::generate_token(); + $share = self::generate_token($id, $type); } $stmt = OC_DB::prepare('INSERT INTO *PREFIX*calendar_share_' . $type . ' (owner,share,sharetype,' . $type . 'id,permissions' . (($type == self::CALENDAR)?', active':'') . ') VALUES(?,?,?,?,0' . (($type == self::CALENDAR)?', 1':'') . ')' ); $result = $stmt->execute(array($owner,$share,$sharetype,$id)); @@ -193,8 +197,8 @@ class OC_Calendar_Share{ return true; } if($type == self::EVENT){ - $calendar == OC_Calendar_App::getCalendar($id); - return self::is_editing_allowed($share, $calendar['id'], self::CALENDAR); + $event = OC_Calendar_App::getEventObject($id, false, false); + return self::is_editing_allowed($share, $event['calendarid'], self::CALENDAR); } return false; } @@ -213,8 +217,8 @@ class OC_Calendar_Share{ return true; } if($type == self::EVENT){ - $calendar == OC_Calendar_App::getCalendar($id); - return self::check_access($share, $calendar['id'], self::CALENDAR); + $event = OC_Calendar_App::getEventObject($id, false, false); + return self::is_editing_allowed($share, $event['calendarid'], self::CALENDAR); } return false; } -- GitLab From 4d884c384968ce5df49669dc9ca28c177e4f2399 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:39:37 -0400 Subject: [PATCH 070/430] clean up events.php of calendar --- apps/calendar/ajax/events.php | 93 ++++------------------------------- 1 file changed, 10 insertions(+), 83 deletions(-) diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php index 196b2c3394f..21e816b1275 100755 --- a/apps/calendar/ajax/events.php +++ b/apps/calendar/ajax/events.php @@ -1,99 +1,26 @@ + * Copyright (c) 2011, 2012 Georg Ehrke * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ require_once ('../../../lib/base.php'); -require_once('when/When.php'); +require_once(OC::$THIRDPARTYROOT . 'when/When.php'); OC_JSON::checkLoggedIn(); OC_JSON::checkAppEnabled('calendar'); -if(version_compare(PHP_VERSION, '5.3.0', '>=')){ - $start = DateTime::createFromFormat('U', $_GET['start']); - $end = DateTime::createFromFormat('U', $_GET['end']); -}else{ - $start = new DateTime('@' . $_GET['start']); - $end = new DateTime('@' . $_GET['end']); -} +$start = (version_compare(PHP_VERSION, '5.3.0', '>='))?DateTime::createFromFormat('U', $_GET['start']):new DateTime('@' . $_GET['start']); +$end = (version_compare(PHP_VERSION, '5.3.0', '>='))?DateTime::createFromFormat('U', $_GET['end']):new DateTime('@' . $_GET['end']); -if($_GET['calendar_id'] == 'shared_rw' || $_GET['calendar_id'] == 'shared_r'){ - $calendars = OC_Calendar_Share::allSharedwithuser(OC_USER::getUser(), OC_Calendar_Share::CALENDAR, 1, ($_GET['calendar_id'] == 'shared_rw')?'rw':'r'); - $events = array(); - foreach($calendars as $calendar){ - $calendarevents = OC_Calendar_Object::allInPeriod($calendar['calendarid'], $start, $end); - $events = array_merge($events, $calendarevents); - } -}else{ - $calendar_id = $_GET['calendar_id']; - if (is_numeric($calendar_id)) { - $calendar = OC_Calendar_App::getCalendar($calendar_id); - OC_Response::enableCaching(0); - OC_Response::setETagHeader($calendar['ctag']); - $events = OC_Calendar_Object::allInPeriod($calendar_id, $start, $end); - } else { - $events = array(); - OC_Hook::emit('OC_Calendar', 'getEvents', array('calendar_id' => $calendar_id, 'events' => &$events)); - } -} +$events = OC_Calendar_App::getrequestedEvents($_GET['calendar_id'], $start, $end); -$user_timezone = OC_Preferences::getValue(OC_USER::getUser(), 'calendar', 'timezone', date_default_timezone_get()); -$return = array(); +$output = array(); foreach($events as $event){ - if (isset($event['calendardata'])) { - $object = OC_VObject::parse($event['calendardata']); - $vevent = $object->VEVENT; - } else { - $vevent = $event['vevent']; - } - - $return_event = OC_Calendar_App::prepareForOutput($event, $vevent); - - $dtstart = $vevent->DTSTART; - $start_dt = $dtstart->getDateTime(); - $dtend = OC_Calendar_Object::getDTEndFromVEvent($vevent); - $end_dt = $dtend->getDateTime(); - if ($dtstart->getDateType() == Sabre_VObject_Element_DateTime::DATE){ - $return_event['allDay'] = true; - }else{ - $return_event['allDay'] = false; - $start_dt->setTimezone(new DateTimeZone($user_timezone)); - $end_dt->setTimezone(new DateTimeZone($user_timezone)); - } - if($event['repeating'] == 1){ - $duration = (double) $end_dt->format('U') - (double) $start_dt->format('U'); - $r = new When(); - $r->recur($start_dt)->rrule((string) $vevent->RRULE); - while($result = $r->next()){ - if($result < $start){ - continue; - } - if($result > $end){ - break; - } - if($return_event['allDay'] == true){ - $return_event['start'] = $result->format('Y-m-d'); - $return_event['end'] = date('Y-m-d', $result->format('U') + --$duration); - }else{ - $return_event['start'] = $result->format('Y-m-d H:i:s'); - $return_event['end'] = date('Y-m-d H:i:s', $result->format('U') + $duration); - } - $return[] = $return_event; - } - }else{ - if($return_event['allDay'] == true){ - $return_event['start'] = $start_dt->format('Y-m-d'); - $end_dt->modify('-1 sec'); - $return_event['end'] = $end_dt->format('Y-m-d'); - }else{ - $return_event['start'] = $start_dt->format('Y-m-d H:i:s'); - $return_event['end'] = $end_dt->format('Y-m-d H:i:s'); - } - $return[] = $return_event; - } + $output[] = OC_Calendar_App::generateEventOutput($event, $start, $end); } -OC_JSON::encodedPrint($return); -?> + +OC_JSON::encodedPrint($output); +?> \ No newline at end of file -- GitLab From 97d216c94d20ec23f8e88ecf490cdaae51ce3b7b Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:40:20 -0400 Subject: [PATCH 071/430] add dropdown to eventform --- apps/calendar/templates/part.eventform.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php index c4c3ae1c1e2..e4bae3d4f81 100644 --- a/apps/calendar/templates/part.eventform.php +++ b/apps/calendar/templates/part.eventform.php @@ -1,3 +1,9 @@ + + @@ -241,4 +247,6 @@
    //Alarm
    //Attendees
    -
    //Share
    +
    + inc('share.dropdown'); ?> +
    -- GitLab From 5a4237a31dd326b6ce46a6a7f1e9f45d103f51b6 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 7 Apr 2012 22:41:24 -0400 Subject: [PATCH 072/430] make dropdown menu work with single event sharing --- apps/calendar/templates/share.dropdown.php | 26 +++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/apps/calendar/templates/share.dropdown.php b/apps/calendar/templates/share.dropdown.php index ca1e128ea78..4e9f41ead14 100644 --- a/apps/calendar/templates/share.dropdown.php +++ b/apps/calendar/templates/share.dropdown.php @@ -1,13 +1,19 @@ @@ -31,7 +37,7 @@ echo html_select_options($allusers, array());
    diff --git a/apps/gallery/templates/view_album.php b/apps/gallery/templates/view_album.php index 6b513a672d5..f938e487954 100644 --- a/apps/gallery/templates/view_album.php +++ b/apps/gallery/templates/view_album.php @@ -5,7 +5,7 @@ OC_Util::addScript('gallery', 'album_cover'); OC_Util::addScript('files_imageviewer', 'jquery.mousewheel-3.0.4.pack'); OC_Util::addScript('files_imageviewer', 'jquery.fancybox-1.3.4.pack'); OC_Util::addStyle( 'files_imageviewer', 'jquery.fancybox-1.3.4' ); -$l = new OC_L10N('gallery'); +$l = OC_L10N::get('gallery'); ?> '; + // Hack so the end script tag isn't counted if this is inline JS. + src += ''; for (var i = 0, ii = names.length; i < ii; ++i) { src += '

    Hi

    '; } @@ -12535,20 +14119,20 @@ function getUnicodeRangeFor(value) { return -1; } -function adaptUnicode(unicode) { - return (unicode <= 0x1F || (unicode >= 127 && unicode < kSizeOfGlyphArea)) ? - unicode + kCmapGlyphOffset : unicode; -} - -function isAdaptedUnicode(unicode) { - return unicode >= kCmapGlyphOffset && - unicode < kCmapGlyphOffset + kSizeOfGlyphArea; +function isRTLRangeFor(value) { + var range = UnicodeRanges[13]; + if (value >= range.begin && value < range.end) + return true; + range = UnicodeRanges[11]; + if (value >= range.begin && value < range.end) + return true; + return false; } function isSpecialUnicode(unicode) { return (unicode <= 0x1F || (unicode >= 127 && unicode < kSizeOfGlyphArea)) || - unicode >= kCmapGlyphOffset && - unicode < kCmapGlyphOffset + kSizeOfGlyphArea; + (unicode >= kCmapGlyphOffset && + unicode < kCmapGlyphOffset + kSizeOfGlyphArea); } /** @@ -12559,18 +14143,19 @@ function isSpecialUnicode(unicode) { * var type1Font = new Font("MyFontName", binaryFile, propertiesObject); * type1Font.bind(); */ -var Font = (function Font() { - var constructor = function font_constructor(name, file, properties) { +var Font = (function FontClosure() { + function Font(name, file, properties) { this.name = name; this.coded = properties.coded; - this.charProcIRQueues = properties.charProcIRQueues; + this.charProcOperatorList = properties.charProcOperatorList; this.resources = properties.resources; this.sizes = []; var names = name.split('+'); names = names.length > 1 ? names[1] : names[0]; names = names.split(/[-,_]/g)[0]; - this.serif = serifFonts[names] || (name.search(/serif/gi) != -1); + this.isSerifFont = !!(properties.flags & FontFlags.Serif); + this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic); var type = properties.type; this.type = type; @@ -12578,7 +14163,7 @@ var Font = (function Font() { // If the font is to be ignored, register it like an already loaded font // to avoid the cost of waiting for it be be loaded by the platform. if (properties.ignore) { - this.loadedName = this.serif ? 'serif' : 'sans-serif'; + this.loadedName = this.isSerifFont ? 'serif' : 'sans-serif'; this.loading = false; return; } @@ -12587,21 +14172,30 @@ var Font = (function Font() { this.widths = properties.widths; this.defaultWidth = properties.defaultWidth; this.composite = properties.composite; - this.toUnicode = properties.toUnicode; this.hasEncoding = properties.hasEncoding; this.fontMatrix = properties.fontMatrix; - if (properties.type == 'Type3') + this.widthMultiplier = 1.0; + if (properties.type == 'Type3') { + this.encoding = properties.baseEncoding; return; + } // Trying to fix encoding using glyph CIDSystemInfo. this.loadCidToUnicode(properties); + if (properties.toUnicode) + this.toUnicode = properties.toUnicode; + else + this.rebuildToUnicode(properties); + + this.toFontChar = this.buildToFontChar(this.toUnicode); + if (!file) { // The file data is not specified. Trying to fix the font name // to be used with the canvas.font. var fontName = name.replace(/[,_]/g, '-'); - fontName = stdFontMap[fontName] || fontName; + fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName; this.bold = (fontName.search(/bold/gi) != -1); this.italic = (fontName.search(/oblique/gi) != -1) || @@ -12626,7 +14220,7 @@ var Font = (function Font() { var subtype = properties.subtype; var cff = (subtype == 'Type1C' || subtype == 'CIDFontType0C') ? - new Type2CFF(file, properties) : new CFF(name, file, properties); + new CFFFont(file, properties) : new Type1Font(name, file, properties); // Wrap the CFF data inside an OTF font file data = this.convert(name, cff, properties); @@ -12648,9 +14242,10 @@ var Font = (function Font() { this.data = data; this.fontMatrix = properties.fontMatrix; + this.widthMultiplier = !properties.fontMatrix ? 1.0 : + 1.0 / properties.fontMatrix[0]; this.encoding = properties.baseEncoding; - this.hasShortCmap = properties.hasShortCmap; - this.loadedName = getUniqueName(); + this.loadedName = properties.loadedName; this.loading = true; }; @@ -12703,6 +14298,13 @@ var Font = (function Font() { String.fromCharCode(value & 0xff); }; + function safeString16(value) { + // clamp value to the 16-bit int range + value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value; + return String.fromCharCode((value >> 8) & 0xff) + + String.fromCharCode(value & 0xff); + }; + function string32(value) { return String.fromCharCode((value >> 24) & 0xff) + String.fromCharCode((value >> 16) & 0xff) + @@ -12777,15 +14379,15 @@ var Font = (function Font() { var ranges = []; for (var n = 0; n < length; ) { var start = codes[n].unicode; - var startCode = codes[n].code; + var codeIndices = [codes[n].code]; ++n; var end = start; while (n < length && end + 1 == codes[n].unicode) { + codeIndices.push(codes[n].code); ++end; ++n; } - var endCode = codes[n - 1].code; - ranges.push([start, end, startCode, endCode]); + ranges.push([start, end, codeIndices]); } return ranges; @@ -12828,17 +14430,16 @@ var Font = (function Font() { idDeltas += string16(0); idRangeOffsets += string16(offset); - var startCode = range[2]; - var endCode = range[3]; - for (var j = startCode; j <= endCode; ++j) - glyphsIds += string16(deltas[j]); + var codes = range[2]; + for (var j = 0, jj = codes.length; j < jj; ++j) + glyphsIds += string16(deltas[codes[j]]); } } else { for (var i = 0; i < segCount - 1; i++) { var range = ranges[i]; var start = range[0]; var end = range[1]; - var startCode = range[2]; + var startCode = range[2][0]; startCount += string16(start); endCount += string16(end); @@ -13042,13 +14643,13 @@ var Font = (function Font() { return nameTable; } - constructor.prototype = { + Font.prototype = { name: null, font: null, mimetype: null, encoding: null, - checkAndRepair: function font_checkAndRepair(name, font, properties) { + checkAndRepair: function Font_checkAndRepair(name, font, properties) { function readTableEntry(file) { var tag = file.getBytes(4); tag = String.fromCharCode(tag[0]) + @@ -13115,7 +14716,7 @@ var Font = (function Font() { properties.baseEncoding = encoding; } - function replaceCMapTable(cmap, font, properties) { + function readCMapTable(cmap, font) { var start = (font.start ? font.start : 0) + cmap.offset; font.pos = start; @@ -13132,7 +14733,7 @@ var Font = (function Font() { } // Check that table are sorted by platformID then encodingID, - records.sort(function fontReplaceCMapTableSort(a, b) { + records.sort(function fontReadCMapTableSort(a, b) { return ((a.platformID << 16) + a.encodingID) - ((b.platformID << 16) + b.encodingID); }); @@ -13187,16 +14788,15 @@ var Font = (function Font() { for (var j = 0; j < 256; j++) { var index = font.getByte(); if (index) { - var unicode = adaptUnicode(j); - glyphs.push({ unicode: unicode, code: j }); + glyphs.push({ unicode: j, code: j }); ids.push(index); } } - - properties.hasShortCmap = true; - - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids, + hasShortCmap: true + }; } else if (format == 4) { // re-creating the table in format 4 since the encoding // might be changed @@ -13248,17 +14848,18 @@ var Font = (function Font() { var glyphCode = offsetIndex < 0 ? j : offsets[offsetIndex + j - start]; glyphCode = (glyphCode + delta) & 0xFFFF; - if (glyphCode == 0 || isAdaptedUnicode(j)) + if (glyphCode == 0) continue; - var unicode = adaptUnicode(j); - glyphs.push({ unicode: unicode, code: j }); + glyphs.push({ unicode: j, code: j }); ids.push(glyphCode); } } - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids + }; } else if (format == 6) { // Format 6 is a 2-bytes dense mapping, which means the font data // lives glue together even if they are pretty far in the unicode @@ -13273,19 +14874,18 @@ var Font = (function Font() { for (var j = 0; j < entryCount; j++) { var glyphCode = int16(font.getBytes(2)); var code = firstCode + j; - if (isAdaptedUnicode(glyphCode)) - continue; - var unicode = adaptUnicode(code); - glyphs.push({ unicode: unicode, code: code }); + glyphs.push({ unicode: code, code: code }); ids.push(glyphCode); } - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids + }; } } - return cmap.data; + error('Unsupported cmap table format'); }; function sanitizeMetrics(font, header, metrics, numGlyphs) { @@ -13321,6 +14921,61 @@ var Font = (function Font() { } }; + function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart) { + if (sourceEnd - sourceStart <= 12) { + // glyph with data less than 12 is invalid one + return 0; + } + var glyf = source.subarray(sourceStart, sourceEnd); + var contoursCount = (glyf[0] << 8) | glyf[1]; + if (contoursCount & 0x8000) { + // complex glyph, writing as is + dest.set(glyf, destStart); + return glyf.length; + } + + var j = 10, flagsCount = 0; + for (var i = 0; i < contoursCount; i++) { + var endPoint = (glyf[j] << 8) | glyf[j + 1]; + flagsCount = endPoint + 1; + j += 2; + } + // skipping instructions + var instructionsLength = (glyf[j] << 8) | glyf[j + 1]; + j += 2 + instructionsLength; + // validating flags + var coordinatesLength = 0; + for (var i = 0; i < flagsCount; i++) { + var flag = glyf[j++]; + if (flag & 0xC0) { + // reserved flags must be zero, rejecting + return 0; + } + var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) + + ((flag & 4) ? 1 : (flag & 32) ? 0 : 2); + coordinatesLength += xyLength; + if (flag & 8) { + var repeat = glyf[j++]; + i += repeat; + coordinatesLength += repeat * xyLength; + } + } + var glyphDataLength = j + coordinatesLength; + if (glyphDataLength > glyf.length) { + // not enough data for coordinates + return 0; + } + if (glyf.length - glyphDataLength > 3) { + // truncating and aligning to 4 bytes the long glyph data + glyphDataLength = (glyphDataLength + 3) & ~3; + dest.set(glyf.subarray(0, glyphDataLength), destStart); + return glyphDataLength; + } + // glyph data is fine + dest.set(glyf, destStart); + return glyf.length; + } + function sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong) { var itemSize, itemDecode, itemEncode; @@ -13347,20 +15002,64 @@ var Font = (function Font() { }; } var locaData = loca.data; + // removing the invalid glyphs + var oldGlyfData = glyf.data; + var oldGlyfDataLength = oldGlyfData.length; + var newGlyfData = new Uint8Array(oldGlyfDataLength); var startOffset = itemDecode(locaData, 0); - var firstOffset = itemDecode(locaData, itemSize); - if (firstOffset - startOffset < 12 || startOffset > 0) { - // removing first glyph - glyf.data = glyf.data.subarray(firstOffset); - glyf.length -= firstOffset; - - itemEncode(locaData, 0, 0); - var i, pos = itemSize; - for (i = 1; i <= numGlyphs; ++i) { - itemEncode(locaData, pos, - itemDecode(locaData, pos) - firstOffset); - pos += itemSize; + var writeOffset = 0; + itemEncode(locaData, 0, writeOffset); + for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) { + var endOffset = itemDecode(locaData, j); + if (endOffset > oldGlyfDataLength) { + // glyph end offset points outside glyf data, rejecting the glyph + itemEncode(locaData, j, writeOffset); + startOffset = endOffset; + continue; } + + var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset, + newGlyfData, writeOffset); + writeOffset += newLength; + itemEncode(locaData, j, writeOffset); + startOffset = endOffset; + } + + if (writeOffset == 0) { + // glyf table cannot be empty -- redoing the glyf and loca tables + // to have single glyph with one point + var simpleGlyph = new Uint8Array( + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]); + for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) + itemEncode(locaData, j, simpleGlyph.length); + glyf.data = simpleGlyph; + return; + } + + glyf.data = newGlyfData.subarray(0, writeOffset); + } + + function findEmptyGlyphs(locaTable, isGlyphLocationsLong, emptyGlyphIds) { + var itemSize, itemDecode; + if (isGlyphLocationsLong) { + itemSize = 4; + itemDecode = function fontItemDecodeLong(data, offset) { + return (data[offset] << 24) | (data[offset + 1] << 16) | + (data[offset + 2] << 8) | data[offset + 3]; + }; + } else { + itemSize = 2; + itemDecode = function fontItemDecode(data, offset) { + return (data[offset] << 9) | (data[offset + 1] << 1); + }; + } + var data = locaTable.data, length = data.length; + var lastOffset = itemDecode(data, 0); + for (var i = itemSize, j = 0; i < length; i += itemSize, j++) { + var offset = itemDecode(data, i); + if (offset == lastOffset) + emptyGlyphIds[j] = true; + lastOffset = offset; } } @@ -13490,11 +15189,15 @@ var Font = (function Font() { sanitizeMetrics(font, hhea, hmtx, numGlyphs); sanitizeMetrics(font, vhea, vmtx, numGlyphs); + var isGlyphLocationsLong = int16([head.data[50], head.data[51]]); if (head && loca && glyf) { - var isGlyphLocationsLong = int16([head.data[50], head.data[51]]); sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong); } + var emptyGlyphIds = []; + if (glyf) + findEmptyGlyphs(loca, isGlyphLocationsLong, emptyGlyphIds); + // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth // Sometimes it's 0. That needs to be fixed if (hhea.data[10] == 0 && hhea.data[11] == 0) { @@ -13507,8 +15210,9 @@ var Font = (function Font() { readGlyphNameMap(post, properties); } - // Replace the old CMAP table with a shiny new one + var glyphs, ids; if (properties.type == 'CIDFontType2') { + // Replace the old CMAP table with a shiny new one // Type2 composite fonts map characters directly to glyphs so the cmap // table must be replaced. // canvas fillText will reencode some characters even if the font has a @@ -13524,19 +15228,236 @@ var Font = (function Font() { tables.push(cmap); } - var glyphs = []; - for (i = 1; i < numGlyphs; i++) { - if (isAdaptedUnicode(i)) - continue; + var cidToGidMap = properties.cidToGidMap || []; + var gidToCidMap = [0]; + if (cidToGidMap.length > 0) { + for (var j = cidToGidMap.length - 1; j >= 0; j--) { + var gid = cidToGidMap[j]; + if (gid) + gidToCidMap[gid] = j; + } + // filling the gaps using CID above the CIDs currently used in font + var nextCid = cidToGidMap.length; + for (var i = 1; i < numGlyphs; i++) { + if (!gidToCidMap[i]) + gidToCidMap[i] = nextCid++; + } + } - glyphs.push({ unicode: adaptUnicode(i) }); + glyphs = []; + ids = []; + + var usedUnicodes = []; + var unassignedUnicodeItems = []; + for (var i = 1; i < numGlyphs; i++) { + var cid = gidToCidMap[i] || i; + var unicode = this.toFontChar[cid]; + if (!unicode || typeof unicode !== 'number' || + isSpecialUnicode(unicode) || unicode in usedUnicodes) { + unassignedUnicodeItems.push(i); + continue; + } + usedUnicodes[unicode] = true; + glyphs.push({ unicode: unicode, code: cid }); + ids.push(i); + } + // trying to fit as many unassigned symbols as we can + // in the range allocated for the user defined symbols + var unusedUnicode = kCmapGlyphOffset; + for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) { + var i = unassignedUnicodeItems[j]; + var cid = gidToCidMap[i] || i; + while (unusedUnicode in usedUnicodes) + unusedUnicode++; + if (unusedUnicode >= kCmapGlyphOffset + kSizeOfGlyphArea) + break; + var unicode = unusedUnicode++; + this.toFontChar[cid] = unicode; + usedUnicodes[unicode] = true; + glyphs.push({ unicode: unicode, code: cid }); + ids.push(i); } - cmap.data = createCMapTable(glyphs); } else { - replaceCMapTable(cmap, font, properties); + var cmapTable = readCMapTable(cmap, font); + + glyphs = cmapTable.glyphs; + ids = cmapTable.ids; + + var hasShortCmap = !!cmapTable.hasShortCmap; + var toFontChar = this.toFontChar; + + if (hasShortCmap && ids.length == numGlyphs) { + // Fixes the short cmap tables -- some generators use incorrect + // glyph id. + for (var i = 0, ii = ids.length; i < ii; i++) + ids[i] = i; + } + + var unusedUnicode = kCmapGlyphOffset; + var glyphNames = properties.glyphNames || []; + var encoding = properties.baseEncoding; + var differences = properties.differences; + if (toFontChar && toFontChar.length > 0) { + // checking if cmap is just identity map + var isIdentity = true; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + if (glyphs[i].unicode != i + 1) { + isIdentity = false; + break; + } + } + // if it is, replacing with meaningful toUnicode values + if (isIdentity && !this.isSymbolicFont) { + var usedUnicodes = [], unassignedUnicodeItems = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var unicode = toFontChar[i + 1]; + if (!unicode || typeof unicode !== 'number' || + unicode in usedUnicodes) { + unassignedUnicodeItems.push(i); + continue; + } + glyphs[i].unicode = unicode; + usedUnicodes[unicode] = true; + } + for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) { + var i = unassignedUnicodeItems[j]; + while (unusedUnicode in usedUnicodes) + unusedUnicode++; + var cid = i + 1; + // override only if unicode mapping is not specified + if (!(cid in toFontChar)) + toFontChar[cid] = unusedUnicode; + glyphs[i].unicode = unusedUnicode++; + } + this.useToFontChar = true; + } + } + + // remove glyph references outside range of avaialable glyphs or empty + var glyphsRemoved = 0; + for (var i = ids.length - 1; i >= 0; i--) { + if (ids[i] < numGlyphs && + (!emptyGlyphIds[ids[i]] || this.isSymbolicFont)) + continue; + ids.splice(i, 1); + glyphs.splice(i, 1); + glyphsRemoved++; + } + + // checking if it's a "true" symbolic font + if (this.isSymbolicFont) { + var minUnicode = 0xFFFF, maxUnicode = 0; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var unicode = glyphs[i].unicode; + minUnicode = Math.min(minUnicode, unicode); + maxUnicode = Math.max(maxUnicode, unicode); + } + // high byte must be the same for min and max unicodes + if ((maxUnicode & 0xFF00) != (minUnicode & 0xFF00)) + this.isSymbolicFont = false; + } + + // heuristics: if removed more than 2 glyphs encoding WinAnsiEncoding + // does not set properly + if (glyphsRemoved > 2) { + warn('Switching TrueType encoding to MacRomanEncoding for ' + + this.name + ' font'); + encoding = Encodings.MacRomanEncoding; + } + + if (hasShortCmap && this.hasEncoding && !this.isSymbolicFont) { + // Re-encode short map encoding to unicode -- that simplifies the + // resolution of MacRoman encoded glyphs logic for TrueType fonts: + // copying all characters to private use area, all mapping all known + // glyphs to the unicodes. The glyphs and ids arrays will grow. + var usedUnicodes = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode; + var gid = ids[i]; + glyphs[i].unicode += kCmapGlyphOffset; + toFontChar[code] = glyphs[i].unicode; + + var glyphName = glyphNames[gid] || encoding[code]; + if (glyphName in GlyphsUnicode) { + var unicode = GlyphsUnicode[glyphName]; + if (unicode in usedUnicodes) + continue; + + usedUnicodes[unicode] = true; + glyphs.push({ + unicode: unicode, + code: glyphs[i].code + }); + ids.push(gid); + toFontChar[code] = unicode; + } + } + this.useToFontChar = true; + } else if (!this.isSymbolicFont && (this.hasEncoding || + properties.glyphNames || differences.length > 0)) { + // Re-encode cmap encoding to unicode, based on the 'post' table data + // diffrence array or base encoding + var reverseMap = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) + reverseMap[glyphs[i].unicode] = i; + + var newGlyphUnicodes = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode; + var changeCode = false; + var gid = ids[i]; + + var glyphName = glyphNames[gid]; + if (!glyphName) { + glyphName = differences[code] || encoding[code]; + changeCode = true; + } + if (glyphName in GlyphsUnicode) { + var unicode = GlyphsUnicode[glyphName]; + if (!unicode || reverseMap[unicode] === i) + continue; // unknown glyph name or in its own place + + newGlyphUnicodes[i] = unicode; + if (changeCode) + toFontChar[code] = unicode; + delete reverseMap[code]; + } + } + for (var index in newGlyphUnicodes) { + var unicode = newGlyphUnicodes[index]; + if (reverseMap[unicode]) { + // avoiding assigning to the same unicode + glyphs[index].unicode = unusedUnicode++; + continue; + } + glyphs[index].unicode = unicode; + reverseMap[unicode] = index; + } + this.useToFontChar = true; + } + + // Moving all symbolic font glyphs into 0xF000 - 0xF0FF range. + if (this.isSymbolicFont) { + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode & 0xFF; + var fontCharCode = kSymbolicFontGlyphOffset | code; + glyphs[i].unicode = toFontChar[code] = fontCharCode; + } + this.useToFontChar = true; + } + + createGlyphNameMap(glyphs, ids, properties); this.glyphNameMap = properties.glyphNameMap; } + // Converting glyphs and ids into font's cmap table + cmap.data = createCMapTable(glyphs, ids); + var unicodeIsEnabled = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + unicodeIsEnabled[glyphs[i].unicode] = true; + } + this.unicodeIsEnabled = unicodeIsEnabled; + // Rewrite the 'post' table if needed if (requiredTables.indexOf('post') != -1) { tables.push({ @@ -13583,7 +15504,7 @@ var Font = (function Font() { return stringToArray(ttf.file); }, - convert: function font_convert(fontName, font, properties) { + convert: function Font_convert(fontName, font, properties) { function isFixedPitch(glyphs) { for (var i = 0, ii = glyphs.length - 1; i < ii; i++) { if (glyphs[i] != glyphs[i + 1]) @@ -13624,6 +15545,14 @@ var Font = (function Font() { } properties.baseEncoding = encoding; } + if (properties.subtype == 'CIDFontType0C') { + var toFontChar = []; + for (var i = 0; i < charstrings.length; ++i) { + var charstring = charstrings[i]; + toFontChar[charstring.code] = charstring.unicode; + } + this.toFontChar = toFontChar; + } var fields = { // PostScript Font Program @@ -13648,9 +15577,9 @@ var Font = (function Font() { '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date '\x00\x00' + // xMin - string16(properties.descent) + // yMin + safeString16(properties.descent) + // yMin '\x0F\xFF' + // xMax - string16(properties.ascent) + // yMax + safeString16(properties.ascent) + // yMax string16(properties.italicAngle ? 2 : 0) + // macStyle '\x00\x11' + // lowestRecPPEM '\x00\x00' + // fontDirectionHint @@ -13662,15 +15591,15 @@ var Font = (function Font() { 'hhea': (function fontFieldsHhea() { return stringToArray( '\x00\x01\x00\x00' + // Version number - string16(properties.ascent) + // Typographic Ascent - string16(properties.descent) + // Typographic Descent + safeString16(properties.ascent) + // Typographic Ascent + safeString16(properties.descent) + // Typographic Descent '\x00\x00' + // Line Gap '\xFF\xFF' + // advanceWidthMax '\x00\x00' + // minLeftSidebearing '\x00\x00' + // minRightSidebearing '\x00\x00' + // xMaxExtent - string16(properties.capHeight) + // caretSlopeRise - string16(Math.tan(properties.italicAngle) * + safeString16(properties.capHeight) + // caretSlopeRise + safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + // caretSlopeRun '\x00\x00' + // caretOffset '\x00\x00' + // -reserved- @@ -13684,8 +15613,11 @@ var Font = (function Font() { // Horizontal metrics 'hmtx': (function fontFieldsHmtx() { var hmtx = '\x00\x00\x00\x00'; // Fake .notdef - for (var i = 0, ii = charstrings.length; i < ii; i++) - hmtx += string16(charstrings[i].width) + string16(0); + for (var i = 0, ii = charstrings.length; i < ii; i++) { + var charstring = charstrings[i]; + var width = 'width' in charstring ? charstring.width : 0; + hmtx += string16(width) + string16(0); + } return stringToArray(hmtx); })(), @@ -13714,17 +15646,48 @@ var Font = (function Font() { return stringToArray(otf.file); }, - loadCidToUnicode: function font_loadCidToUnicode(properties) { - if (properties.cidToGidMap) { - this.cidToUnicode = properties.cidToGidMap; - return; + buildToFontChar: function Font_buildToFontChar(toUnicode) { + var result = []; + var unusedUnicode = kCmapGlyphOffset; + for (var i = 0, ii = toUnicode.length; i < ii; i++) { + var unicode = toUnicode[i]; + var fontCharCode = typeof unicode === 'object' ? unusedUnicode++ : + unicode; + if (typeof unicode !== 'undefined') + result[i] = fontCharCode; + } + return result; + }, + + rebuildToUnicode: function Font_rebuildToUnicode(properties) { + var firstChar = properties.firstChar, lastChar = properties.lastChar; + var map = []; + if (properties.composite) { + var isIdentityMap = this.cidToUnicode.length == 0; + for (var i = firstChar, ii = lastChar; i <= ii; i++) { + // TODO missing map the character according font's CMap + var cid = i; + map[i] = isIdentityMap ? cid : this.cidToUnicode[cid]; + } + } else { + for (var i = firstChar, ii = lastChar; i <= ii; i++) { + var glyph = properties.differences[i]; + if (!glyph) + glyph = properties.baseEncoding[i]; + if (!!glyph && (glyph in GlyphsUnicode)) + map[i] = GlyphsUnicode[glyph]; + } } + this.toUnicode = map; + }, + loadCidToUnicode: function Font_loadCidToUnicode(properties) { if (!properties.cidSystemInfo) return; - var cidToUnicodeMap = []; + var cidToUnicodeMap = [], unicodeToCIDMap = []; this.cidToUnicode = cidToUnicodeMap; + this.unicodeToCID = unicodeToCIDMap; var cidSystemInfo = properties.cidSystemInfo; var cidToUnicode; @@ -13736,43 +15699,38 @@ var Font = (function Font() { if (!cidToUnicode) return; // identity encoding - var glyph = 1, i, j, k, ii; + var cid = 1, i, j, k, ii; for (i = 0, ii = cidToUnicode.length; i < ii; ++i) { var unicode = cidToUnicode[i]; if (isArray(unicode)) { var length = unicode.length; - for (j = 0; j < length; j++) - cidToUnicodeMap[unicode[j]] = glyph; - glyph++; + for (j = 0; j < length; j++) { + cidToUnicodeMap[cid] = unicode[j]; + unicodeToCIDMap[unicode[j]] = cid; + } + cid++; } else if (typeof unicode === 'object') { var fillLength = unicode.f; if (fillLength) { k = unicode.c; for (j = 0; j < fillLength; ++j) { - cidToUnicodeMap[k] = glyph++; + cidToUnicodeMap[cid] = k; + unicodeToCIDMap[k] = cid; + cid++; k++; } } else - glyph += unicode.s; + cid += unicode.s; } else if (unicode) { - cidToUnicodeMap[unicode] = glyph++; + cidToUnicodeMap[cid] = unicode; + unicodeToCIDMap[unicode] = cid; + cid++; } else - glyph++; + cid++; } }, - bindWorker: function font_bindWorker(data) { - postMessage({ - action: 'font', - data: { - raw: data, - fontName: this.loadedName, - mimetype: this.mimetype - } - }); - }, - - bindDOM: function font_bindDom(data) { + bindDOM: function Font_bindDOM(data) { var fontName = this.loadedName; // Add the font-face rule to the document @@ -13780,89 +15738,137 @@ var Font = (function Font() { window.btoa(data) + ');'); var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}'; - document.documentElement.firstChild.appendChild( - document.createElement('style')); + var styleElement = document.createElement('style'); + document.documentElement.getElementsByTagName('head')[0].appendChild( + styleElement); - var styleSheet = document.styleSheets[document.styleSheets.length - 1]; + var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); + if (PDFJS.pdfBug && FontInspector.enabled) + FontInspector.fontAdded(this, url); + return rule; }, - charToGlyph: function fonts_charToGlyph(charcode) { - var unicode, width, codeIRQueue; + get spaceWidth() { + // trying to estimate space character width + var possibleSpaceReplacements = ['space', 'minus', 'one', 'i']; + var width; + for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) { + var glyphName = possibleSpaceReplacements[i]; + // if possible, getting width by glyph name + if (glyphName in this.widths) { + width = this.widths[glyphName]; + break; + } + var glyphUnicode = GlyphsUnicode[glyphName]; + // finding the charcode via unicodeToCID map + var charcode = 0; + if (this.composite) + charcode = this.unicodeToCID[glyphUnicode]; + // ... via toUnicode map + if (!charcode && 'toUnicode' in this) + charcode = this.toUnicode.indexOf(glyphUnicode); + // setting it to unicode if negative or undefined + if (!(charcode > 0)) + charcode = glyphUnicode; + // trying to get width via charcode + width = this.widths[charcode]; + if (width) + break; // the non-zero width found + } + width = (width || this.defaultWidth) * this.widthMultiplier; + return shadow(this, 'spaceWidth', width); + }, + + charToGlyph: function Font_charToGlyph(charcode) { + var fontCharCode, width, operatorList, disabled; var width = this.widths[charcode]; switch (this.type) { case 'CIDFontType0': if (this.noUnicodeAdaptation) { - width = this.widths[this.cidToUnicode[charcode]]; - unicode = charcode; + width = this.widths[this.unicodeToCID[charcode] || charcode]; + fontCharCode = mapPrivateUseChars(charcode); break; } - unicode = adaptUnicode(this.cidToUnicode[charcode] || charcode); + fontCharCode = this.toFontChar[charcode] || charcode; break; case 'CIDFontType2': if (this.noUnicodeAdaptation) { - width = this.widths[this.cidToUnicode[charcode]]; - unicode = charcode; + width = this.widths[this.unicodeToCID[charcode] || charcode]; + fontCharCode = mapPrivateUseChars(charcode); break; } - unicode = adaptUnicode(this.cidToUnicode[charcode] || charcode); + fontCharCode = this.toFontChar[charcode] || charcode; break; case 'Type1': var glyphName = this.differences[charcode] || this.encoding[charcode]; + if (!isNum(width)) + width = this.widths[glyphName]; if (this.noUnicodeAdaptation) { - if (!isNum(width)) - width = this.widths[glyphName]; - unicode = GlyphsUnicode[glyphName] || charcode; + fontCharCode = mapPrivateUseChars(GlyphsUnicode[glyphName] || + charcode); break; } - unicode = this.glyphNameMap[glyphName] || - adaptUnicode(GlyphsUnicode[glyphName] || charcode); + fontCharCode = this.glyphNameMap[glyphName] || + GlyphsUnicode[glyphName] || charcode; break; case 'Type3': var glyphName = this.differences[charcode] || this.encoding[charcode]; - codeIRQueue = this.charProcIRQueues[glyphName]; - unicode = charcode; + operatorList = this.charProcOperatorList[glyphName]; + fontCharCode = charcode; break; case 'TrueType': + if (this.useToFontChar) { + fontCharCode = this.toFontChar[charcode] || charcode; + break; + } var glyphName = this.differences[charcode] || this.encoding[charcode]; if (!glyphName) glyphName = Encodings.StandardEncoding[charcode]; if (!isNum(width)) width = this.widths[glyphName]; if (this.noUnicodeAdaptation) { - unicode = GlyphsUnicode[glyphName] || charcode; + fontCharCode = GlyphsUnicode[glyphName] || charcode; break; } - if (!this.hasEncoding) { - unicode = adaptUnicode(charcode); + if (!this.hasEncoding || this.isSymbolicFont) { + fontCharCode = this.useToFontChar ? this.toFontChar[charcode] : + charcode; break; } - if (this.hasShortCmap) { - var j = Encodings.MacRomanEncoding.indexOf(glyphName); - unicode = j >= 0 && !isSpecialUnicode(j) ? j : - this.glyphNameMap[glyphName]; - } else { - unicode = glyphName in GlyphsUnicode ? - adaptUnicode(GlyphsUnicode[glyphName]) : - this.glyphNameMap[glyphName]; - } + + // MacRoman encoding address by re-encoding the cmap table + fontCharCode = glyphName in this.glyphNameMap ? + this.glyphNameMap[glyphName] : GlyphsUnicode[glyphName]; break; default: warn('Unsupported font type: ' + this.type); break; } + + var unicodeChars = !('toUnicode' in this) ? charcode : + this.toUnicode[charcode] || charcode; + if (typeof unicodeChars === 'number') + unicodeChars = String.fromCharCode(unicodeChars); + + width = (isNum(width) ? width : this.defaultWidth) * this.widthMultiplier; + disabled = this.unicodeIsEnabled ? + !this.unicodeIsEnabled[fontCharCode] : false; + return { - unicode: unicode, - width: isNum(width) ? width : this.defaultWidth, - codeIRQueue: codeIRQueue + fontChar: String.fromCharCode(fontCharCode), + unicode: unicodeChars, + width: width, + disabled: disabled, + operatorList: operatorList }; }, - charsToGlyphs: function fonts_chars2Glyphs(chars) { + charsToGlyphs: function Font_charsToGlyphs(chars) { var charsCache = this.charsCache; var glyphs; @@ -13910,7 +15916,7 @@ var Font = (function Font() { } }; - return constructor; + return Font; })(); /* @@ -14197,7 +16203,13 @@ var Type1Parser = function type1Parser() { while (str[index++] != ']') count++; - var array = str.substr(start, count).split(' '); + str = str.substr(start, count); + + str = str.trim(); + // Remove adjacent spaces + str = str.replace(/\s+/g, ' '); + + var array = str.split(' '); for (var i = 0, ii = array.length; i < ii; i++) array[i] = parseFloat(array[i] || 0); return array; @@ -14220,7 +16232,7 @@ var Type1Parser = function type1Parser() { return c == ' ' || c == '\n' || c == '\x0d'; } - this.extractFontProgram = function t1_extractFontProgram(stream) { + this.extractFontProgram = function Type1Parser_extractFontProgram(stream) { var eexec = decrypt(stream, kEexecEncryptionKey, 4); var eexecStr = ''; for (var i = 0, ii = eexec.length; i < ii; i++) @@ -14231,7 +16243,7 @@ var Type1Parser = function type1Parser() { subrs: [], charstrings: [], properties: { - 'private': { + 'privateData': { 'lenIV': 4 } } @@ -14260,7 +16272,7 @@ var Type1Parser = function type1Parser() { (token == 'RD' || token == '-|')) { i++; var data = eexec.slice(i, i + length); - var lenIV = program.properties.private['lenIV']; + var lenIV = program.properties.privateData['lenIV']; var encoded = decrypt(data, kCharStringsEncryptionKey, lenIV); var str = decodeCharString(encoded); @@ -14300,7 +16312,7 @@ var Type1Parser = function type1Parser() { var length = parseInt(getToken(), 10); getToken(); // read in 'RD' var data = eexec.slice(i + 1, i + 1 + length); - var lenIV = program.properties.private['lenIV']; + var lenIV = program.properties.privateData['lenIV']; var encoded = decrypt(data, kCharStringsEncryptionKey, lenIV); var str = decodeCharString(encoded); i = i + 1 + length; @@ -14316,12 +16328,12 @@ var Type1Parser = function type1Parser() { case '/FamilyOtherBlues': case '/StemSnapH': case '/StemSnapV': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumberArray(eexecStr, i + 1); break; case '/StdHW': case '/StdVW': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumberArray(eexecStr, i + 2)[0]; break; case '/BlueShift': @@ -14330,7 +16342,7 @@ var Type1Parser = function type1Parser() { case '/BlueScale': case '/LanguageGroup': case '/ExpansionFactor': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumber(eexecStr, i + 1); break; } @@ -14345,7 +16357,8 @@ var Type1Parser = function type1Parser() { return program; }; - this.extractFontHeader = function t1_extractFontHeader(stream, properties) { + this.extractFontHeader = function Type1Parser_extractFontHeader(stream, + properties) { var headerString = ''; for (var i = 0, ii = stream.length; i < ii; i++) headerString += String.fromCharCode(stream[i]); @@ -14354,14 +16367,14 @@ var Type1Parser = function type1Parser() { var count = headerString.length; for (var i = 0; i < count; i++) { var getToken = function getToken() { - var char = headerString[i]; - while (i < count && (isSeparator(char) || char == '/')) - char = headerString[++i]; + var character = headerString[i]; + while (i < count && (isSeparator(character) || character == '/')) + character = headerString[++i]; var token = ''; - while (i < count && !(isSeparator(char) || char == '/')) { - token += char; - char = headerString[++i]; + while (i < count && !(isSeparator(character) || character == '/')) { + token += character; + character = headerString[++i]; } return token; @@ -14421,7 +16434,7 @@ var Type1Parser = function type1Parser() { * The CFF class takes a Type1 file and wrap it into a * 'Compact Font Format' which itself embed Type2 charstrings. */ -var CFFStrings = [ +var CFFStandardStrings = [ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', @@ -14491,7 +16504,8 @@ var CFFStrings = [ var type1Parser = new Type1Parser(); -var CFF = function cffCFF(name, file, properties) { +// Type1Font is also a CIDFontType0. +var Type1Font = function Type1Font(name, file, properties) { // Get the data block containing glyphs and subrs informations var headerBlock = file.getBytes(properties.length1); type1Parser.extractFontHeader(headerBlock, properties); @@ -14511,8 +16525,9 @@ var CFF = function cffCFF(name, file, properties) { subrs, properties); }; -CFF.prototype = { - createCFFIndexHeader: function cff_createCFFIndexHeader(objects, isByte) { +Type1Font.prototype = { + createCFFIndexHeader: function Type1Font_createCFFIndexHeader(objects, + isByte) { // First 2 bytes contains the number of objects contained into this index var count = objects.length; @@ -14548,7 +16563,7 @@ CFF.prototype = { return data; }, - encodeNumber: function cff_encodeNumber(value) { + encodeNumber: function Type1Font_encodeNumber(value) { // some of the fonts has ouf-of-range values // they are just arithmetic overflows // make sanitizer happy @@ -14566,25 +16581,16 @@ CFF.prototype = { } }, - getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs, + getOrderedCharStrings: function Type1Font_getOrderedCharStrings(glyphs, properties) { var charstrings = []; - var reverseMapping = {}; - var encoding = properties.baseEncoding; var i, length, glyphName; - for (i = 0, length = encoding.length; i < length; ++i) { - glyphName = encoding[i]; - if (!glyphName || isSpecialUnicode(i)) - continue; - reverseMapping[glyphName] = i; - } - reverseMapping['.notdef'] = 0; var unusedUnicode = kCmapGlyphOffset; for (i = 0, length = glyphs.length; i < length; i++) { var item = glyphs[i]; var glyphName = item.glyph; - var unicode = glyphName in reverseMapping ? - reverseMapping[glyphName] : unusedUnicode++; + var unicode = glyphName in GlyphsUnicode ? + GlyphsUnicode[glyphName] : unusedUnicode++; charstrings.push({ glyph: glyphName, unicode: unicode, @@ -14601,7 +16607,8 @@ CFF.prototype = { return charstrings; }, - getType2Charstrings: function cff_getType2Charstrings(type1Charstrings) { + getType2Charstrings: function Type1Font_getType2Charstrings( + type1Charstrings) { var type2Charstrings = []; var count = type1Charstrings.length; for (var i = 0; i < count; i++) { @@ -14612,7 +16619,7 @@ CFF.prototype = { return type2Charstrings; }, - getType2Subrs: function cff_getType2Subrs(type1Subrs) { + getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) { var bias = 0; var count = type1Subrs.length; if (count < 1240) @@ -14664,7 +16671,7 @@ CFF.prototype = { 'hvcurveto': 31 }, - flattenCharstring: function flattenCharstring(charstring, map) { + flattenCharstring: function Type1Font_flattenCharstring(charstring, map) { // charstring changes size - can't cache .length in loop for (var i = 0; i < charstring.length; i++) { var command = charstring[i]; @@ -14691,7 +16698,7 @@ CFF.prototype = { return charstring; }, - wrap: function wrap(name, glyphs, charstrings, subrs, properties) { + wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) { var fields = { // major version, minor version, header size, offset size 'header': '\x01\x00\x04\x04', @@ -14735,7 +16742,7 @@ CFF.prototype = { dict += self.encodeNumber(offset) + '\x11'; // Charstrings offset = offset + fields.charstrings.length; - dict += self.encodeNumber(fields.private.length); + dict += self.encodeNumber(fields.privateData.length); dict += self.encodeNumber(offset) + '\x12'; // Private return header + String.fromCharCode(dict.length + 1) + dict; @@ -14760,7 +16767,7 @@ CFF.prototype = { var count = glyphs.length; for (var i = 0; i < count; i++) { - var index = CFFStrings.indexOf(charstrings[i].glyph); + var index = CFFStandardStrings.indexOf(charstrings[i].glyph); // Some characters like asterikmath && circlecopyrt are // missing from the original strings, for the moment let's // map them to .notdef and see later if it cause any @@ -14776,7 +16783,7 @@ CFF.prototype = { 'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), true), - 'private': (function cffWrapPrivate(self) { + 'privateData': (function cffWrapPrivate(self) { var data = '\x8b\x14' + // defaultWidth '\x8b\x15'; // nominalWidth @@ -14794,9 +16801,9 @@ CFF.prototype = { ExpansionFactor: '\x0c\x18' }; for (var field in fieldMap) { - if (!properties.private.hasOwnProperty(field)) + if (!properties.privateData.hasOwnProperty(field)) continue; - var value = properties.private[field]; + var value = properties.privateData[field]; if (isArray(value)) { data += self.encodeNumber(value[0]); @@ -14829,106 +16836,31 @@ CFF.prototype = { } }; -var Type2CFF = (function type2CFF() { - // TODO: replace parsing code with the Type2Parser in font_utils.js - function constructor(file, properties) { - var bytes = file.getBytes(); - this.bytes = bytes; +var CFFFont = (function CFFFontClosure() { + function CFFFont(file, properties) { this.properties = properties; - this.data = this.parse(); + var parser = new CFFParser(file, properties); + var cff = parser.parse(); + var compiler = new CFFCompiler(cff); + this.readExtra(cff); + try { + this.data = compiler.compile(); + } catch (e) { + warn('Failed to compile font ' + properties.loadedName); + // There may have just been an issue with the compiler, set the data + // anyway and hope the font loaded. + this.data = file; + } } - constructor.prototype = { - parse: function cff_parse() { - var header = this.parseHeader(); - var properties = this.properties; - var nameIndex = this.parseIndex(header.endPos); - - var dictIndex = this.parseIndex(nameIndex.endPos); - if (dictIndex.length != 1) - error('CFF contains more than 1 font'); - - var stringIndex = this.parseIndex(dictIndex.endPos); - var gsubrIndex = this.parseIndex(stringIndex.endPos); - - var strings = this.getStrings(stringIndex); - - var baseDict = this.parseDict(dictIndex.get(0).data); - var topDict = this.getTopDict(baseDict, strings); - - var bytes = this.bytes; - - var privateDict = {}; - var privateInfo = topDict.Private; - if (privateInfo) { - var privOffset = privateInfo[1], privLength = privateInfo[0]; - var privBytes = bytes.subarray(privOffset, privOffset + privLength); - baseDict = this.parseDict(privBytes); - privateDict = this.getPrivDict(baseDict, strings); - } else { - privateDict.defaultWidthX = properties.defaultWidth; - } - - var charStrings = this.parseIndex(topDict.CharStrings); - var charset = this.parseCharsets(topDict.charset, - charStrings.length, strings); - var encoding = this.parseEncoding(topDict.Encoding, properties, - strings, charset); - - var charset, encoding; - var isCIDFont = properties.subtype == 'CIDFontType0C'; - if (isCIDFont) { - charset = []; - charset.length = charStrings.length; - encoding = this.parseCidMap(topDict.charset, - charStrings.length); - } else { - charset = this.parseCharsets(topDict.charset, - charStrings.length, strings); - encoding = this.parseEncoding(topDict.Encoding, properties, - strings, charset); - } - - // The font sanitizer does not support CFF encoding with a - // supplement, since the encoding is not really use to map - // between gid to glyph, let's overwrite what is declared in - // the top dictionary to let the sanitizer think the font use - // StandardEncoding, that's a lie but that's ok. - if (encoding.hasSupplement) - bytes[topDict.Encoding] &= 0x7F; - - // The CFF specification state that the 'dotsection' command - // (12, 0) is deprecated and treated as a no-op, but all Type2 - // charstrings processors should support them. Unfortunately - // the font sanitizer don't. As a workaround the sequence (12, 0) - // is replaced by a useless (0, hmoveto). - var count = charStrings.length; - for (var i = 0; i < count; i++) { - var charstring = charStrings.get(i); - - var start = charstring.start; - var data = charstring.data; - var length = data.length; - for (var j = 0; j <= length; j) { - var value = data[j++]; - if (value == 12 && data[j++] == 0) { - bytes[start + j - 2] = 139; - bytes[start + j - 1] = 22; - } else if (value === 28) { - j += 2; - } else if (value >= 247 && value <= 254) { - j++; - } else if (value == 255) { - j += 4; - } - } - } - + CFFFont.prototype = { + readExtra: function CFFFont_readExtra(cff) { // charstrings contains info about glyphs (one element per glyph // containing mappings for {unicode, width}) - var charstrings = this.getCharStrings(charset, encoding.encoding, - privateDict, this.properties); + var charset = cff.charset.charset; + var encoding = cff.encoding ? cff.encoding.encoding : null; + var charstrings = this.getCharStrings(charset, encoding); // create the mapping between charstring and glyph id var glyphIds = []; @@ -14937,301 +16869,127 @@ var Type2CFF = (function type2CFF() { this.charstrings = charstrings; this.glyphIds = glyphIds; - - var data = []; - for (var i = 0, ii = bytes.length; i < ii; ++i) - data.push(bytes[i]); - return data; }, - - getCharStrings: function cff_charstrings(charsets, encoding, - privateDict, properties) { + getCharStrings: function CFFFont_getCharStrings(charsets, encoding) { var charstrings = []; var unicodeUsed = []; var unassignedUnicodeItems = []; + var inverseEncoding = []; + // CID fonts don't have an encoding. + if (encoding !== null) + for (var charcode in encoding) + inverseEncoding[encoding[charcode]] = charcode | 0; + else + inverseEncoding = charsets; for (var i = 0, ii = charsets.length; i < ii; i++) { var glyph = charsets[i]; - var encodingFound = false; - for (var charcode in encoding) { - if (encoding[charcode] == i) { - var code = charcode | 0; - charstrings.push({ - unicode: adaptUnicode(code), - code: code, - gid: i, - glyph: glyph - }); - unicodeUsed[code] = true; - encodingFound = true; - break; - } - } - if (!encodingFound) { + if (glyph == '.notdef') + continue; + + var code = inverseEncoding[i]; + if (!code || isSpecialUnicode(code)) { unassignedUnicodeItems.push(i); + continue; } + charstrings.push({ + unicode: code, + code: code, + gid: i, + glyph: glyph + }); + unicodeUsed[code] = true; } - var nextUnusedUnicode = 0x21; + var nextUnusedUnicode = kCmapGlyphOffset; for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; ++j) { var i = unassignedUnicodeItems[j]; // giving unicode value anyway - while (unicodeUsed[nextUnusedUnicode]) + while (nextUnusedUnicode in unicodeUsed) nextUnusedUnicode++; - var code = nextUnusedUnicode++; + var unicode = nextUnusedUnicode++; charstrings.push({ - unicode: adaptUnicode(code), - code: code, + unicode: unicode, + code: inverseEncoding[i] || 0, gid: i, glyph: charsets[i] }); } // sort the array by the unicode value (again) - charstrings.sort(function type2CFFGetCharStringsSort(a, b) { + charstrings.sort(function getCharStringsSort(a, b) { return a.unicode - b.unicode; }); return charstrings; - }, - - parseEncoding: function cff_parseencoding(pos, properties, strings, - charset) { - var encoding = {}; - var bytes = this.bytes; - var result = { - encoding: encoding, - hasSupplement: false - }; - - function readSupplement() { - var supplementsCount = bytes[pos++]; - for (var i = 0; i < supplementsCount; i++) { - var code = bytes[pos++]; - var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff); - encoding[code] = properties.differences.indexOf(strings[sid]); - } - } - - if (pos == 0 || pos == 1) { - var gid = 1; - var baseEncoding = pos ? Encodings.ExpertEncoding : - Encodings.StandardEncoding; - for (var i = 0, ii = charset.length; i < ii; i++) { - var index = baseEncoding.indexOf(charset[i]); - if (index != -1) - encoding[index] = gid++; - } - } else { - var format = bytes[pos++]; - switch (format & 0x7f) { - case 0: - var glyphsCount = bytes[pos++]; - for (var i = 1; i <= glyphsCount; i++) - encoding[bytes[pos++]] = i; - break; - - case 1: - var rangesCount = bytes[pos++]; - var gid = 1; - for (var i = 0; i < rangesCount; i++) { - var start = bytes[pos++]; - var left = bytes[pos++]; - for (var j = start; j <= start + left; j++) - encoding[j] = gid++; - } - break; - - default: - error('Unknow encoding format: ' + format + ' in CFF'); - break; - } - if (format & 0x80) { - readSupplement(); - result.hasSupplement = true; - } - } - return result; - }, - - parseCharsets: function cff_parsecharsets(pos, length, strings) { - if (pos == 0) { - return ISOAdobeCharset.slice(); - } else if (pos == 1) { - return ExpertCharset.slice(); - } else if (pos == 2) { - return ExpertSubsetCharset.slice(); - } - - var bytes = this.bytes; - var format = bytes[pos++]; - var charset = ['.notdef']; - - // subtract 1 for the .notdef glyph - length -= 1; - - switch (format) { - case 0: - for (var i = 0; i < length; i++) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - charset.push(strings[sid]); - } - break; - case 1: - while (charset.length <= length) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - var count = bytes[pos++]; - for (var i = 0; i <= count; i++) - charset.push(strings[sid++]); - } - break; - case 2: - while (charset.length <= length) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - var count = (bytes[pos++] << 8) | bytes[pos++]; - for (var i = 0; i <= count; i++) - charset.push(strings[sid++]); - } - break; - default: - error('Unknown charset format'); - } - return charset; - }, + } + }; - parseCidMap: function cff_parsecharsets(pos, length) { - var bytes = this.bytes; - var format = bytes[pos++]; + return CFFFont; +})(); - var encoding = {}; - var map = {encoding: encoding}; +var CFFParser = (function CFFParserClosure() { + function CFFParser(file, properties) { + this.bytes = file.getBytes(); + this.properties = properties; + } + CFFParser.prototype = { + parse: function CFFParser_parse() { + var properties = this.properties; + var cff = new CFF(); + this.cff = cff; - encoding[0] = 0; + // The first five sections must be in order, all the others are reached + // via offsets contained in one of the below. + var header = this.parseHeader(); + var nameIndex = this.parseIndex(header.endPos); + var topDictIndex = this.parseIndex(nameIndex.endPos); + var stringIndex = this.parseIndex(topDictIndex.endPos); + var globalSubrIndex = this.parseIndex(stringIndex.endPos); - var gid = 1; - switch (format) { - case 0: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - encoding[cid] = gid++; - } - break; - case 1: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - var count = bytes[pos++]; - for (var i = 0; i <= count; i++) - encoding[cid++] = gid++; - } - break; - case 2: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - var count = (bytes[pos++] << 8) | bytes[pos++]; - for (var i = 0; i <= count; i++) - encoding[cid++] = gid++; - } - break; - default: - error('Unknown charset format'); - } - return map; - }, + var topDictParsed = this.parseDict(topDictIndex.obj.get(0)); + var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings); - getPrivDict: function cff_getprivdict(baseDict, strings) { - var dict = {}; + cff.header = header.obj; + cff.names = this.parseNameIndex(nameIndex.obj); + cff.strings = this.parseStringIndex(stringIndex.obj); + cff.topDict = topDict; + cff.globalSubrIndex = globalSubrIndex.obj; - // default values - dict['defaultWidthX'] = 0; - dict['nominalWidthX'] = 0; + this.parsePrivateDict(cff.topDict); - for (var i = 0, ii = baseDict.length; i < ii; ++i) { - var pair = baseDict[i]; - var key = pair[0]; - var value = pair[1]; - switch (key) { - case 20: - dict['defaultWidthX'] = value[0]; - case 21: - dict['nominalWidthX'] = value[0]; - default: - TODO('interpret top dict key: ' + key); - } - } - return dict; - }, - getTopDict: function cff_gettopdict(baseDict, strings) { - var dict = {}; + cff.isCIDFont = topDict.hasName('ROS'); - // default values - dict['Encoding'] = 0; - dict['charset'] = 0; + var charStringOffset = topDict.getByName('CharStrings'); + cff.charStrings = this.parseCharStrings(charStringOffset); - for (var i = 0, ii = baseDict.length; i < ii; ++i) { - var pair = baseDict[i]; - var key = pair[0]; - var value = pair[1]; - switch (key) { - case 1: - dict['Notice'] = strings[value[0]]; - break; - case 4: - dict['Weight'] = strings[value[0]]; - break; - case 3094: - dict['BaseFontName'] = strings[value[0]]; - break; - case 5: - dict['FontBBox'] = value; - break; - case 13: - dict['UniqueID'] = value[0]; - break; - case 15: - dict['charset'] = value[0]; - break; - case 16: - dict['Encoding'] = value[0]; - break; - case 17: - dict['CharStrings'] = value[0]; - break; - case 18: - dict['Private'] = value; - break; - case 3102: - case 3103: - case 3104: - case 3105: - case 3106: - case 3107: - case 3108: - case 3109: - case 3110: - dict['cidOperatorPresent'] = true; - break; - default: - TODO('interpret top dict key'); + var charset, encoding; + if (cff.isCIDFont) { + var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj; + for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) { + var dictRaw = fdArrayIndex.get(i); + var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw), + cff.strings); + this.parsePrivateDict(fontDict); + cff.fdArray.push(fontDict); } + // cid fonts don't have an encoding + encoding = null; + charset = this.parseCharsets(topDict.getByName('charset'), + cff.charStrings.count, cff.strings, true); + cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'), + cff.charStrings.count); + } else { + charset = this.parseCharsets(topDict.getByName('charset'), + cff.charStrings.count, cff.strings, false); + encoding = this.parseEncoding(topDict.getByName('Encoding'), + properties, + cff.strings, charset.charset); } - return dict; - }, - getStrings: function cff_getStrings(stringIndex) { - function bytesToString(bytesArray) { - var str = ''; - for (var i = 0, ii = bytesArray.length; i < ii; i++) - str += String.fromCharCode(bytesArray[i]); - return str; - } + cff.charset = charset; + cff.encoding = encoding; - var stringArray = []; - for (var i = 0, ii = CFFStrings.length; i < ii; i++) - stringArray.push(CFFStrings[i]); - - for (var i = 0, ii = stringIndex.length; i < ii; i++) - stringArray.push(bytesToString(stringIndex.get(i).data)); - - return stringArray; + return cff; }, - parseHeader: function cff_parseHeader() { + parseHeader: function CFFParser_parseHeader() { var bytes = this.bytes; var offset = 0; @@ -15239,17 +16997,18 @@ var Type2CFF = (function type2CFF() { ++offset; if (offset != 0) { - warning('cff data is shifted'); + warn('cff data is shifted'); bytes = bytes.subarray(offset); this.bytes = bytes; } - - return { - endPos: bytes[2], - offsetSize: bytes[3] - }; + var major = bytes[0]; + var minor = bytes[1]; + var hdrSize = bytes[2]; + var offSize = bytes[3]; + var header = new CFFHeader(major, minor, hdrSize, offSize); + return {obj: header, endPos: hdrSize}; }, - parseDict: function cff_parseDict(dict) { + parseDict: function CFFParser_parseDict(dict) { var pos = 0; function parseOperand() { @@ -15266,11 +17025,11 @@ var Type2CFF = (function type2CFF() { value = (value << 8) | dict[pos++]; value = (value << 8) | dict[pos++]; return value; - } else if (value <= 246) { + } else if (value >= 32 && value <= 246) { return value - 139; - } else if (value <= 250) { + } else if (value >= 247 && value <= 250) { return ((value - 247) * 256) + dict[pos++] + 108; - } else if (value <= 254) { + } else if (value >= 251 && value <= 254) { return -((value - 251) * 256) - dict[pos++] - 108; } else { error('255 is not a valid DICT command'); @@ -15308,27 +17067,8 @@ var Type2CFF = (function type2CFF() { while (pos < end) { var b = dict[pos]; if (b <= 21) { - if (b === 12) { - ++pos; - var op = dict[pos]; - if ((op > 14 && op < 17) || - (op > 23 && op < 30) || op > 38) { - warn('Invalid CFF dictionary key: ' + op); - // trying to replace it with initialRandomSeed - // to pass sanitizer - dict[pos] = 19; - } - var b = (b << 8) | op; - } - if (!operands.length && b == 8 && - dict[pos + 1] == 9) { - // no operands for FamilyBlues, removing the key - // and next one is FamilyOtherBlues - skipping them - // also replacing FamilyBlues to pass sanitizer - dict[pos] = 139; - pos += 2; - continue; - } + if (b === 12) + b = (b << 8) | dict[++pos]; entries.push([b, operands]); operands = []; ++pos; @@ -15338,10 +17078,12 @@ var Type2CFF = (function type2CFF() { } return entries; }, - parseIndex: function cff_parseIndex(pos) { + parseIndex: function CFFParser_parseIndex(pos) { + var cffIndex = new CFFIndex(); var bytes = this.bytes; - var count = bytes[pos++] << 8 | bytes[pos++]; + var count = (bytes[pos++] << 8) | bytes[pos++]; var offsets = []; + var start = pos; var end = pos; if (count != 0) { @@ -15359,142 +17101,1063 @@ var Type2CFF = (function type2CFF() { } end = offsets[count]; } + for (var i = 0, ii = offsets.length - 1; i < ii; ++i) { + var offsetStart = offsets[i]; + var offsetEnd = offsets[i + 1]; + cffIndex.add(bytes.subarray(offsetStart, offsetEnd)); + } + return {obj: cffIndex, endPos: end}; + }, + parseNameIndex: function CFFParser_parseNameIndex(index) { + var names = []; + for (var i = 0, ii = index.count; i < ii; ++i) { + var name = index.get(i); + // OTS doesn't allow names to be over 127 characters. + var length = Math.min(name.length, 127); + var data = []; + // OTS also only permits certain characters in the name. + for (var j = 0; j < length; ++j) { + var c = name[j]; + if (j === 0 && c === 0) { + data[j] = c; + continue; + } + if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ || + c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ || + c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ || + c === 47 /* / */ || c === 37 /* % */) { + data[j] = 95; + continue; + } + data[j] = c; + } + names.push(String.fromCharCode.apply(null, data)); + } + return names; + }, + parseStringIndex: function CFFParser_parseStringIndex(index) { + var strings = new CFFStrings(); + for (var i = 0, ii = index.count; i < ii; ++i) { + var data = index.get(i); + strings.add(String.fromCharCode.apply(null, data)); + } + return strings; + }, + createDict: function CFFParser_createDict(type, dict, strings) { + var cffDict = new type(strings); + var types = cffDict.types; - return { - get: function index_get(index) { - if (index >= count) - return null; - - var start = offsets[index]; - var end = offsets[index + 1]; - return { - start: start, - end: end, - data: bytes.subarray(start, end) - }; - }, - length: count, - endPos: end - }; + for (var i = 0, ii = dict.length; i < ii; ++i) { + var pair = dict[i]; + var key = pair[0]; + var value = pair[1]; + cffDict.setByKey(key, value); + } + return cffDict; + }, + parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) { + var charStrings = this.parseIndex(charStringOffset).obj; + // The CFF specification state that the 'dotsection' command + // (12, 0) is deprecated and treated as a no-op, but all Type2 + // charstrings processors should support them. Unfortunately + // the font sanitizer don't. As a workaround the sequence (12, 0) + // is replaced by a useless (0, hmoveto). + var count = charStrings.count; + for (var i = 0; i < count; i++) { + var charstring = charStrings.get(i); + + var data = charstring; + var length = data.length; + for (var j = 0; j <= length; j) { + var value = data[j++]; + if (value == 12 && data[j++] == 0) { + data[j - 2] = 139; + data[j - 1] = 22; + } else if (value === 28) { + j += 2; + } else if (value >= 247 && value <= 254) { + j++; + } else if (value == 255) { + j += 4; + } + } + } + return charStrings; + }, + parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) { + // no private dict, do nothing + if (!parentDict.hasName('Private')) + return; + var privateOffset = parentDict.getByName('Private'); + // make sure the params are formatted correctly + if (!isArray(privateOffset) || privateOffset.length !== 2) { + parentDict.removeByName('Private'); + return; + } + var size = privateOffset[0]; + var offset = privateOffset[1]; + // remove empty dicts or ones that refer to invalid location + if (size === 0 || offset >= this.bytes.length) { + parentDict.removeByName('Private'); + return; + } + + var privateDictEnd = offset + size; + var dictData = this.bytes.subarray(offset, privateDictEnd); + var dict = this.parseDict(dictData); + var privateDict = this.createDict(CFFPrivateDict, dict, + parentDict.strings); + parentDict.privateDict = privateDict; + + // Parse the Subrs index also since it's relative to the private dict. + if (!privateDict.getByName('Subrs')) + return; + var subrsOffset = privateDict.getByName('Subrs'); + var relativeOffset = offset + subrsOffset; + // Validate the offset. + if (subrsOffset === 0 || relativeOffset >= this.bytes.length) { + privateDict.removeByName('Subrs'); + return; + } + var subrsIndex = this.parseIndex(relativeOffset); + privateDict.subrsIndex = subrsIndex.obj; + }, + parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) { + if (pos == 0) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, + ISOAdobeCharset); + } else if (pos == 1) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, + ExpertCharset); + } else if (pos == 2) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, + ExpertSubsetCharset); + } + + var bytes = this.bytes; + var start = pos; + var format = bytes[pos++]; + var charset = ['.notdef']; + + // subtract 1 for the .notdef glyph + length -= 1; + + switch (format) { + case 0: + for (var i = 0; i < length; i++) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + charset.push(cid ? id : strings.get(id)); + } + break; + case 1: + while (charset.length <= length) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + var count = bytes[pos++]; + for (var i = 0; i <= count; i++) + charset.push(cid ? id++ : strings.get(id++)); + } + break; + case 2: + while (charset.length <= length) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + var count = (bytes[pos++] << 8) | bytes[pos++]; + for (var i = 0; i <= count; i++) + charset.push(cid ? id++ : strings.get(id++)); + } + break; + default: + error('Unknown charset format'); + } + // Raw won't be needed if we actually compile the charset. + var end = pos; + var raw = bytes.subarray(start, end); + + return new CFFCharset(false, format, charset, raw); + }, + parseEncoding: function CFFParser_parseEncoding(pos, + properties, + strings, + charset) { + var encoding = {}; + var bytes = this.bytes; + var predefined = false; + var hasSupplement = false; + var format; + var raw = null; + + function readSupplement() { + var supplementsCount = bytes[pos++]; + for (var i = 0; i < supplementsCount; i++) { + var code = bytes[pos++]; + var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff); + encoding[code] = properties.differences.indexOf(strings.get(sid)); + } + } + + if (pos == 0 || pos == 1) { + predefined = true; + format = pos; + var gid = 1; + var baseEncoding = pos ? Encodings.ExpertEncoding : + Encodings.StandardEncoding; + for (var i = 0, ii = charset.length; i < ii; i++) { + var index = baseEncoding.indexOf(charset[i]); + if (index != -1) + encoding[index] = gid++; + } + } else { + var dataStart = pos; + var format = bytes[pos++]; + switch (format & 0x7f) { + case 0: + var glyphsCount = bytes[pos++]; + for (var i = 1; i <= glyphsCount; i++) + encoding[bytes[pos++]] = i; + break; + + case 1: + var rangesCount = bytes[pos++]; + var gid = 1; + for (var i = 0; i < rangesCount; i++) { + var start = bytes[pos++]; + var left = bytes[pos++]; + for (var j = start; j <= start + left; j++) + encoding[j] = gid++; + } + break; + + default: + error('Unknow encoding format: ' + format + ' in CFF'); + break; + } + var dataEnd = pos; + if (format & 0x80) { + // The font sanitizer does not support CFF encoding with a + // supplement, since the encoding is not really used to map + // between gid to glyph, let's overwrite what is declared in + // the top dictionary to let the sanitizer think the font use + // StandardEncoding, that's a lie but that's ok. + bytes[dataStart] &= 0x7f; + readSupplement(); + hasSupplement = true; + } + raw = bytes.subarray(dataStart, dataEnd); + } + format = format & 0x7f; + return new CFFEncoding(predefined, format, encoding, raw); + }, + parseFDSelect: function CFFParser_parseFDSelect(pos, length) { + var start = pos; + var bytes = this.bytes; + var format = bytes[pos++]; + var fdSelect = []; + switch (format) { + case 0: + for (var i = 0; i < length; ++i) { + var id = bytes[pos++]; + fdSelect.push(id); + } + break; + case 3: + var rangesCount = (bytes[pos++] << 8) | bytes[pos++]; + for (var i = 0; i < rangesCount; ++i) { + var first = (bytes[pos++] << 8) | bytes[pos++]; + var fdIndex = bytes[pos++]; + var next = (bytes[pos] << 8) | bytes[pos + 1]; + for (var j = first; j < next; ++j) + fdSelect.push(fdIndex); + } + // Advance past the sentinel(next). + pos += 2; + break; + default: + error('Unknown fdselect format ' + format); + break; + } + var end = pos; + return new CFFFDSelect(fdSelect, bytes.subarray(start, end)); } }; + return CFFParser; +})(); - return constructor; +// Compact Font Format +var CFF = (function CFFClosure() { + function CFF() { + this.header = null; + this.names = []; + this.topDict = null; + this.strings = new CFFStrings(); + this.globalSubrIndex = null; + + // The following could really be per font, but since we only have one font + // store them here. + this.encoding = null; + this.charset = null; + this.charStrings = null; + this.fdArray = []; + this.fdSelect = null; + + this.isCIDFont = false; + } + return CFF; })(); -/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ +var CFFHeader = (function CFFHeaderClosure() { + function CFFHeader(major, minor, hdrSize, offSize) { + this.major = major; + this.minor = minor; + this.hdrSize = hdrSize; + this.offSize = offSize; + } + return CFFHeader; +})(); -'use strict'; +var CFFStrings = (function CFFStringsClosure() { + function CFFStrings() { + this.strings = []; + } + CFFStrings.prototype = { + get: function CFFStrings_get(index) { + if (index >= 0 && index <= 390) + return CFFStandardStrings[index]; + if (index - 391 <= this.strings.length) + return this.strings[index - 391]; + return CFFStandardStrings[0]; + }, + add: function CFFStrings_add(value) { + this.strings.push(value); + }, + get count() { + return this.strings.length; + } + }; + return CFFStrings; +})(); -var GlyphsUnicode = { - A: 0x0041, - AE: 0x00C6, - AEacute: 0x01FC, - AEmacron: 0x01E2, - AEsmall: 0xF7E6, - Aacute: 0x00C1, - Aacutesmall: 0xF7E1, - Abreve: 0x0102, - Abreveacute: 0x1EAE, - Abrevecyrillic: 0x04D0, - Abrevedotbelow: 0x1EB6, - Abrevegrave: 0x1EB0, - Abrevehookabove: 0x1EB2, - Abrevetilde: 0x1EB4, - Acaron: 0x01CD, - Acircle: 0x24B6, - Acircumflex: 0x00C2, - Acircumflexacute: 0x1EA4, - Acircumflexdotbelow: 0x1EAC, - Acircumflexgrave: 0x1EA6, - Acircumflexhookabove: 0x1EA8, - Acircumflexsmall: 0xF7E2, - Acircumflextilde: 0x1EAA, - Acute: 0xF6C9, - Acutesmall: 0xF7B4, - Acyrillic: 0x0410, - Adblgrave: 0x0200, - Adieresis: 0x00C4, - Adieresiscyrillic: 0x04D2, - Adieresismacron: 0x01DE, - Adieresissmall: 0xF7E4, - Adotbelow: 0x1EA0, - Adotmacron: 0x01E0, - Agrave: 0x00C0, - Agravesmall: 0xF7E0, - Ahookabove: 0x1EA2, - Aiecyrillic: 0x04D4, - Ainvertedbreve: 0x0202, - Alpha: 0x0391, - Alphatonos: 0x0386, - Amacron: 0x0100, - Amonospace: 0xFF21, - Aogonek: 0x0104, - Aring: 0x00C5, - Aringacute: 0x01FA, - Aringbelow: 0x1E00, - Aringsmall: 0xF7E5, - Asmall: 0xF761, - Atilde: 0x00C3, - Atildesmall: 0xF7E3, - Aybarmenian: 0x0531, - B: 0x0042, - Bcircle: 0x24B7, - Bdotaccent: 0x1E02, - Bdotbelow: 0x1E04, - Becyrillic: 0x0411, - Benarmenian: 0x0532, - Beta: 0x0392, - Bhook: 0x0181, - Blinebelow: 0x1E06, - Bmonospace: 0xFF22, - Brevesmall: 0xF6F4, - Bsmall: 0xF762, - Btopbar: 0x0182, - C: 0x0043, - Caarmenian: 0x053E, - Cacute: 0x0106, - Caron: 0xF6CA, - Caronsmall: 0xF6F5, - Ccaron: 0x010C, - Ccedilla: 0x00C7, - Ccedillaacute: 0x1E08, - Ccedillasmall: 0xF7E7, - Ccircle: 0x24B8, - Ccircumflex: 0x0108, - Cdot: 0x010A, - Cdotaccent: 0x010A, - Cedillasmall: 0xF7B8, - Chaarmenian: 0x0549, - Cheabkhasiancyrillic: 0x04BC, - Checyrillic: 0x0427, - Chedescenderabkhasiancyrillic: 0x04BE, - Chedescendercyrillic: 0x04B6, - Chedieresiscyrillic: 0x04F4, - Cheharmenian: 0x0543, - Chekhakassiancyrillic: 0x04CB, - Cheverticalstrokecyrillic: 0x04B8, - Chi: 0x03A7, - Chook: 0x0187, - Circumflexsmall: 0xF6F6, - Cmonospace: 0xFF23, - Coarmenian: 0x0551, - Csmall: 0xF763, - D: 0x0044, - DZ: 0x01F1, - DZcaron: 0x01C4, - Daarmenian: 0x0534, - Dafrican: 0x0189, - Dcaron: 0x010E, - Dcedilla: 0x1E10, - Dcircle: 0x24B9, - Dcircumflexbelow: 0x1E12, - Dcroat: 0x0110, - Ddotaccent: 0x1E0A, - Ddotbelow: 0x1E0C, - Decyrillic: 0x0414, - Deicoptic: 0x03EE, +var CFFIndex = (function CFFIndexClosure() { + function CFFIndex() { + this.objects = []; + this.length = 0; + } + CFFIndex.prototype = { + add: function CFFIndex_add(data) { + this.length += data.length; + this.objects.push(data); + }, + get: function CFFIndex_get(index) { + return this.objects[index]; + }, + get count() { + return this.objects.length; + } + }; + return CFFIndex; +})(); + +var CFFDict = (function CFFDictClosure() { + function CFFDict(tables, strings) { + this.keyToNameMap = tables.keyToNameMap; + this.nameToKeyMap = tables.nameToKeyMap; + this.defaults = tables.defaults; + this.types = tables.types; + this.opcodes = tables.opcodes; + this.order = tables.order; + this.strings = strings; + this.values = {}; + } + CFFDict.prototype = { + // value should always be an array + setByKey: function CFFDict_setByKey(key, value) { + if (!(key in this.keyToNameMap)) + return false; + // ignore empty values + if (value.length === 0) + return true; + var type = this.types[key]; + // remove the array wrapping these types of values + if (type === 'num' || type === 'sid' || type === 'offset') + value = value[0]; + this.values[key] = value; + return true; + }, + hasName: function CFFDict_hasName(name) { + return this.nameToKeyMap[name] in this.values; + }, + getByName: function CFFDict_getByName(name) { + if (!(name in this.nameToKeyMap)) + error('Invalid dictionary name "' + name + '"'); + var key = this.nameToKeyMap[name]; + if (!(key in this.values)) + return this.defaults[key]; + return this.values[key]; + }, + removeByName: function CFFDict_removeByName(name) { + delete this.values[this.nameToKeyMap[name]]; + } + }; + CFFDict.createTables = function CFFDict_createTables(layout) { + var tables = { + keyToNameMap: {}, + nameToKeyMap: {}, + defaults: {}, + types: {}, + opcodes: {}, + order: [] + }; + for (var i = 0, ii = layout.length; i < ii; ++i) { + var entry = layout[i]; + var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0]; + tables.keyToNameMap[key] = entry[1]; + tables.nameToKeyMap[entry[1]] = key; + tables.types[key] = entry[2]; + tables.defaults[key] = entry[3]; + tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]]; + tables.order.push(key); + } + return tables; + }; + return CFFDict; +})(); + +var CFFTopDict = (function CFFTopDictClosure() { + var layout = [ + [[12, 30], 'ROS', ['sid', 'sid', 'num'], null], + [[12, 20], 'SyntheticBase', 'num', null], + [0, 'version', 'sid', null], + [1, 'Notice', 'sid', null], + [[12, 0], 'Copyright', 'sid', null], + [2, 'FullName', 'sid', null], + [3, 'FamilyName', 'sid', null], + [4, 'Weight', 'sid', null], + [[12, 1], 'isFixedPitch', 'num', 0], + [[12, 2], 'ItalicAngle', 'num', 0], + [[12, 3], 'UnderlinePosition', 'num', -100], + [[12, 4], 'UnderlineThickness', 'num', 50], + [[12, 5], 'PaintType', 'num', 0], + [[12, 6], 'CharstringType', 'num', 2], + [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'], + [.001, 0, 0, .001, 0, 0]], + [13, 'UniqueID', 'num', null], + [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]], + [[12, 8], 'StrokeWidth', 'num', 0], + [14, 'XUID', 'array', null], + [15, 'charset', 'offset', 0], + [16, 'Encoding', 'offset', 0], + [17, 'CharStrings', 'offset', 0], + [18, 'Private', ['offset', 'offset'], null], + [[12, 21], 'PostScript', 'sid', null], + [[12, 22], 'BaseFontName', 'sid', null], + [[12, 23], 'BaseFontBlend', 'delta', null], + [[12, 31], 'CIDFontVersion', 'num', 0], + [[12, 32], 'CIDFontRevision', 'num', 0], + [[12, 33], 'CIDFontType', 'num', 0], + [[12, 34], 'CIDCount', 'num', 8720], + [[12, 35], 'UIDBase', 'num', null], + [[12, 36], 'FDArray', 'offset', null], + [[12, 37], 'FDSelect', 'offset', null], + [[12, 38], 'FontName', 'sid', null]]; + var tables = null; + function CFFTopDict(strings) { + if (tables === null) + tables = CFFDict.createTables(layout); + CFFDict.call(this, tables, strings); + this.privateDict = null; + } + CFFTopDict.prototype = Object.create(CFFDict.prototype); + return CFFTopDict; +})(); + +var CFFPrivateDict = (function CFFPrivateDictClosure() { + var layout = [ + [6, 'BlueValues', 'delta', null], + [7, 'OtherBlues', 'delta', null], + [8, 'FamilyBlues', 'delta', null], + [9, 'FamilyOtherBlues', 'delta', null], + [[12, 9], 'BlueScale', 'num', 0.039625], + [[12, 10], 'BlueShift', 'num', 7], + [[12, 11], 'BlueFuzz', 'num', 1], + [10, 'StdHW', 'num', null], + [11, 'StdVW', 'num', null], + [[12, 12], 'StemSnapH', 'delta', null], + [[12, 13], 'StemSnapV', 'delta', null], + [[12, 14], 'ForceBold', 'num', 0], + [[12, 17], 'LanguageGroup', 'num', 0], + [[12, 18], 'ExpansionFactor', 'num', 0.06], + [[12, 19], 'initialRandomSeed', 'num', 0], + [19, 'Subrs', 'offset', null], + [20, 'defaultWidthX', 'num', 0], + [21, 'nominalWidthX', 'num', 0] + ]; + var tables = null; + function CFFPrivateDict(strings) { + if (tables === null) + tables = CFFDict.createTables(layout); + CFFDict.call(this, tables, strings); + this.subrsIndex = null; + } + CFFPrivateDict.prototype = Object.create(CFFDict.prototype); + return CFFPrivateDict; +})(); + +var CFFCharsetPredefinedTypes = { + ISO_ADOBE: 0, + EXPERT: 1, + EXPERT_SUBSET: 2 +}; +var CFFCharsetEmbeddedTypes = { + FORMAT0: 0, + FORMAT1: 1, + FORMAT2: 2 +}; +var CFFCharset = (function CFFCharsetClosure() { + function CFFCharset(predefined, format, charset, raw) { + this.predefined = predefined; + this.format = format; + this.charset = charset; + this.raw = raw; + } + return CFFCharset; +})(); + +var CFFEncodingPredefinedTypes = { + STANDARD: 0, + EXPERT: 1 +}; +var CFFCharsetEmbeddedTypes = { + FORMAT0: 0, + FORMAT1: 1 +}; +var CFFEncoding = (function CFFEncodingClosure() { + function CFFEncoding(predefined, format, encoding, raw) { + this.predefined = predefined; + this.format = format; + this.encoding = encoding; + this.raw = raw; + } + return CFFEncoding; +})(); + +var CFFFDSelect = (function CFFFDSelectClosure() { + function CFFFDSelect(fdSelect, raw) { + this.fdSelect = fdSelect; + this.raw = raw; + } + return CFFFDSelect; +})(); + +// Helper class to keep track of where an offset is within the data and helps +// filling in that offset once it's known. +var CFFOffsetTracker = (function CFFOffsetTrackerClosure() { + function CFFOffsetTracker() { + this.offsets = {}; + } + CFFOffsetTracker.prototype = { + isTracking: function CFFOffsetTracker_isTracking(key) { + return key in this.offsets; + }, + track: function CFFOffsetTracker_track(key, location) { + if (key in this.offsets) + error('Already tracking location of ' + key); + this.offsets[key] = location; + }, + offset: function CFFOffsetTracker_offset(value) { + for (var key in this.offsets) { + this.offsets[key] += value; + } + }, + setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, + values, + output) { + if (!(key in this.offsets)) + error('Not tracking location of ' + key); + var data = output.data; + var dataOffset = this.offsets[key]; + var size = 5; + for (var i = 0, ii = values.length; i < ii; ++i) { + var offset0 = i * size + dataOffset; + var offset1 = offset0 + 1; + var offset2 = offset0 + 2; + var offset3 = offset0 + 3; + var offset4 = offset0 + 4; + // It's easy to screw up offsets so perform this sanity check. + if (data[offset0] !== 0x1d || data[offset1] !== 0 || + data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) + error('writing to an offset that is not empty'); + var value = values[i]; + data[offset0] = 0x1d; + data[offset1] = (value >> 24) & 0xFF; + data[offset2] = (value >> 16) & 0xFF; + data[offset3] = (value >> 8) & 0xFF; + data[offset4] = value & 0xFF; + } + } + }; + return CFFOffsetTracker; +})(); + +// Takes a CFF and converts it to the binary representation. +var CFFCompiler = (function CFFCompilerClosure() { + function stringToArray(str) { + var array = []; + for (var i = 0, ii = str.length; i < ii; ++i) + array[i] = str.charCodeAt(i); + + return array; + }; + function CFFCompiler(cff) { + this.cff = cff; + } + CFFCompiler.prototype = { + compile: function CFFCompiler_compile() { + var cff = this.cff; + var output = { + data: [], + length: 0, + add: function CFFCompiler_add(data) { + this.data = this.data.concat(data); + this.length = this.data.length; + } + }; + + // Compile the five entries that must be in order. + var header = this.compileHeader(cff.header); + output.add(header); + + var nameIndex = this.compileNameIndex(cff.names); + output.add(nameIndex); + + var compiled = this.compileTopDicts([cff.topDict], output.length); + output.add(compiled.output); + var topDictTracker = compiled.trackers[0]; + + var stringIndex = this.compileStringIndex(cff.strings.strings); + output.add(stringIndex); + + var globalSubrIndex = this.compileIndex(cff.globalSubrIndex); + output.add(globalSubrIndex); + + // Now start on the other entries that have no specfic order. + if (cff.encoding && cff.topDict.hasName('Encoding')) { + if (cff.encoding.predefined) { + topDictTracker.setEntryLocation('Encoding', [cff.encoding.format], + output); + } else { + var encoding = this.compileEncoding(cff.encoding); + topDictTracker.setEntryLocation('Encoding', [output.length], output); + output.add(encoding); + } + } + + if (cff.charset && cff.topDict.hasName('charset')) { + if (cff.charset.predefined) { + topDictTracker.setEntryLocation('charset', [cff.charset.format], + output); + } else { + var charset = this.compileCharset(cff.charset); + topDictTracker.setEntryLocation('charset', [output.length], output); + output.add(charset); + } + } + + var charStrings = this.compileCharStrings(cff.charStrings); + topDictTracker.setEntryLocation('CharStrings', [output.length], output); + output.add(charStrings); + + if (cff.isCIDFont) { + // For some reason FDSelect must be in front of FDArray on windows. OSX + // and linux don't seem to care. + topDictTracker.setEntryLocation('FDSelect', [output.length], output); + var fdSelect = this.compileFDSelect(cff.fdSelect.raw); + output.add(fdSelect); + + var compiled = this.compileTopDicts(cff.fdArray, output.length); + topDictTracker.setEntryLocation('FDArray', [output.length], output); + output.add(compiled.output); + var fontDictTrackers = compiled.trackers; + + this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output); + } + + this.compilePrivateDicts([cff.topDict], [topDictTracker], output); + + return output.data; + }, + encodeNumber: function CFFCompiler_encodeNumber(value) { + if (parseFloat(value) == parseInt(value) && !isNaN(value)) // isInt + return this.encodeInteger(value); + else + return this.encodeFloat(value); + }, + encodeFloat: function CFFCompiler_encodeFloat(value) { + value = value.toString(); + // Strip off the any leading zeros. + if (value.substr(0, 2) === '0.') + value = value.substr(1); + else if (value.substr(0, 3) === '-0.') + value = '-' + value.substr(2); + var nibbles = []; + for (var i = 0, ii = value.length; i < ii; ++i) { + var a = value.charAt(i), b = value.charAt(i + 1); + var nibble; + if (a === 'e' && b === '-') { + nibble = 0xc; + ++i; + } else if (a === '.') { + nibble = 0xa; + } else if (a === 'E') { + nibble = 0xb; + } else if (a === '-') { + nibble = 0xe; + } else { + nibble = a; + } + nibbles.push(nibble); + } + nibbles.push(0xf); + if (nibbles.length % 2) + nibbles.push(0xf); + var out = [30]; + for (var i = 0, ii = nibbles.length; i < ii; i += 2) + out.push(nibbles[i] << 4 | nibbles[i + 1]); + return out; + }, + encodeInteger: function CFFCompiler_encodeInteger(value) { + var code; + if (value >= -107 && value <= 107) { + code = [value + 139]; + } else if (value >= 108 && value <= 1131) { + value = [value - 108]; + code = [(value >> 8) + 247, value & 0xFF]; + } else if (value >= -1131 && value <= -108) { + value = -value - 108; + code = [(value >> 8) + 251, value & 0xFF]; + } else if (value >= -32768 && value <= 32767) { + code = [0x1c, (value >> 8) & 0xFF, value & 0xFF]; + } else { + code = [0x1d, + (value >> 24) & 0xFF, + (value >> 16) & 0xFF, + (value >> 8) & 0xFF, + value & 0xFF]; + } + return code; + }, + compileHeader: function CFFCompiler_compileHeader(header) { + return [ + header.major, + header.minor, + header.hdrSize, + header.offSize + ]; + }, + compileNameIndex: function CFFCompiler_compileNameIndex(names) { + var nameIndex = new CFFIndex(); + for (var i = 0, ii = names.length; i < ii; ++i) + nameIndex.add(stringToArray(names[i])); + return this.compileIndex(nameIndex); + }, + compileTopDicts: function CFFCompiler_compileTopDicts(dicts, length) { + var fontDictTrackers = []; + var fdArrayIndex = new CFFIndex(); + for (var i = 0, ii = dicts.length; i < ii; ++i) { + var fontDict = dicts[i]; + var fontDictTracker = new CFFOffsetTracker(); + var fontDictData = this.compileDict(fontDict, fontDictTracker); + fontDictTrackers.push(fontDictTracker); + fdArrayIndex.add(fontDictData); + fontDictTracker.offset(length); + } + fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers); + return { + trackers: fontDictTrackers, + output: fdArrayIndex + }; + }, + compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts, + trackers, + output) { + for (var i = 0, ii = dicts.length; i < ii; ++i) { + var fontDict = dicts[i]; + if (!fontDict.privateDict || !fontDict.hasName('Private')) + continue; + var privateDict = fontDict.privateDict; + var privateDictTracker = new CFFOffsetTracker(); + var privateDictData = this.compileDict(privateDict, privateDictTracker); + + privateDictTracker.offset(output.length); + trackers[i].setEntryLocation('Private', + [privateDictData.length, output.length], + output); + output.add(privateDictData); + + if (privateDict.subrsIndex && privateDict.hasName('Subrs')) { + var subrs = this.compileIndex(privateDict.subrsIndex); + privateDictTracker.setEntryLocation('Subrs', [privateDictData.length], + output); + output.add(subrs); + } + } + }, + compileDict: function CFFCompiler_compileDict(dict, offsetTracker) { + var out = []; + // The dictionary keys must be in a certain order. + var order = dict.order; + for (var i = 0; i < order.length; ++i) { + var key = order[i]; + if (!(key in dict.values)) + continue; + var values = dict.values[key]; + var types = dict.types[key]; + if (!isArray(types)) types = [types]; + if (!isArray(values)) values = [values]; + + // Remove any empty dict values. + if (values.length === 0) + continue; + + for (var j = 0, jj = types.length; j < jj; ++j) { + var type = types[j]; + var value = values[j]; + switch (type) { + case 'num': + case 'sid': + out = out.concat(this.encodeNumber(value)); + break; + case 'offset': + // For offsets we just insert a 32bit integer so we don't have to + // deal with figuring out the length of the offset when it gets + // replaced later on by the compiler. + var name = dict.keyToNameMap[key]; + // Some offsets have the offset and the length, so just record the + // position of the first one. + if (!offsetTracker.isTracking(name)) + offsetTracker.track(name, out.length); + out = out.concat([0x1d, 0, 0, 0, 0]); + break; + case 'array': + case 'delta': + out = out.concat(this.encodeNumber(value)); + for (var k = 1, kk = values.length; k < kk; ++k) + out = out.concat(this.encodeNumber(values[k])); + break; + default: + error('Unknown data type of ' + type); + break; + } + } + out = out.concat(dict.opcodes[key]); + } + return out; + }, + compileStringIndex: function CFFCompiler_compileStringIndex(strings) { + var stringIndex = new CFFIndex(); + for (var i = 0, ii = strings.length; i < ii; ++i) + stringIndex.add(stringToArray(strings[i])); + return this.compileIndex(stringIndex); + }, + compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() { + var globalSubrIndex = this.cff.globalSubrIndex; + this.out.writeByteArray(this.compileIndex(globalSubrIndex)); + }, + compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) { + return this.compileIndex(charStrings); + }, + compileCharset: function CFFCompiler_compileCharset(charset) { + return this.compileTypedArray(charset.raw); + }, + compileEncoding: function CFFCompiler_compileEncoding(encoding) { + return this.compileTypedArray(encoding.raw); + }, + compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) { + return this.compileTypedArray(fdSelect); + }, + compileTypedArray: function CFFCompiler_compileTypedArray(data) { + var out = []; + for (var i = 0, ii = data.length; i < ii; ++i) + out[i] = data[i]; + return out; + }, + compileIndex: function CFFCompiler_compileIndex(index, trackers) { + trackers = trackers || []; + var objects = index.objects; + // First 2 bytes contains the number of objects contained into this index + var count = objects.length; + + // If there is no object, just create an index. This technically + // should just be [0, 0] but OTS has an issue with that. + if (count == 0) + return [0, 0, 0]; + + var data = [(count >> 8) & 0xFF, count & 0xff]; + + var lastOffset = 1; + for (var i = 0; i < count; ++i) + lastOffset += objects[i].length; + + var offsetSize; + if (lastOffset < 0x100) + offsetSize = 1; + else if (lastOffset < 0x10000) + offsetSize = 2; + else if (lastOffset < 0x1000000) + offsetSize = 3; + else + offsetSize = 4; + + // Next byte contains the offset size use to reference object in the file + data.push(offsetSize); + + // Add another offset after this one because we need a new offset + var relativeOffset = 1; + for (var i = 0; i < count + 1; i++) { + if (offsetSize === 1) { + data.push(relativeOffset & 0xFF); + } else if (offsetSize === 2) { + data.push((relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } else if (offsetSize === 3) { + data.push((relativeOffset >> 16) & 0xFF, + (relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } else { + data.push((relativeOffset >>> 24) & 0xFF, + (relativeOffset >> 16) & 0xFF, + (relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } + + if (objects[i]) + relativeOffset += objects[i].length; + } + var offset = data.length; + + for (var i = 0; i < count; i++) { + // Notify the tracker where the object will be offset in the data. + if (trackers[i]) + trackers[i].offset(data.length); + for (var j = 0, jj = objects[i].length; j < jj; j++) + data.push(objects[i][j]); + } + return data; + } + }; + return CFFCompiler; +})(); + +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +'use strict'; + +var GlyphsUnicode = { + A: 0x0041, + AE: 0x00C6, + AEacute: 0x01FC, + AEmacron: 0x01E2, + AEsmall: 0xF7E6, + Aacute: 0x00C1, + Aacutesmall: 0xF7E1, + Abreve: 0x0102, + Abreveacute: 0x1EAE, + Abrevecyrillic: 0x04D0, + Abrevedotbelow: 0x1EB6, + Abrevegrave: 0x1EB0, + Abrevehookabove: 0x1EB2, + Abrevetilde: 0x1EB4, + Acaron: 0x01CD, + Acircle: 0x24B6, + Acircumflex: 0x00C2, + Acircumflexacute: 0x1EA4, + Acircumflexdotbelow: 0x1EAC, + Acircumflexgrave: 0x1EA6, + Acircumflexhookabove: 0x1EA8, + Acircumflexsmall: 0xF7E2, + Acircumflextilde: 0x1EAA, + Acute: 0xF6C9, + Acutesmall: 0xF7B4, + Acyrillic: 0x0410, + Adblgrave: 0x0200, + Adieresis: 0x00C4, + Adieresiscyrillic: 0x04D2, + Adieresismacron: 0x01DE, + Adieresissmall: 0xF7E4, + Adotbelow: 0x1EA0, + Adotmacron: 0x01E0, + Agrave: 0x00C0, + Agravesmall: 0xF7E0, + Ahookabove: 0x1EA2, + Aiecyrillic: 0x04D4, + Ainvertedbreve: 0x0202, + Alpha: 0x0391, + Alphatonos: 0x0386, + Amacron: 0x0100, + Amonospace: 0xFF21, + Aogonek: 0x0104, + Aring: 0x00C5, + Aringacute: 0x01FA, + Aringbelow: 0x1E00, + Aringsmall: 0xF7E5, + Asmall: 0xF761, + Atilde: 0x00C3, + Atildesmall: 0xF7E3, + Aybarmenian: 0x0531, + B: 0x0042, + Bcircle: 0x24B7, + Bdotaccent: 0x1E02, + Bdotbelow: 0x1E04, + Becyrillic: 0x0411, + Benarmenian: 0x0532, + Beta: 0x0392, + Bhook: 0x0181, + Blinebelow: 0x1E06, + Bmonospace: 0xFF22, + Brevesmall: 0xF6F4, + Bsmall: 0xF762, + Btopbar: 0x0182, + C: 0x0043, + Caarmenian: 0x053E, + Cacute: 0x0106, + Caron: 0xF6CA, + Caronsmall: 0xF6F5, + Ccaron: 0x010C, + Ccedilla: 0x00C7, + Ccedillaacute: 0x1E08, + Ccedillasmall: 0xF7E7, + Ccircle: 0x24B8, + Ccircumflex: 0x0108, + Cdot: 0x010A, + Cdotaccent: 0x010A, + Cedillasmall: 0xF7B8, + Chaarmenian: 0x0549, + Cheabkhasiancyrillic: 0x04BC, + Checyrillic: 0x0427, + Chedescenderabkhasiancyrillic: 0x04BE, + Chedescendercyrillic: 0x04B6, + Chedieresiscyrillic: 0x04F4, + Cheharmenian: 0x0543, + Chekhakassiancyrillic: 0x04CB, + Cheverticalstrokecyrillic: 0x04B8, + Chi: 0x03A7, + Chook: 0x0187, + Circumflexsmall: 0xF6F6, + Cmonospace: 0xFF23, + Coarmenian: 0x0551, + Csmall: 0xF763, + D: 0x0044, + DZ: 0x01F1, + DZcaron: 0x01C4, + Daarmenian: 0x0534, + Dafrican: 0x0189, + Dcaron: 0x010E, + Dcedilla: 0x1E10, + Dcircle: 0x24B9, + Dcircumflexbelow: 0x1E12, + Dcroat: 0x0110, + Ddotaccent: 0x1E0A, + Ddotbelow: 0x1E0C, + Decyrillic: 0x0414, + Deicoptic: 0x03EE, Delta: 0x2206, Deltagreek: 0x0394, Dhook: 0x018A, @@ -16892,27 +19555,7 @@ var GlyphsUnicode = { dalet: 0x05D3, daletdagesh: 0xFB33, daletdageshhebrew: 0xFB33, - dalethatafpatah: 0x05D305B2, - dalethatafpatahhebrew: 0x05D305B2, - dalethatafsegol: 0x05D305B1, - dalethatafsegolhebrew: 0x05D305B1, dalethebrew: 0x05D3, - dalethiriq: 0x05D305B4, - dalethiriqhebrew: 0x05D305B4, - daletholam: 0x05D305B9, - daletholamhebrew: 0x05D305B9, - daletpatah: 0x05D305B7, - daletpatahhebrew: 0x05D305B7, - daletqamats: 0x05D305B8, - daletqamatshebrew: 0x05D305B8, - daletqubuts: 0x05D305BB, - daletqubutshebrew: 0x05D305BB, - daletsegol: 0x05D305B6, - daletsegolhebrew: 0x05D305B6, - daletsheva: 0x05D305B0, - daletshevahebrew: 0x05D305B0, - dalettsere: 0x05D305B5, - dalettserehebrew: 0x05D305B5, dalfinalarabic: 0xFEAA, dammaarabic: 0x064F, dammalowarabic: 0x064F, @@ -17229,10 +19872,6 @@ var GlyphsUnicode = { finalkafdagesh: 0xFB3A, finalkafdageshhebrew: 0xFB3A, finalkafhebrew: 0x05DA, - finalkafqamats: 0x05DA05B8, - finalkafqamatshebrew: 0x05DA05B8, - finalkafsheva: 0x05DA05B0, - finalkafshevahebrew: 0x05DA05B0, finalmem: 0x05DD, finalmemhebrew: 0x05DD, finalnun: 0x05DF, @@ -17421,14 +20060,7 @@ var GlyphsUnicode = { hakatakanahalfwidth: 0xFF8A, halantgurmukhi: 0x0A4D, hamzaarabic: 0x0621, - hamzadammaarabic: 0x0621064F, - hamzadammatanarabic: 0x0621064C, - hamzafathaarabic: 0x0621064E, - hamzafathatanarabic: 0x0621064B, hamzalowarabic: 0x0621, - hamzalowkasraarabic: 0x06210650, - hamzalowkasratanarabic: 0x0621064D, - hamzasukunarabic: 0x06210652, hangulfiller: 0x3164, hardsigncyrillic: 0x044A, harpoonleftbarbup: 0x21BC, @@ -17860,10 +20492,6 @@ var GlyphsUnicode = { lameddagesh: 0xFB3C, lameddageshhebrew: 0xFB3C, lamedhebrew: 0x05DC, - lamedholam: 0x05DC05B9, - lamedholamdagesh: '05DC 05B9 05BC', - lamedholamdageshhebrew: '05DC 05B9 05BC', - lamedholamhebrew: 0x05DC05B9, lamfinalarabic: 0xFEDE, lamhahinitialarabic: 0xFCCA, laminitialarabic: 0xFEDF, @@ -17873,8 +20501,6 @@ var GlyphsUnicode = { lammedialarabic: 0xFEE0, lammeemhahinitialarabic: 0xFD88, lammeeminitialarabic: 0xFCCC, - lammeemjeeminitialarabic: 'FEDF FEE4 FEA0', - lammeemkhahinitialarabic: 'FEDF FEE4 FEA8', largecircle: 0x25EF, lbar: 0x019A, lbelt: 0x026C, @@ -18171,7 +20797,6 @@ var GlyphsUnicode = { noonfinalarabic: 0xFEE6, noonghunnaarabic: 0x06BA, noonghunnafinalarabic: 0xFB9F, - noonhehinitialarabic: 0xFEE7FEEC, nooninitialarabic: 0xFEE7, noonjeeminitialarabic: 0xFCD2, noonjeemisolatedarabic: 0xFC4B, @@ -18543,27 +21168,7 @@ var GlyphsUnicode = { qof: 0x05E7, qofdagesh: 0xFB47, qofdageshhebrew: 0xFB47, - qofhatafpatah: 0x05E705B2, - qofhatafpatahhebrew: 0x05E705B2, - qofhatafsegol: 0x05E705B1, - qofhatafsegolhebrew: 0x05E705B1, qofhebrew: 0x05E7, - qofhiriq: 0x05E705B4, - qofhiriqhebrew: 0x05E705B4, - qofholam: 0x05E705B9, - qofholamhebrew: 0x05E705B9, - qofpatah: 0x05E705B7, - qofpatahhebrew: 0x05E705B7, - qofqamats: 0x05E705B8, - qofqamatshebrew: 0x05E705B8, - qofqubuts: 0x05E705BB, - qofqubutshebrew: 0x05E705BB, - qofsegol: 0x05E705B6, - qofsegolhebrew: 0x05E705B6, - qofsheva: 0x05E705B0, - qofshevahebrew: 0x05E705B0, - qoftsere: 0x05E705B5, - qoftserehebrew: 0x05E705B5, qparen: 0x24AC, quarternote: 0x2669, qubuts: 0x05BB, @@ -18637,32 +21242,11 @@ var GlyphsUnicode = { reharmenian: 0x0580, rehfinalarabic: 0xFEAE, rehiragana: 0x308C, - rehyehaleflamarabic: '0631 FEF3 FE8E 0644', rekatakana: 0x30EC, rekatakanahalfwidth: 0xFF9A, resh: 0x05E8, reshdageshhebrew: 0xFB48, - reshhatafpatah: 0x05E805B2, - reshhatafpatahhebrew: 0x05E805B2, - reshhatafsegol: 0x05E805B1, - reshhatafsegolhebrew: 0x05E805B1, reshhebrew: 0x05E8, - reshhiriq: 0x05E805B4, - reshhiriqhebrew: 0x05E805B4, - reshholam: 0x05E805B9, - reshholamhebrew: 0x05E805B9, - reshpatah: 0x05E805B7, - reshpatahhebrew: 0x05E805B7, - reshqamats: 0x05E805B8, - reshqamatshebrew: 0x05E805B8, - reshqubuts: 0x05E805BB, - reshqubutshebrew: 0x05E805BB, - reshsegol: 0x05E805B6, - reshsegolhebrew: 0x05E805B6, - reshsheva: 0x05E805B0, - reshshevahebrew: 0x05E805B0, - reshtsere: 0x05E805B5, - reshtserehebrew: 0x05E805B5, reversedtilde: 0x223D, reviahebrew: 0x0597, reviamugrashhebrew: 0x0597, @@ -18861,7 +21445,6 @@ var GlyphsUnicode = { shaddadammaarabic: 0xFC61, shaddadammatanarabic: 0xFC5E, shaddafathaarabic: 0xFC60, - shaddafathatanarabic: 0x0651064B, shaddakasraarabic: 0xFC62, shaddakasratanarabic: 0xFC5F, shade: 0x2592, @@ -19058,7 +21641,6 @@ var GlyphsUnicode = { tchehfinalarabic: 0xFB7B, tchehinitialarabic: 0xFB7C, tchehmedialarabic: 0xFB7D, - tchehmeeminitialarabic: 0xFB7CFEE4, tcircle: 0x24E3, tcircumflexbelow: 0x1E71, tcommaaccent: 0x0163, @@ -19671,7 +22253,8 @@ var GlyphsUnicode = { zretroflexhook: 0x0290, zstroke: 0x01B6, zuhiragana: 0x305A, - zukatakana: 0x30BA + zukatakana: 0x30BA, + '.notdef': 0x0000 }; /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ @@ -19679,15 +22262,44 @@ var GlyphsUnicode = { 'use strict'; -var PDFImage = (function pdfImage() { - function constructor(xref, res, image, inline) { - this.image = image; - if (image.getParams) { - // JPX/JPEG2000 streams directly contain bits per component - // and color space mode information. - TODO('get params from actual stream'); - // var bits = ... - // var colorspace = ... +var PDFImage = (function PDFImageClosure() { + /** + * Decode the image in the main thread if it supported. Resovles the promise + * when the image data is ready. + */ + function handleImageData(handler, xref, res, image, promise) { + if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) { + // For natively supported jpegs send them to the main thread for decoding. + var dict = image.dict; + var colorSpace = dict.get('ColorSpace', 'CS'); + colorSpace = ColorSpace.parse(colorSpace, xref, res); + var numComps = colorSpace.numComps; + handler.send('jpeg_decode', [image.getIR(), numComps], function(message) { + var data = message.data; + var stream = new Stream(data, 0, data.length, image.dict); + promise.resolve(stream); + }); + } else { + promise.resolve(image); + } + } + /** + * Decode and clamp a value. The formula is different from the spec because we + * don't decode to float range [0,1], we decode it in the [0,max] range. + */ + function decodeAndClamp(value, addend, coefficient, max) { + value = addend + value * coefficient; + // Clamp the value to the range + return value < 0 ? 0 : value > max ? max : value; + } + function PDFImage(xref, res, image, inline, smask) { + this.image = image; + if (image.getParams) { + // JPX/JPEG2000 streams directly contain bits per component + // and color space mode information. + TODO('get params from actual stream'); + // var bits = ... + // var colorspace = ... } // TODO cache rendered images? @@ -19725,34 +22337,143 @@ var PDFImage = (function pdfImage() { } this.decode = dict.get('Decode', 'D'); + this.needsDecode = false; + if (this.decode && this.colorSpace && + !this.colorSpace.isDefaultDecode(this.decode)) { + this.needsDecode = true; + // Do some preprocessing to avoid more math. + var max = (1 << bitsPerComponent) - 1; + this.decodeCoefficients = []; + this.decodeAddends = []; + for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) { + var dmin = this.decode[i]; + var dmax = this.decode[i + 1]; + this.decodeCoefficients[j] = dmax - dmin; + this.decodeAddends[j] = max * dmin; + } + } - var mask = xref.fetchIfRef(dict.get('Mask')); - var smask = xref.fetchIfRef(dict.get('SMask')); + var mask = dict.get('Mask'); if (mask) { TODO('masked images'); } else if (smask) { - this.smask = new PDFImage(xref, res, smask); + this.smask = new PDFImage(xref, res, smask, false); } } + /** + * Handles processing of image data and calls the callback with an argument + * of a PDFImage when the image is ready to be used. + */ + PDFImage.buildImage = function PDFImage_buildImage(callback, handler, xref, + res, image, inline) { + var imageDataPromise = new Promise(); + var smaskPromise = new Promise(); + // The image data and smask data may not be ready yet, wait till both are + // resolved. + Promise.all([imageDataPromise, smaskPromise]).then(function(results) { + var imageData = results[0], smaskData = results[1]; + var image = new PDFImage(xref, res, imageData, inline, smaskData); + callback(image); + }); - constructor.prototype = { - getComponents: function getComponents(buffer, decodeMap) { + handleImageData(handler, xref, res, image, imageDataPromise); + + var smask = image.dict.get('SMask'); + if (smask) + handleImageData(handler, xref, res, smask, smaskPromise); + else + smaskPromise.resolve(null); + }; + + /** + * Resize an image using the nearest neighbor algorithm. Currently only + * supports one and three component images. + * @param {TypedArray} pixels The original image with one component. + * @param {Number} bpc Number of bits per component. + * @param {Number} components Number of color components, 1 or 3 is supported. + * @param {Number} w1 Original width. + * @param {Number} h1 Original height. + * @param {Number} w2 New width. + * @param {Number} h2 New height. + * @return {TypedArray} Resized image data. + */ + PDFImage.resize = function PDFImage_resize(pixels, bpc, components, + w1, h1, w2, h2) { + var length = w2 * h2 * components; + var temp = bpc <= 8 ? new Uint8Array(length) : + bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length); + var xRatio = w1 / w2; + var yRatio = h1 / h2; + var px, py, newIndex, oldIndex; + for (var i = 0; i < h2; i++) { + for (var j = 0; j < w2; j++) { + px = Math.floor(j * xRatio); + py = Math.floor(i * yRatio); + newIndex = (i * w2) + j; + oldIndex = ((py * w1) + px); + if (components === 1) { + temp[newIndex] = pixels[oldIndex]; + } else if (components === 3) { + newIndex *= 3; + oldIndex *= 3; + temp[newIndex] = pixels[oldIndex]; + temp[newIndex + 1] = pixels[oldIndex + 1]; + temp[newIndex + 2] = pixels[oldIndex + 2]; + } + } + } + return temp; + }; + + PDFImage.prototype = { + get drawWidth() { + if (!this.smask) + return this.width; + return Math.max(this.width, this.smask.width); + }, + get drawHeight() { + if (!this.smask) + return this.height; + return Math.max(this.height, this.smask.height); + }, + getComponents: function PDFImage_getComponents(buffer) { var bpc = this.bpc; - if (bpc == 8) + var needsDecode = this.needsDecode; + var decodeMap = this.decode; + + // This image doesn't require any extra work. + if (bpc == 8 && !needsDecode) return buffer; + var bufferLength = buffer.length; var width = this.width; var height = this.height; var numComps = this.numComps; - var length = width * height; + var length = width * height * numComps; var bufferPos = 0; var output = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length); var rowComps = width * numComps; + var decodeAddends, decodeCoefficients; + if (needsDecode) { + decodeAddends = this.decodeAddends; + decodeCoefficients = this.decodeCoefficients; + } + var max = (1 << bpc) - 1; - if (bpc == 1) { + if (bpc == 8) { + // Optimization for reading 8 bpc images that have a decode. + for (var i = 0, ii = length; i < ii; ++i) { + var compIndex = i % numComps; + var value = buffer[i]; + value = decodeAndClamp(value, decodeAddends[compIndex], + decodeCoefficients[compIndex], max); + output[i] = value; + } + } else if (bpc == 1) { + // Optimization for reading 1 bpc images. var valueZero = 0, valueOne = 1; if (decodeMap) { valueZero = decodeMap[0] ? 1 : 0; @@ -19777,8 +22498,7 @@ var PDFImage = (function pdfImage() { output[i] = !(buf & mask) ? valueZero : valueOne; } } else { - if (decodeMap != null) - TODO('interpolate component values'); + // The general case that handles all other bpc values. var bits = 0, buf = 0; for (var i = 0, ii = length; i < ii; ++i) { if (i % rowComps == 0) { @@ -19792,51 +22512,44 @@ var PDFImage = (function pdfImage() { } var remainingBits = bits - bpc; - output[i] = buf >> remainingBits; + var value = buf >> remainingBits; + if (needsDecode) { + var compIndex = i % numComps; + value = decodeAndClamp(value, decodeAddends[compIndex], + decodeCoefficients[compIndex], max); + } + output[i] = value; buf = buf & ((1 << remainingBits) - 1); bits = remainingBits; } } return output; }, - getOpacity: function getOpacity() { + getOpacity: function PDFImage_getOpacity(width, height) { var smask = this.smask; - var width = this.width; - var height = this.height; - var buf = new Uint8Array(width * height); + var originalWidth = this.width; + var originalHeight = this.height; + var buf; if (smask) { - if (smask.image.getImage) { - // smask is a DOM image - var tempCanvas = new ScratchCanvas(width, height); - var tempCtx = tempCanvas.getContext('2d'); - var domImage = smask.image.getImage(); - tempCtx.drawImage(domImage, 0, 0, domImage.width, domImage.height, - 0, 0, width, height); - var data = tempCtx.getImageData(0, 0, width, height).data; - for (var i = 0, j = 0, ii = width * height; i < ii; ++i, j += 4) - buf[i] = data[j]; // getting first component value - return buf; - } var sw = smask.width; var sh = smask.height; - if (sw != this.width || sh != this.height) - error('smask dimensions do not match image dimensions: ' + sw + - ' != ' + this.width + ', ' + sh + ' != ' + this.height); - + buf = new Uint8Array(sw * sh); smask.fillGrayBuffer(buf); - return buf; + if (sw != width || sh != height) + buf = PDFImage.resize(buf, smask.bps, 1, sw, sh, width, height); } else { + buf = new Uint8Array(width * height); for (var i = 0, ii = width * height; i < ii; ++i) buf[i] = 255; } return buf; }, - applyStencilMask: function applyStencilMask(buffer, inverseDecode) { + applyStencilMask: function PDFImage_applyStencilMask(buffer, + inverseDecode) { var width = this.width, height = this.height; var bitStrideLength = (width + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(bitStrideLength * height); + var imgArray = this.getImageBytes(bitStrideLength * height); var imgArrayPos = 0; var i, j, mask, buf; // removing making non-masked pixels transparent @@ -19856,21 +22569,23 @@ var PDFImage = (function pdfImage() { } } }, - fillRgbaBuffer: function fillRgbaBuffer(buffer, decodeMap) { + fillRgbaBuffer: function PDFImage_fillRgbaBuffer(buffer, width, height) { var numComps = this.numComps; - var width = this.width; - var height = this.height; + var originalWidth = this.width; + var originalHeight = this.height; var bpc = this.bpc; // rows start at byte boundary; - var rowBytes = (width * numComps * bpc + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(height * rowBytes); + var rowBytes = (originalWidth * numComps * bpc + 7) >> 3; + var imgArray = this.getImageBytes(originalHeight * rowBytes); var comps = this.colorSpace.getRgbBuffer( - this.getComponents(imgArray, decodeMap), bpc); + this.getComponents(imgArray), bpc); + if (originalWidth != width || originalHeight != height) + comps = PDFImage.resize(comps, this.bpc, 3, originalWidth, + originalHeight, width, height); var compsPos = 0; - var opacity = this.getOpacity(); + var opacity = this.getOpacity(width, height); var opacityPos = 0; var length = width * height * 4; @@ -19881,7 +22596,7 @@ var PDFImage = (function pdfImage() { buffer[i + 3] = opacity[opacityPos++]; } }, - fillGrayBuffer: function fillGrayBuffer(buffer) { + fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) { var numComps = this.numComps; if (numComps != 1) error('Reading gray scale from a color image: ' + numComps); @@ -19892,50 +22607,39 @@ var PDFImage = (function pdfImage() { // rows start at byte boundary; var rowBytes = (width * numComps * bpc + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(height * rowBytes); + var imgArray = this.getImageBytes(height * rowBytes); var comps = this.getComponents(imgArray); var length = width * height; - + // we aren't using a colorspace so we need to scale the value + var scale = 255 / ((1 << bpc) - 1); for (var i = 0; i < length; ++i) - buffer[i] = comps[i]; + buffer[i] = (scale * comps[i]) | 0; + }, + getImageBytes: function PDFImage_getImageBytes(length) { + this.image.reset(); + return this.image.getBytes(length); } }; - return constructor; + return PDFImage; })(); -var JpegImageLoader = (function jpegImage() { - function JpegImageLoader(objId, imageData, objs) { - var src = 'data:image/jpeg;base64,' + window.btoa(imageData); - - var img = new Image(); - img.onload = (function jpegImageLoaderOnload() { - this.loaded = true; - - objs.resolve(objId, this); - - if (this.onLoad) - this.onLoad(); - }).bind(this); - img.src = src; - this.domImage = img; - } - - JpegImageLoader.prototype = { - getImage: function jpegImageLoaderGetImage() { - return this.domImage; - } - }; - - return JpegImageLoader; -})(); +function loadJpegStream(id, imageData, objs) { + var img = new Image(); + img.onload = (function loadJpegStream_onloadClosure() { + objs.resolve(id, img); + }); + img.src = 'data:image/jpeg;base64,' + window.btoa(imageData); +} /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ 'use strict'; +// The Metrics object contains glyph widths (in glyph space units). +// As per PDF spec, for most fonts (Type 3 being an exception) a glyph +// space unit corresponds to 1/1000th of text space unit. var Metrics = { 'Courier': 600, 'Courier-Bold': 600, @@ -22886,8 +25590,8 @@ function isEOF(v) { return v == EOF; } -var Parser = (function parserParser() { - function constructor(lexer, allowStreams, xref) { +var Parser = (function ParserClosure() { + function Parser(lexer, allowStreams, xref) { this.lexer = lexer; this.allowStreams = allowStreams; this.xref = xref; @@ -22895,12 +25599,12 @@ var Parser = (function parserParser() { this.refill(); } - constructor.prototype = { - refill: function parserRefill() { + Parser.prototype = { + refill: function Parser_refill() { this.buf1 = this.lexer.getObj(); this.buf2 = this.lexer.getObj(); }, - shift: function parserShift() { + shift: function Parser_shift() { if (isCmd(this.buf2, 'ID')) { this.buf1 = this.buf2; this.buf2 = null; @@ -22911,7 +25615,7 @@ var Parser = (function parserParser() { this.buf2 = this.lexer.getObj(); } }, - getObj: function parserGetObj(cipherTransform) { + getObj: function Parser_getObj(cipherTransform) { if (isCmd(this.buf1, 'BI')) { // inline image this.shift(); return this.makeInlineImage(cipherTransform); @@ -22928,17 +25632,16 @@ var Parser = (function parserParser() { } if (isCmd(this.buf1, '<<')) { // dictionary or stream this.shift(); - var dict = new Dict(); + var dict = new Dict(this.xref); while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) { - if (!isName(this.buf1)) { + if (!isName(this.buf1)) error('Dictionary key must be a name object'); - } else { - var key = this.buf1.name; - this.shift(); - if (isEOF(this.buf1)) - break; - dict.set(key, this.getObj(cipherTransform)); - } + + var key = this.buf1.name; + this.shift(); + if (isEOF(this.buf1)) + break; + dict.set(key, this.getObj(cipherTransform)); } if (isEOF(this.buf1)) error('End of file inside dictionary'); @@ -22976,38 +25679,37 @@ var Parser = (function parserParser() { this.shift(); return obj; }, - makeInlineImage: function parserMakeInlineImage(cipherTransform) { + makeInlineImage: function Parser_makeInlineImage(cipherTransform) { var lexer = this.lexer; var stream = lexer.stream; // parse dictionary var dict = new Dict(); while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) { - if (!isName(this.buf1)) { + if (!isName(this.buf1)) error('Dictionary key must be a name object'); - } else { - var key = this.buf1.name; - this.shift(); - if (isEOF(this.buf1)) - break; - dict.set(key, this.getObj(cipherTransform)); - } + + var key = this.buf1.name; + this.shift(); + if (isEOF(this.buf1)) + break; + dict.set(key, this.getObj(cipherTransform)); } // parse image stream var startPos = stream.pos; - // searching for the /\sEI\s/ + // searching for the /EI\s/ var state = 0, ch; while (state != 4 && (ch = stream.getByte()) != null) { switch (ch) { case 0x20: case 0x0D: case 0x0A: - state = state === 3 ? 4 : 1; + state = state === 3 ? 4 : 0; break; case 0x45: - state = state === 1 ? 2 : 0; + state = 2; break; case 0x49: state = state === 2 ? 3 : 0; @@ -23034,12 +25736,16 @@ var Parser = (function parserParser() { imageStream = this.filter(imageStream, dict, length); imageStream.parameters = dict; - this.buf2 = new Cmd('EI'); + this.buf2 = Cmd.get('EI'); this.shift(); return imageStream; }, - makeStream: function parserMakeStream(dict, cipherTransform) { + fetchIfRef: function Parser_fetchIfRef(obj) { + // not relying on the xref.fetchIfRef -- xref might not be set + return isRef(obj) ? this.xref.fetch(obj) : obj; + }, + makeStream: function Parser_makeStream(dict, cipherTransform) { var lexer = this.lexer; var stream = lexer.stream; @@ -23048,14 +25754,9 @@ var Parser = (function parserParser() { var pos = stream.pos; // get length - var length = dict.get('Length'); - var xref = this.xref; - if (xref) - length = xref.fetchIfRef(length); - if (!isInt(length)) { + var length = this.fetchIfRef(dict.get('Length')); + if (!isInt(length)) error('Bad ' + length + ' attribute in stream'); - length = 0; - } // skip over the stream data stream.pos = pos + length; @@ -23072,9 +25773,9 @@ var Parser = (function parserParser() { stream.parameters = dict; return stream; }, - filter: function parserFilter(stream, dict, length) { - var filter = dict.get('Filter', 'F'); - var params = dict.get('DecodeParms', 'DP'); + filter: function Parser_filter(stream, dict, length) { + var filter = this.fetchIfRef(dict.get('Filter', 'F')); + var params = this.fetchIfRef(dict.get('DecodeParms', 'DP')); if (isName(filter)) return this.makeFilter(stream, filter.name, length, params); if (isArray(filter)) { @@ -23084,25 +25785,25 @@ var Parser = (function parserParser() { filter = filterArray[i]; if (!isName(filter)) error('Bad filter name: ' + filter); - else { - params = null; - if (isArray(paramsArray) && (i in paramsArray)) - params = paramsArray[i]; - stream = this.makeFilter(stream, filter.name, length, params); - // after the first stream the length variable is invalid - length = null; - } + + params = null; + if (isArray(paramsArray) && (i in paramsArray)) + params = paramsArray[i]; + stream = this.makeFilter(stream, filter.name, length, params); + // after the first stream the length variable is invalid + length = null; } } return stream; }, - makeFilter: function parserMakeFilter(stream, name, length, params) { + makeFilter: function Parser_makeFilter(stream, name, length, params) { if (name == 'FlateDecode' || name == 'Fl') { if (params) { return new PredictorStream(new FlateStream(stream), params); } return new FlateStream(stream); - } else if (name == 'LZWDecode' || name == 'LZW') { + } + if (name == 'LZWDecode' || name == 'LZW') { var earlyChange = 1; if (params) { if (params.has('EarlyChange')) @@ -23111,31 +25812,41 @@ var Parser = (function parserParser() { new LZWStream(stream, earlyChange), params); } return new LZWStream(stream, earlyChange); - } else if (name == 'DCTDecode' || name == 'DCT') { + } + if (name == 'DCTDecode' || name == 'DCT') { var bytes = stream.getBytes(length); return new JpegStream(bytes, stream.dict, this.xref); - } else if (name == 'ASCII85Decode' || name == 'A85') { + } + if (name == 'JPXDecode' || name == 'JPX') { + var bytes = stream.getBytes(length); + return new JpxStream(bytes, stream.dict); + } + if (name == 'ASCII85Decode' || name == 'A85') { return new Ascii85Stream(stream); - } else if (name == 'ASCIIHexDecode' || name == 'AHx') { + } + if (name == 'ASCIIHexDecode' || name == 'AHx') { return new AsciiHexStream(stream); - } else if (name == 'CCITTFaxDecode' || name == 'CCF') { + } + if (name == 'CCITTFaxDecode' || name == 'CCF') { return new CCITTFaxStream(stream, params); - } else { - TODO('filter "' + name + '" not supported yet'); } + if (name == 'RunLengthDecode') { + return new RunLengthStream(stream); + } + warn('filter "' + name + '" not supported yet'); return stream; } }; - return constructor; + return Parser; })(); -var Lexer = (function lexer() { - function constructor(stream) { +var Lexer = (function LexerClosure() { + function Lexer(stream) { this.stream = stream; } - constructor.isSpace = function lexerIsSpace(ch) { + Lexer.isSpace = function Lexer_isSpace(ch) { return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a'; }; @@ -23169,8 +25880,8 @@ var Lexer = (function lexer() { return -1; } - constructor.prototype = { - getNumber: function lexerGetNumber(ch) { + Lexer.prototype = { + getNumber: function Lexer_getNumber(ch) { var floating = false; var str = ch; var stream = this.stream; @@ -23198,7 +25909,7 @@ var Lexer = (function lexer() { error('Invalid floating point number: ' + value); return value; }, - getString: function lexerGetString() { + getString: function Lexer_getString() { var numParen = 1; var done = false; var str = ''; @@ -23282,7 +25993,7 @@ var Lexer = (function lexer() { } while (!done); return str; }, - getName: function lexerGetName(ch) { + getName: function Lexer_getName(ch) { var str = ''; var stream = this.stream; while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) { @@ -23309,7 +26020,7 @@ var Lexer = (function lexer() { str.length); return new Name(str); }, - getHexString: function lexerGetHexString(ch) { + getHexString: function Lexer_getHexString(ch) { var str = ''; var stream = this.stream; for (;;) { @@ -23338,7 +26049,7 @@ var Lexer = (function lexer() { } return str; }, - getObj: function lexerGetObj() { + getObj: function Lexer_getObj() { // skip whitespace and comments var comment = false; var stream = this.stream; @@ -23369,14 +26080,14 @@ var Lexer = (function lexer() { // array punctuation case '[': case ']': - return new Cmd(ch); + return Cmd.get(ch); // hex string or dict punctuation case '<': ch = stream.lookChar(); if (ch == '<') { // dict punctuation stream.skip(); - return new Cmd('<<'); + return Cmd.get('<<'); } return this.getHexString(ch); // dict punctuation @@ -23384,25 +26095,23 @@ var Lexer = (function lexer() { ch = stream.lookChar(); if (ch == '>') { stream.skip(); - return new Cmd('>>'); + return Cmd.get('>>'); } case '{': case '}': - return new Cmd(ch); + return Cmd.get(ch); // fall through case ')': error('Illegal character: ' + ch); - return Error; } // command var str = ch; while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) { stream.skip(); - if (str.length == 128) { + if (str.length == 128) error('Command token too long: ' + str.length); - break; - } + str += ch; } if (str == 'true') @@ -23411,9 +26120,9 @@ var Lexer = (function lexer() { return false; if (str == 'null') return null; - return new Cmd(str); + return Cmd.get(str); }, - skipToNextLine: function lexerSkipToNextLine() { + skipToNextLine: function Lexer_skipToNextLine() { var stream = this.stream; while (true) { var ch = stream.getChar(); @@ -23426,17 +26135,17 @@ var Lexer = (function lexer() { } } }, - skip: function lexerSkip() { + skip: function Lexer_skip() { this.stream.skip(); } }; - return constructor; + return Lexer; })(); -var Linearization = (function linearizationLinearization() { - function constructor(stream) { - this.parser = new Parser(new Lexer(stream), false); +var Linearization = (function LinearizationClosure() { + function Linearization(stream) { + this.parser = new Parser(new Lexer(stream), false, null); var obj1 = this.parser.getObj(); var obj2 = this.parser.getObj(); var obj3 = this.parser.getObj(); @@ -23449,8 +26158,8 @@ var Linearization = (function linearizationLinearization() { } } - constructor.prototype = { - getInt: function linearizationGetInt(name) { + Linearization.prototype = { + getInt: function Linearization_getInt(name) { var linDict = this.linDict; var obj; if (isDict(linDict) && @@ -23459,9 +26168,8 @@ var Linearization = (function linearizationLinearization() { return obj; } error('"' + name + '" field in linearization table is invalid'); - return 0; }, - getHint: function linearizationGetHint(index) { + getHint: function Linearization_getHint(index) { var linDict = this.linDict; var obj1, obj2; if (isDict(linDict) && @@ -23472,7 +26180,6 @@ var Linearization = (function linearizationLinearization() { return obj2; } error('Hints table in linearization table is invalid: ' + index); - return 0; }, get length() { if (!isDict(this.linDict)) @@ -23508,7 +26215,7 @@ var Linearization = (function linearizationLinearization() { } }; - return constructor; + return Linearization; })(); /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ @@ -23516,48 +26223,53 @@ var Linearization = (function linearizationLinearization() { 'use strict'; -var Pattern = (function patternPattern() { +var PatternType = { + AXIAL: 2, + RADIAL: 3 +}; + +var Pattern = (function PatternClosure() { // Constructor should define this.getPattern - function constructor() { + function Pattern() { error('should not call Pattern constructor'); } - constructor.prototype = { + Pattern.prototype = { // Input: current Canvas context // Output: the appropriate fillStyle or strokeStyle - getPattern: function pattern_getStyle(ctx) { + getPattern: function Pattern_getPattern(ctx) { error('Should not call Pattern.getStyle: ' + ctx); } }; - constructor.shadingFromIR = function pattern_shadingFromIR(ctx, raw) { - return Shadings[raw[0]].fromIR(ctx, raw); + Pattern.shadingFromIR = function Pattern_shadingFromIR(raw) { + return Shadings[raw[0]].fromIR(raw); }; - constructor.parseShading = function pattern_shading(shading, matrix, xref, - res, ctx) { + Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref, + res) { var dict = isStream(shading) ? shading.dict : shading; var type = dict.get('ShadingType'); switch (type) { - case 2: - case 3: - // both radial and axial shadings are handled by RadialAxial shading - return new Shadings.RadialAxial(dict, matrix, xref, res, ctx); + case PatternType.AXIAL: + case PatternType.RADIAL: + // Both radial and axial shadings are handled by RadialAxial shading. + return new Shadings.RadialAxial(dict, matrix, xref, res); default: return new Shadings.Dummy(); } }; - return constructor; + return Pattern; })(); var Shadings = {}; // Radial and axial shading have very similar implementations // If needed, the implementations can be broken into two classes -Shadings.RadialAxial = (function radialAxialShading() { - function constructor(dict, matrix, xref, res, ctx) { +Shadings.RadialAxial = (function RadialAxialClosure() { + function RadialAxial(dict, matrix, xref, res, ctx) { this.matrix = matrix; this.coordsArr = dict.get('Coords'); this.shadingType = dict.get('ShadingType'); @@ -23587,10 +26299,9 @@ Shadings.RadialAxial = (function radialAxialShading() { this.extendEnd = extendEnd; var fnObj = dict.get('Function'); - fnObj = xref.fetchIfRef(fnObj); if (isArray(fnObj)) error('No support for array of functions'); - else if (!isPDFFunction(fnObj)) + if (!isPDFFunction(fnObj)) error('Invalid function'); var fn = PDFFunction.parse(xref, fnObj); @@ -23602,56 +26313,60 @@ Shadings.RadialAxial = (function radialAxialShading() { var colorStops = []; for (var i = t0; i <= t1; i += step) { - var color = fn([i]); - var rgbColor = Util.makeCssRgb.apply(this, cs.getRgb(color)); - colorStops.push([(i - t0) / diff, rgbColor]); + var rgbColor = cs.getRgb(fn([i])); + var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); + colorStops.push([(i - t0) / diff, cssColor]); } this.colorStops = colorStops; } - constructor.fromIR = function radialAxialShadingGetIR(ctx, raw) { + RadialAxial.fromIR = function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; + return { + type: 'Pattern', + getPattern: function(ctx) { + var curMatrix = ctx.mozCurrentTransform; + if (curMatrix) { + var userMatrix = ctx.mozCurrentTransformInverse; + + p0 = Util.applyTransform(p0, curMatrix); + p0 = Util.applyTransform(p0, userMatrix); + + p1 = Util.applyTransform(p1, curMatrix); + p1 = Util.applyTransform(p1, userMatrix); + } - var curMatrix = ctx.mozCurrentTransform; - if (curMatrix) { - var userMatrix = ctx.mozCurrentTransformInverse; - - p0 = Util.applyTransform(p0, curMatrix); - p0 = Util.applyTransform(p0, userMatrix); - - p1 = Util.applyTransform(p1, curMatrix); - p1 = Util.applyTransform(p1, userMatrix); - } - - var grad; - if (type == 2) - grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); - else if (type == 3) - grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); + var grad; + if (type == PatternType.AXIAL) + grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); + else if (type == PatternType.RADIAL) + grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); - for (var i = 0, ii = colorStops.length; i < ii; ++i) { - var c = colorStops[i]; - grad.addColorStop(c[0], c[1]); - } - return grad; + for (var i = 0, ii = colorStops.length; i < ii; ++i) { + var c = colorStops[i]; + grad.addColorStop(c[0], c[1]); + } + return grad; + } + }; }; - constructor.prototype = { - getIR: function radialAxialShadingGetIR() { + RadialAxial.prototype = { + getIR: function RadialAxial_getIR() { var coordsArr = this.coordsArr; var type = this.shadingType; - if (type == 2) { + if (type == PatternType.AXIAL) { var p0 = [coordsArr[0], coordsArr[1]]; var p1 = [coordsArr[2], coordsArr[3]]; var r0 = null; var r1 = null; - } else if (type == 3) { + } else if (type == PatternType.RADIAL) { var p0 = [coordsArr[0], coordsArr[1]]; var p1 = [coordsArr[3], coordsArr[4]]; var r0 = coordsArr[2]; @@ -23670,31 +26385,35 @@ Shadings.RadialAxial = (function radialAxialShading() { } }; - return constructor; + return RadialAxial; })(); -Shadings.Dummy = (function dummyShading() { - function constructor() { +Shadings.Dummy = (function DummyClosure() { + function Dummy() { this.type = 'Pattern'; } - constructor.fromIR = function dummyShadingFromIR() { + Dummy.fromIR = function Dummy_fromIR() { return 'hotpink'; }; - constructor.prototype = { - getIR: function dummyShadingGetIR() { + Dummy.prototype = { + getIR: function Dummy_getIR() { return ['Dummy']; } }; - return constructor; + return Dummy; })(); -var TilingPattern = (function tilingPattern() { - var PAINT_TYPE_COLORED = 1, PAINT_TYPE_UNCOLORED = 2; +var TilingPattern = (function TilingPatternClosure() { + var PaintType = { + COLORED: 1, + UNCOLORED: 2 + }; + var MAX_PATTERN_SIZE = 512; function TilingPattern(IR, color, ctx, objs) { - var IRQueue = IR[2]; + var operatorList = IR[2]; this.matrix = IR[3]; var bbox = IR[4]; var xstep = IR[5]; @@ -23717,30 +26436,30 @@ var TilingPattern = (function tilingPattern() { var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; - // TODO: hack to avoid OOM, we would idealy compute the tiling + // TODO: hack to avoid OOM, we would ideally compute the tiling // pattern to be only as large as the acual size in device space // This could be computed with .mozCurrentTransform, but still // needs to be implemented - while (Math.abs(width) > 512 || Math.abs(height) > 512) { - width = 512; - height = 512; + while (Math.abs(width) > MAX_PATTERN_SIZE || + Math.abs(height) > MAX_PATTERN_SIZE) { + width = height = MAX_PATTERN_SIZE; } - var tmpCanvas = new ScratchCanvas(width, height); + var tmpCanvas = createScratchCanvas(width, height); // set the new canvas element context as the graphics context var tmpCtx = tmpCanvas.getContext('2d'); var graphics = new CanvasGraphics(tmpCtx, objs); switch (paintType) { - case PAINT_TYPE_COLORED: + case PaintType.COLORED: tmpCtx.fillStyle = ctx.fillStyle; tmpCtx.strokeStyle = ctx.strokeStyle; break; - case PAINT_TYPE_UNCOLORED: - color = Util.makeCssRgb.apply(this, color); - tmpCtx.fillStyle = color; - tmpCtx.strokeStyle = color; + case PaintType.UNCOLORED: + var cssColor = Util.makeCssRgb(this, color[0], color[1], color[2]); + tmpCtx.fillStyle = cssColor; + tmpCtx.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); @@ -23763,12 +26482,12 @@ var TilingPattern = (function tilingPattern() { graphics.endPath(); } - graphics.executeIRQueue(IRQueue); + graphics.executeOperatorList(operatorList); this.canvas = tmpCanvas; } - TilingPattern.getIR = function tiling_getIR(codeIR, dict, args) { + TilingPattern.getIR = function TilingPattern_getIR(operatorList, dict, args) { var matrix = dict.get('Matrix'); var bbox = dict.get('BBox'); var xstep = dict.get('XStep'); @@ -23776,12 +26495,12 @@ var TilingPattern = (function tilingPattern() { var paintType = dict.get('PaintType'); return [ - 'TilingPattern', args, codeIR, matrix, bbox, xstep, ystep, paintType + 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep, paintType ]; }; TilingPattern.prototype = { - getPattern: function tiling_getPattern() { + getPattern: function TilingPattern_getPattern() { var matrix = this.matrix; var curMatrix = this.curMatrix; var ctx = this.ctx; @@ -23807,8 +26526,8 @@ var TilingPattern = (function tilingPattern() { 'use strict'; -var Stream = (function streamStream() { - function constructor(arrayBuffer, start, length, dict) { +var Stream = (function StreamClosure() { + function Stream(arrayBuffer, start, length, dict) { this.bytes = new Uint8Array(arrayBuffer); this.start = start || 0; this.pos = this.start; @@ -23818,18 +26537,18 @@ var Stream = (function streamStream() { // required methods for a stream. if a particular stream does not // implement these, an error should be thrown - constructor.prototype = { + Stream.prototype = { get length() { return this.end - this.start; }, - getByte: function stream_getByte() { + getByte: function Stream_getByte() { if (this.pos >= this.end) return null; return this.bytes[this.pos++]; }, // returns subarray of original buffer // should only be read - getBytes: function stream_getBytes(length) { + getBytes: function Stream_getBytes(length) { var bytes = this.bytes; var pos = this.pos; var strEnd = this.end; @@ -23844,38 +26563,38 @@ var Stream = (function streamStream() { this.pos = end; return bytes.subarray(pos, end); }, - lookChar: function stream_lookChar() { + lookChar: function Stream_lookChar() { if (this.pos >= this.end) return null; return String.fromCharCode(this.bytes[this.pos]); }, - getChar: function stream_getChar() { + getChar: function Stream_getChar() { if (this.pos >= this.end) return null; return String.fromCharCode(this.bytes[this.pos++]); }, - skip: function stream_skip(n) { + skip: function Stream_skip(n) { if (!n) n = 1; this.pos += n; }, - reset: function stream_reset() { + reset: function Stream_reset() { this.pos = this.start; }, - moveStart: function stream_moveStart() { + moveStart: function Stream_moveStart() { this.start = this.pos; }, - makeSubStream: function stream_makeSubstream(start, length, dict) { + makeSubStream: function Stream_makeSubStream(start, length, dict) { return new Stream(this.bytes.buffer, start, length, dict); }, isStream: true }; - return constructor; + return Stream; })(); -var StringStream = (function stringStream() { - function constructor(str) { +var StringStream = (function StringStreamClosure() { + function StringStream(str) { var length = str.length; var bytes = new Uint8Array(length); for (var n = 0; n < length; ++n) @@ -23883,22 +26602,22 @@ var StringStream = (function stringStream() { Stream.call(this, bytes); } - constructor.prototype = Stream.prototype; + StringStream.prototype = Stream.prototype; - return constructor; + return StringStream; })(); // super class for the decoding streams -var DecodeStream = (function decodeStream() { - function constructor() { +var DecodeStream = (function DecodeStreamClosure() { + function DecodeStream() { this.pos = 0; this.bufferLength = 0; this.eof = false; this.buffer = null; } - constructor.prototype = { - ensureBuffer: function decodestream_ensureBuffer(requested) { + DecodeStream.prototype = { + ensureBuffer: function DecodeStream_ensureBuffer(requested) { var buffer = this.buffer; var current = buffer ? buffer.byteLength : 0; if (requested < current) @@ -23911,7 +26630,7 @@ var DecodeStream = (function decodeStream() { buffer2[i] = buffer[i]; return (this.buffer = buffer2); }, - getByte: function decodestream_getByte() { + getByte: function DecodeStream_getByte() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -23920,7 +26639,7 @@ var DecodeStream = (function decodeStream() { } return this.buffer[this.pos++]; }, - getBytes: function decodestream_getBytes(length) { + getBytes: function DecodeStream_getBytes(length) { var end, pos = this.pos; if (length) { @@ -23948,7 +26667,7 @@ var DecodeStream = (function decodeStream() { this.pos = end; return this.buffer.subarray(pos, end); }, - lookChar: function decodestream_lookChar() { + lookChar: function DecodeStream_lookChar() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -23957,7 +26676,7 @@ var DecodeStream = (function decodeStream() { } return String.fromCharCode(this.buffer[this.pos]); }, - getChar: function decodestream_getChar() { + getChar: function DecodeStream_getChar() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -23966,40 +26685,40 @@ var DecodeStream = (function decodeStream() { } return String.fromCharCode(this.buffer[this.pos++]); }, - makeSubStream: function decodestream_makeSubstream(start, length, dict) { + makeSubStream: function DecodeStream_makeSubStream(start, length, dict) { var end = start + length; while (this.bufferLength <= end && !this.eof) this.readBlock(); return new Stream(this.buffer, start, length, dict); }, - skip: function decodestream_skip(n) { + skip: function DecodeStream_skip(n) { if (!n) n = 1; this.pos += n; }, - reset: function decodestream_reset() { + reset: function DecodeStream_reset() { this.pos = 0; } }; - return constructor; + return DecodeStream; })(); -var FakeStream = (function fakeStream() { - function constructor(stream) { +var FakeStream = (function FakeStreamClosure() { + function FakeStream(stream) { this.dict = stream.dict; DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function fakeStreamReadBlock() { + FakeStream.prototype = Object.create(DecodeStream.prototype); + FakeStream.prototype.readBlock = function FakeStream_readBlock() { var bufferLength = this.bufferLength; bufferLength += 1024; var buffer = this.ensureBuffer(bufferLength); this.bufferLength = bufferLength; }; - constructor.prototype.getBytes = function fakeStreamGetBytes(length) { + FakeStream.prototype.getBytes = function FakeStream_getBytes(length) { var end, pos = this.pos; if (length) { @@ -24021,18 +26740,20 @@ var FakeStream = (function fakeStream() { return this.buffer.subarray(pos, end); }; - return constructor; + return FakeStream; })(); -var StreamsSequenceStream = (function streamSequenceStream() { - function constructor(streams) { +var StreamsSequenceStream = (function StreamsSequenceStreamClosure() { + function StreamsSequenceStream(streams) { this.streams = streams; DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype); + + StreamsSequenceStream.prototype.readBlock = + function streamSequenceStreamReadBlock() { - constructor.prototype.readBlock = function streamSequenceStreamReadBlock() { var streams = this.streams; if (streams.length == 0) { this.eof = true; @@ -24047,10 +26768,10 @@ var StreamsSequenceStream = (function streamSequenceStream() { this.bufferLength = newLength; }; - return constructor; + return StreamsSequenceStream; })(); -var FlateStream = (function flateStream() { +var FlateStream = (function FlateStreamClosure() { var codeLenCodeMap = new Uint32Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); @@ -24143,7 +26864,7 @@ var FlateStream = (function flateStream() { 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000 ]), 5]; - function constructor(stream) { + function FlateStream(stream) { var bytes = stream.getBytes(); var bytesPos = 0; @@ -24168,9 +26889,9 @@ var FlateStream = (function flateStream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + FlateStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.getBits = function flateStreamGetBits(bits) { + FlateStream.prototype.getBits = function FlateStream_getBits(bits) { var codeSize = this.codeSize; var codeBuf = this.codeBuf; var bytes = this.bytes; @@ -24190,7 +26911,7 @@ var FlateStream = (function flateStream() { return b; }; - constructor.prototype.getCode = function flateStreamGetCode(table) { + FlateStream.prototype.getCode = function FlateStream_getCode(table) { var codes = table[0]; var maxLen = table[1]; var codeSize = this.codeSize; @@ -24216,7 +26937,7 @@ var FlateStream = (function flateStream() { return codeVal; }; - constructor.prototype.generateHuffmanTable = + FlateStream.prototype.generateHuffmanTable = function flateStreamGenerateHuffmanTable(lengths) { var n = lengths.length; @@ -24255,7 +26976,7 @@ var FlateStream = (function flateStream() { return [codes, maxLen]; }; - constructor.prototype.readBlock = function flateStreamReadBlock() { + FlateStream.prototype.readBlock = function FlateStream_readBlock() { // read block header var hdr = this.getBits(3); if (hdr & 1) @@ -24386,11 +27107,11 @@ var FlateStream = (function flateStream() { } }; - return constructor; + return FlateStream; })(); -var PredictorStream = (function predictorStream() { - function constructor(stream, params) { +var PredictorStream = (function PredictorStreamClosure() { + function PredictorStream(stream, params) { var predictor = this.predictor = params.get('Predictor') || 1; if (predictor <= 1) @@ -24417,15 +27138,14 @@ var PredictorStream = (function predictorStream() { return this; } - constructor.prototype = Object.create(DecodeStream.prototype); + PredictorStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlockTiff = + PredictorStream.prototype.readBlockTiff = function predictorStreamReadBlockTiff() { var rowBytes = this.rowBytes; var bufferLength = this.bufferLength; var buffer = this.ensureBuffer(bufferLength + rowBytes); - var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes); var bits = this.bits; var colors = this.colors; @@ -24434,6 +27154,7 @@ var PredictorStream = (function predictorStream() { var inbuf = 0, outbuf = 0; var inbits = 0, outbits = 0; + var pos = bufferLength; if (bits === 1) { for (var i = 0; i < rowBytes; ++i) { @@ -24441,19 +27162,21 @@ var PredictorStream = (function predictorStream() { inbuf = (inbuf << 8) | c; // bitwise addition is exclusive or // first shift inbuf and then add - currentRow[i] = (c ^ (inbuf >> colors)) & 0xFF; + buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF; // truncate inbuf (assumes colors < 16) inbuf &= 0xFFFF; } } else if (bits === 8) { for (var i = 0; i < colors; ++i) - currentRow[i] = rawBytes[i]; - for (; i < rowBytes; ++i) - currentRow[i] = currentRow[i - colors] + rawBytes[i]; + buffer[pos++] = rawBytes[i]; + for (; i < rowBytes; ++i) { + buffer[pos] = buffer[pos - colors] + rawBytes[i]; + pos++; + } } else { var compArray = new Uint8Array(colors + 1); var bitMask = (1 << bits) - 1; - var j = 0, k = 0; + var j = 0, k = bufferLength; var columns = this.columns; for (var i = 0; i < columns; ++i) { for (var kk = 0; kk < colors; ++kk) { @@ -24467,20 +27190,22 @@ var PredictorStream = (function predictorStream() { outbuf = (outbuf << bits) | compArray[kk]; outbits += bits; if (outbits >= 8) { - currentRow[k++] = (outbuf >> (outbits - 8)) & 0xFF; + buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF; outbits -= 8; } } } if (outbits > 0) { - currentRow[k++] = (outbuf << (8 - outbits)) + + buffer[k++] = (outbuf << (8 - outbits)) + (inbuf & ((1 << (8 - outbits)) - 1)); } } this.bufferLength += rowBytes; }; - constructor.prototype.readBlockPng = function predictorStreamReadBlockPng() { + PredictorStream.prototype.readBlockPng = + function predictorStreamReadBlockPng() { + var rowBytes = this.rowBytes; var pixBytes = this.pixBytes; @@ -24490,32 +27215,35 @@ var PredictorStream = (function predictorStream() { var bufferLength = this.bufferLength; var buffer = this.ensureBuffer(bufferLength + rowBytes); - var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes); var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength); if (prevRow.length == 0) prevRow = new Uint8Array(rowBytes); + var j = bufferLength; switch (predictor) { case 0: for (var i = 0; i < rowBytes; ++i) - currentRow[i] = rawBytes[i]; + buffer[j++] = rawBytes[i]; break; case 1: for (var i = 0; i < pixBytes; ++i) - currentRow[i] = rawBytes[i]; - for (; i < rowBytes; ++i) - currentRow[i] = (currentRow[i - pixBytes] + rawBytes[i]) & 0xFF; + buffer[j++] = rawBytes[i]; + for (; i < rowBytes; ++i) { + buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF; + j++; + } break; case 2: for (var i = 0; i < rowBytes; ++i) - currentRow[i] = (prevRow[i] + rawBytes[i]) & 0xFF; + buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF; break; case 3: for (var i = 0; i < pixBytes; ++i) - currentRow[i] = (prevRow[i] >> 1) + rawBytes[i]; + buffer[j++] = (prevRow[i] >> 1) + rawBytes[i]; for (; i < rowBytes; ++i) { - currentRow[i] = (((prevRow[i] + currentRow[i - pixBytes]) >> 1) + + buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) + rawBytes[i]) & 0xFF; + j++; } break; case 4: @@ -24524,12 +27252,12 @@ var PredictorStream = (function predictorStream() { for (var i = 0; i < pixBytes; ++i) { var up = prevRow[i]; var c = rawBytes[i]; - currentRow[i] = up + c; + buffer[j++] = up + c; } for (; i < rowBytes; ++i) { var up = prevRow[i]; var upLeft = prevRow[i - pixBytes]; - var left = currentRow[i - pixBytes]; + var left = buffer[j - pixBytes]; var p = left + up - upLeft; var pa = p - left; @@ -24544,11 +27272,11 @@ var PredictorStream = (function predictorStream() { var c = rawBytes[i]; if (pa <= pb && pa <= pc) - currentRow[i] = left + c; + buffer[j++] = left + c; else if (pb <= pc) - currentRow[i] = up + c; + buffer[j++] = up + c; else - currentRow[i] = upLeft + c; + buffer[j++] = upLeft + c; } break; default: @@ -24557,7 +27285,7 @@ var PredictorStream = (function predictorStream() { this.bufferLength += rowBytes; }; - return constructor; + return PredictorStream; })(); /** @@ -24567,7 +27295,7 @@ var PredictorStream = (function predictorStream() { * a library to decode these images and the stream behaves like all the other * DecodeStreams. */ -var JpegStream = (function jpegStream() { +var JpegStream = (function JpegStreamClosure() { function isAdobeImage(bytes) { var maxBytesScanned = Math.max(bytes.length - 16, 1024); // Looking for APP14, 'Adobe' @@ -24598,63 +27326,184 @@ var JpegStream = (function jpegStream() { return newBytes; } - function constructor(bytes, dict, xref) { + function JpegStream(bytes, dict, xref) { // TODO: per poppler, some images may have 'junk' before that // need to be removed this.dict = dict; - // Flag indicating wether the image can be natively loaded. - this.isNative = true; - - this.colorTransform = -1; + this.isAdobeImage = false; + this.colorTransform = dict.get('ColorTransform') || -1; if (isAdobeImage(bytes)) { - // when bug 674619 land, let's check if browser can do - // normal cmyk and then we won't have to the following - var cs = xref.fetchIfRef(dict.get('ColorSpace')); - - // DeviceRGB and DeviceGray are the only Adobe images that work natively - if (isName(cs) && (cs.name === 'DeviceRGB' || cs.name === 'DeviceGray')) { - bytes = fixAdobeImage(bytes); - this.src = bytesToString(bytes); - } else { - this.colorTransform = dict.get('ColorTransform'); - this.isNative = false; - this.bytes = bytes; - } - } else { - this.src = bytesToString(bytes); + this.isAdobeImage = true; + bytes = fixAdobeImage(bytes); + } + + this.bytes = bytes; + + DecodeStream.call(this); + } + + JpegStream.prototype = Object.create(DecodeStream.prototype); + + JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) { + if (this.bufferLength) + return; + try { + var jpegImage = new JpegImage(); + if (this.colorTransform != -1) + jpegImage.colorTransform = this.colorTransform; + jpegImage.parse(this.bytes); + var width = jpegImage.width; + var height = jpegImage.height; + var data = jpegImage.getData(width, height); + this.buffer = data; + this.bufferLength = data.length; + } catch (e) { + error('JPEG error: ' + e); } + }; + JpegStream.prototype.getIR = function JpegStream_getIR() { + return bytesToString(this.bytes); + }; + JpegStream.prototype.getChar = function JpegStream_getChar() { + error('internal error: getChar is not valid on JpegStream'); + }; + /** + * Checks if the image can be decoded and displayed by the browser without any + * further processing such as color space conversions. + */ + JpegStream.prototype.isNativelySupported = + function JpegStream_isNativelySupported(xref, res) { + var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res); + // when bug 674619 lands, let's check if browser can do + // normal cmyk and then we won't need to decode in JS + if (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') + return true; + if (cs.name === 'DeviceCMYK' && !this.isAdobeImage && + this.colorTransform < 1) + return true; + return false; + }; + /** + * Checks if the image can be decoded by the browser. + */ + JpegStream.prototype.isNativelyDecodable = + function JpegStream_isNativelyDecodable(xref, res) { + var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res); + var numComps = cs.numComps; + if (numComps == 1 || numComps == 3) + return true; + + return false; + }; + + return JpegStream; +})(); + +/** + * For JPEG 2000's we use a library to decode these images and + * the stream behaves like all the other DecodeStreams. + */ +var JpxStream = (function JpxStreamClosure() { + function JpxStream(bytes, dict) { + this.dict = dict; + this.bytes = bytes; DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + JpxStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) { + JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) { if (this.bufferLength) return; - var jpegImage = new JpegImage(); - jpegImage.colorTransform = this.colorTransform; - jpegImage.parse(this.bytes); - var width = jpegImage.width; - var height = jpegImage.height; - var data = jpegImage.getData(width, height); + + var jpxImage = new JpxImage(); + jpxImage.parse(this.bytes); + + var width = jpxImage.width; + var height = jpxImage.height; + var componentsCount = jpxImage.componentsCount; + if (componentsCount != 1 && componentsCount != 3 && componentsCount != 4) + error('JPX with ' + componentsCount + ' components is not supported'); + + var data = new Uint8Array(width * height * componentsCount); + + for (var k = 0, kk = jpxImage.tiles.length; k < kk; k++) { + var tileCompoments = jpxImage.tiles[k]; + var tileWidth = tileCompoments[0].width; + var tileHeight = tileCompoments[0].height; + var tileLeft = tileCompoments[0].left; + var tileTop = tileCompoments[0].top; + + var dataPosition, sourcePosition, data0, data1, data2, data3, rowFeed; + switch (componentsCount) { + case 1: + data0 = tileCompoments[0].items; + + dataPosition = width * tileTop + tileLeft; + rowFeed = width - tileWidth; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) + data[dataPosition++] = data0[sourcePosition++]; + dataPosition += rowFeed; + } + break; + case 3: + data0 = tileCompoments[0].items; + data1 = tileCompoments[1].items; + data2 = tileCompoments[2].items; + + dataPosition = (width * tileTop + tileLeft) * 3; + rowFeed = (width - tileWidth) * 3; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) { + data[dataPosition++] = data0[sourcePosition]; + data[dataPosition++] = data1[sourcePosition]; + data[dataPosition++] = data2[sourcePosition]; + sourcePosition++; + } + dataPosition += rowFeed; + } + break; + case 4: + data0 = tileCompoments[0].items; + data1 = tileCompoments[1].items; + data2 = tileCompoments[2].items; + data3 = tileCompoments[3].items; + + dataPosition = (width * tileTop + tileLeft) * 4; + rowFeed = (width - tileWidth) * 4; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) { + data[dataPosition++] = data0[sourcePosition]; + data[dataPosition++] = data1[sourcePosition]; + data[dataPosition++] = data2[sourcePosition]; + data[dataPosition++] = data3[sourcePosition]; + sourcePosition++; + } + dataPosition += rowFeed; + } + break; + } + } + this.buffer = data; this.bufferLength = data.length; }; - constructor.prototype.getIR = function jpegStreamGetIR() { - return this.src; - }; - constructor.prototype.getChar = function jpegStreamGetChar() { - error('internal error: getChar is not valid on JpegStream'); + JpxStream.prototype.getChar = function JpxStream_getChar() { + error('internal error: getChar is not valid on JpxStream'); }; - return constructor; + return JpxStream; })(); -var DecryptStream = (function decryptStream() { - function constructor(str, decrypt) { +var DecryptStream = (function DecryptStreamClosure() { + function DecryptStream(str, decrypt) { this.str = str; this.dict = str.dict; this.decrypt = decrypt; @@ -24664,9 +27513,9 @@ var DecryptStream = (function decryptStream() { var chunkSize = 512; - constructor.prototype = Object.create(DecodeStream.prototype); + DecryptStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function decryptStreamReadBlock() { + DecryptStream.prototype.readBlock = function DecryptStream_readBlock() { var chunk = this.str.getBytes(chunkSize); if (!chunk || chunk.length == 0) { this.eof = true; @@ -24683,11 +27532,11 @@ var DecryptStream = (function decryptStream() { this.bufferLength = bufferLength; }; - return constructor; + return DecryptStream; })(); -var Ascii85Stream = (function ascii85Stream() { - function constructor(str) { +var Ascii85Stream = (function Ascii85StreamClosure() { + function Ascii85Stream(str) { this.str = str; this.dict = str.dict; this.input = new Uint8Array(5); @@ -24695,9 +27544,9 @@ var Ascii85Stream = (function ascii85Stream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + Ascii85Stream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function ascii85StreamReadBlock() { + Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() { var tildaCode = '~'.charCodeAt(0); var zCode = 'z'.charCodeAt(0); var str = this.str; @@ -24752,11 +27601,11 @@ var Ascii85Stream = (function ascii85Stream() { } }; - return constructor; + return Ascii85Stream; })(); -var AsciiHexStream = (function asciiHexStream() { - function constructor(str) { +var AsciiHexStream = (function AsciiHexStreamClosure() { + function AsciiHexStream(str) { this.str = str; this.dict = str.dict; @@ -24790,9 +27639,9 @@ var AsciiHexStream = (function asciiHexStream() { 102: 15 }; - constructor.prototype = Object.create(DecodeStream.prototype); + AsciiHexStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function asciiHexStreamReadBlock() { + AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() { var gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n, decodeLength, buffer, bufferLength, i, length; @@ -24822,10 +27671,55 @@ var AsciiHexStream = (function asciiHexStream() { this.eof = true; }; - return constructor; + return AsciiHexStream; +})(); + +var RunLengthStream = (function RunLengthStreamClosure() { + function RunLengthStream(str) { + this.str = str; + this.dict = str.dict; + + DecodeStream.call(this); + } + + RunLengthStream.prototype = Object.create(DecodeStream.prototype); + + RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() { + // The repeatHeader has following format. The first byte defines type of run + // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes + // (in addition to the second byte from the header), n = 129 through 255 - + // duplicate the second byte from the header (257 - n) times, n = 128 - end. + var repeatHeader = this.str.getBytes(2); + if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] == 128) { + this.eof = true; + return; + } + + var bufferLength = this.bufferLength; + var n = repeatHeader[0]; + if (n < 128) { + // copy n bytes + var buffer = this.ensureBuffer(bufferLength + n + 1); + buffer[bufferLength++] = repeatHeader[1]; + if (n > 0) { + var source = this.str.getBytes(n); + buffer.set(source, bufferLength); + bufferLength += n; + } + } else { + n = 257 - n; + var b = repeatHeader[1]; + var buffer = this.ensureBuffer(bufferLength + n + 1); + for (var i = 0; i < n; i++) + buffer[bufferLength++] = b; + } + this.bufferLength = bufferLength; + }; + + return RunLengthStream; })(); -var CCITTFaxStream = (function ccittFaxStream() { +var CCITTFaxStream = (function CCITTFaxStreamClosure() { var ccittEOL = -2; var twoDimPass = 0; @@ -25253,1770 +28147,4144 @@ var CCITTFaxStream = (function ccittFaxStream() { [2, 2], [2, 2], [2, 2], [2, 2] ]; - function constructor(str, params) { - this.str = str; - this.dict = str.dict; + function CCITTFaxStream(str, params) { + this.str = str; + this.dict = str.dict; + + params = params || new Dict(); + + this.encoding = params.get('K') || 0; + this.eoline = params.get('EndOfLine') || false; + this.byteAlign = params.get('EncodedByteAlign') || false; + this.columns = params.get('Columns') || 1728; + this.rows = params.get('Rows') || 0; + var eoblock = params.get('EndOfBlock'); + if (eoblock == null) + eoblock = true; + this.eoblock = eoblock; + this.black = params.get('BlackIs1') || false; + + this.codingLine = new Uint32Array(this.columns + 1); + this.refLine = new Uint32Array(this.columns + 2); + + this.codingLine[0] = this.columns; + this.codingPos = 0; + + this.row = 0; + this.nextLine2D = this.encoding < 0; + this.inputBits = 0; + this.inputBuf = 0; + this.outputBits = 0; + this.buf = EOF; + + var code1; + while ((code1 = this.lookBits(12)) == 0) { + this.eatBits(1); + } + if (code1 == 1) { + this.eatBits(12); + } + if (this.encoding > 0) { + this.nextLine2D = !this.lookBits(1); + this.eatBits(1); + } + + DecodeStream.call(this); + } + + CCITTFaxStream.prototype = Object.create(DecodeStream.prototype); + + CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() { + while (!this.eof) { + var c = this.lookChar(); + this.buf = EOF; + this.ensureBuffer(this.bufferLength + 1); + this.buffer[this.bufferLength++] = c; + } + }; + + CCITTFaxStream.prototype.addPixels = + function ccittFaxStreamAddPixels(a1, blackPixels) { + var codingLine = this.codingLine; + var codingPos = this.codingPos; + + if (a1 > codingLine[codingPos]) { + if (a1 > this.columns) { + warn('row is wrong length'); + this.err = true; + a1 = this.columns; + } + if ((codingPos & 1) ^ blackPixels) { + ++codingPos; + } + + codingLine[codingPos] = a1; + } + this.codingPos = codingPos; + }; + + CCITTFaxStream.prototype.addPixelsNeg = + function ccittFaxStreamAddPixelsNeg(a1, blackPixels) { + var codingLine = this.codingLine; + var codingPos = this.codingPos; + + if (a1 > codingLine[codingPos]) { + if (a1 > this.columns) { + warn('row is wrong length'); + this.err = true; + a1 = this.columns; + } + if ((codingPos & 1) ^ blackPixels) + ++codingPos; + + codingLine[codingPos] = a1; + } else if (a1 < codingLine[codingPos]) { + if (a1 < 0) { + warn('invalid code'); + this.err = true; + a1 = 0; + } + while (codingPos > 0 && a1 < codingLine[codingPos - 1]) + --codingPos; + codingLine[codingPos] = a1; + } + + this.codingPos = codingPos; + }; + + CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() { + if (this.buf != EOF) + return this.buf; + + var refLine = this.refLine; + var codingLine = this.codingLine; + var columns = this.columns; + + var refPos, blackPixels, bits; + + if (this.outputBits == 0) { + if (this.eof) + return null; + + this.err = false; + + var code1, code2, code3; + if (this.nextLine2D) { + for (var i = 0; codingLine[i] < columns; ++i) + refLine[i] = codingLine[i]; + + refLine[i++] = columns; + refLine[i] = columns; + codingLine[0] = 0; + this.codingPos = 0; + refPos = 0; + blackPixels = 0; + + while (codingLine[this.codingPos] < columns) { + code1 = this.getTwoDimCode(); + switch (code1) { + case twoDimPass: + this.addPixels(refLine[refPos + 1], blackPixels); + if (refLine[refPos + 1] < columns) + refPos += 2; + break; + case twoDimHoriz: + code1 = code2 = 0; + if (blackPixels) { + do { + code1 += (code3 = this.getBlackCode()); + } while (code3 >= 64); + do { + code2 += (code3 = this.getWhiteCode()); + } while (code3 >= 64); + } else { + do { + code1 += (code3 = this.getWhiteCode()); + } while (code3 >= 64); + do { + code2 += (code3 = this.getBlackCode()); + } while (code3 >= 64); + } + this.addPixels(codingLine[this.codingPos] + + code1, blackPixels); + if (codingLine[this.codingPos] < columns) { + this.addPixels(codingLine[this.codingPos] + code2, + blackPixels ^ 1); + } + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) { + refPos += 2; + } + break; + case twoDimVertR3: + this.addPixels(refLine[refPos] + 3, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case twoDimVertR2: + this.addPixels(refLine[refPos] + 2, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) { + refPos += 2; + } + } + break; + case twoDimVertR1: + this.addPixels(refLine[refPos] + 1, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case twoDimVert0: + this.addPixels(refLine[refPos], blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case twoDimVertL3: + this.addPixelsNeg(refLine[refPos] - 3, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + if (refPos > 0) + --refPos; + else + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case twoDimVertL2: + this.addPixelsNeg(refLine[refPos] - 2, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + if (refPos > 0) + --refPos; + else + ++refPos; + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case twoDimVertL1: + this.addPixelsNeg(refLine[refPos] - 1, blackPixels); + blackPixels ^= 1; + if (codingLine[this.codingPos] < columns) { + if (refPos > 0) + --refPos; + else + ++refPos; + + while (refLine[refPos] <= codingLine[this.codingPos] && + refLine[refPos] < columns) + refPos += 2; + } + break; + case EOF: + this.addPixels(columns, 0); + this.eof = true; + break; + default: + warn('bad 2d code'); + this.addPixels(columns, 0); + this.err = true; + } + } + } else { + codingLine[0] = 0; + this.codingPos = 0; + blackPixels = 0; + while (codingLine[this.codingPos] < columns) { + code1 = 0; + if (blackPixels) { + do { + code1 += (code3 = this.getBlackCode()); + } while (code3 >= 64); + } else { + do { + code1 += (code3 = this.getWhiteCode()); + } while (code3 >= 64); + } + this.addPixels(codingLine[this.codingPos] + code1, blackPixels); + blackPixels ^= 1; + } + } + + if (this.byteAlign) + this.inputBits &= ~7; + + var gotEOL = false; + + if (!this.eoblock && this.row == this.rows - 1) { + this.eof = true; + } else { + code1 = this.lookBits(12); + while (code1 == 0) { + this.eatBits(1); + code1 = this.lookBits(12); + } + if (code1 == 1) { + this.eatBits(12); + gotEOL = true; + } else if (code1 == EOF) { + this.eof = true; + } + } + + if (!this.eof && this.encoding > 0) { + this.nextLine2D = !this.lookBits(1); + this.eatBits(1); + } + + if (this.eoblock && gotEOL) { + code1 = this.lookBits(12); + if (code1 == 1) { + this.eatBits(12); + if (this.encoding > 0) { + this.lookBits(1); + this.eatBits(1); + } + if (this.encoding >= 0) { + for (var i = 0; i < 4; ++i) { + code1 = this.lookBits(12); + if (code1 != 1) + warn('bad rtc code: ' + code1); + this.eatBits(12); + if (this.encoding > 0) { + this.lookBits(1); + this.eatBits(1); + } + } + } + this.eof = true; + } + } else if (this.err && this.eoline) { + while (true) { + code1 = this.lookBits(13); + if (code1 == EOF) { + this.eof = true; + return null; + } + if ((code1 >> 1) == 1) { + break; + } + this.eatBits(1); + } + this.eatBits(12); + if (this.encoding > 0) { + this.eatBits(1); + this.nextLine2D = !(code1 & 1); + } + } + + if (codingLine[0] > 0) + this.outputBits = codingLine[this.codingPos = 0]; + else + this.outputBits = codingLine[this.codingPos = 1]; + this.row++; + } + + if (this.outputBits >= 8) { + this.buf = (this.codingPos & 1) ? 0 : 0xFF; + this.outputBits -= 8; + if (this.outputBits == 0 && codingLine[this.codingPos] < columns) { + this.codingPos++; + this.outputBits = (codingLine[this.codingPos] - + codingLine[this.codingPos - 1]); + } + } else { + var bits = 8; + this.buf = 0; + do { + if (this.outputBits > bits) { + this.buf <<= bits; + if (!(this.codingPos & 1)) { + this.buf |= 0xFF >> (8 - bits); + } + this.outputBits -= bits; + bits = 0; + } else { + this.buf <<= this.outputBits; + if (!(this.codingPos & 1)) { + this.buf |= 0xFF >> (8 - this.outputBits); + } + bits -= this.outputBits; + this.outputBits = 0; + if (codingLine[this.codingPos] < columns) { + this.codingPos++; + this.outputBits = (codingLine[this.codingPos] - + codingLine[this.codingPos - 1]); + } else if (bits > 0) { + this.buf <<= bits; + bits = 0; + } + } + } while (bits); + } + if (this.black) { + this.buf ^= 0xFF; + } + return this.buf; + }; + + // This functions returns the code found from the table. + // The start and end parameters set the boundaries for searching the table. + // The limit parameter is optional. Function returns an array with three + // values. The first array element indicates whether a valid code is being + // returned. The second array element is the actual code. The third array + // element indicates whether EOF was reached. + CCITTFaxStream.prototype.findTableCode = + function ccittFaxStreamFindTableCode(start, end, table, limit) { + + var limitValue = limit || 0; + for (var i = start; i <= end; ++i) { + var code = this.lookBits(i); + if (code == EOF) + return [true, 1, false]; + if (i < end) + code <<= end - i; + if (!limitValue || code >= limitValue) { + var p = table[code - limitValue]; + if (p[0] == i) { + this.eatBits(i); + return [true, p[1], true]; + } + } + } + return [false, 0, false]; + }; + + CCITTFaxStream.prototype.getTwoDimCode = + function ccittFaxStreamGetTwoDimCode() { + + var code = 0; + var p; + if (this.eoblock) { + code = this.lookBits(7); + p = twoDimTable[code]; + if (p && p[0] > 0) { + this.eatBits(p[0]); + return p[1]; + } + } else { + var result = this.findTableCode(1, 7, twoDimTable); + if (result[0] && result[2]) + return result[1]; + } + warn('Bad two dim code'); + return EOF; + }; + + CCITTFaxStream.prototype.getWhiteCode = + function ccittFaxStreamGetWhiteCode() { + + var code = 0; + var p; + var n; + if (this.eoblock) { + code = this.lookBits(12); + if (code == EOF) + return 1; + + if ((code >> 5) == 0) + p = whiteTable1[code]; + else + p = whiteTable2[code >> 3]; + + if (p[0] > 0) { + this.eatBits(p[0]); + return p[1]; + } + } else { + var result = this.findTableCode(1, 9, whiteTable2); + if (result[0]) + return result[1]; + + result = this.findTableCode(11, 12, whiteTable1); + if (result[0]) + return result[1]; + } + warn('bad white code'); + this.eatBits(1); + return 1; + }; + + CCITTFaxStream.prototype.getBlackCode = + function ccittFaxStreamGetBlackCode() { + + var code, p; + if (this.eoblock) { + code = this.lookBits(13); + if (code == EOF) + return 1; + if ((code >> 7) == 0) + p = blackTable1[code]; + else if ((code >> 9) == 0 && (code >> 7) != 0) + p = blackTable2[(code >> 1) - 64]; + else + p = blackTable3[code >> 7]; + + if (p[0] > 0) { + this.eatBits(p[0]); + return p[1]; + } + } else { + var result = this.findTableCode(2, 6, blackTable3); + if (result[0]) + return result[1]; + + result = this.findTableCode(7, 12, blackTable2, 64); + if (result[0]) + return result[1]; + + result = this.findTableCode(10, 13, blackTable1); + if (result[0]) + return result[1]; + } + warn('bad black code'); + this.eatBits(1); + return 1; + }; + + CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) { + var c; + while (this.inputBits < n) { + if ((c = this.str.getByte()) == null) { + if (this.inputBits == 0) + return EOF; + return ((this.inputBuf << (n - this.inputBits)) & + (0xFFFF >> (16 - n))); + } + this.inputBuf = (this.inputBuf << 8) + c; + this.inputBits += 8; + } + return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n)); + }; + + CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) { + if ((this.inputBits -= n) < 0) + this.inputBits = 0; + }; + + return CCITTFaxStream; +})(); + +var LZWStream = (function LZWStreamClosure() { + function LZWStream(str, earlyChange) { + this.str = str; + this.dict = str.dict; + this.cachedData = 0; + this.bitsCached = 0; + + var maxLzwDictionarySize = 4096; + var lzwState = { + earlyChange: earlyChange, + codeLength: 9, + nextCode: 258, + dictionaryValues: new Uint8Array(maxLzwDictionarySize), + dictionaryLengths: new Uint16Array(maxLzwDictionarySize), + dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize), + currentSequence: new Uint8Array(maxLzwDictionarySize), + currentSequenceLength: 0 + }; + for (var i = 0; i < 256; ++i) { + lzwState.dictionaryValues[i] = i; + lzwState.dictionaryLengths[i] = 1; + } + this.lzwState = lzwState; + + DecodeStream.call(this); + } + + LZWStream.prototype = Object.create(DecodeStream.prototype); + + LZWStream.prototype.readBits = function LZWStream_readBits(n) { + var bitsCached = this.bitsCached; + var cachedData = this.cachedData; + while (bitsCached < n) { + var c = this.str.getByte(); + if (c == null) { + this.eof = true; + return null; + } + cachedData = (cachedData << 8) | c; + bitsCached += 8; + } + this.bitsCached = (bitsCached -= n); + this.cachedData = cachedData; + this.lastCode = null; + return (cachedData >>> bitsCached) & ((1 << n) - 1); + }; + + LZWStream.prototype.readBlock = function LZWStream_readBlock() { + var blockSize = 512; + var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize; + var i, j, q; + + var lzwState = this.lzwState; + if (!lzwState) + return; // eof was found + + var earlyChange = lzwState.earlyChange; + var nextCode = lzwState.nextCode; + var dictionaryValues = lzwState.dictionaryValues; + var dictionaryLengths = lzwState.dictionaryLengths; + var dictionaryPrevCodes = lzwState.dictionaryPrevCodes; + var codeLength = lzwState.codeLength; + var prevCode = lzwState.prevCode; + var currentSequence = lzwState.currentSequence; + var currentSequenceLength = lzwState.currentSequenceLength; + + var decodedLength = 0; + var currentBufferLength = this.bufferLength; + var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + + for (i = 0; i < blockSize; i++) { + var code = this.readBits(codeLength); + var hasPrev = currentSequenceLength > 0; + if (code < 256) { + currentSequence[0] = code; + currentSequenceLength = 1; + } else if (code >= 258) { + if (code < nextCode) { + currentSequenceLength = dictionaryLengths[code]; + for (j = currentSequenceLength - 1, q = code; j >= 0; j--) { + currentSequence[j] = dictionaryValues[q]; + q = dictionaryPrevCodes[q]; + } + } else { + currentSequence[currentSequenceLength++] = currentSequence[0]; + } + } else if (code == 256) { + codeLength = 9; + nextCode = 258; + currentSequenceLength = 0; + continue; + } else { + this.eof = true; + delete this.lzwState; + break; + } + + if (hasPrev) { + dictionaryPrevCodes[nextCode] = prevCode; + dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1; + dictionaryValues[nextCode] = currentSequence[0]; + nextCode++; + codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ? + codeLength : Math.min(Math.log(nextCode + earlyChange) / + 0.6931471805599453 + 1, 12) | 0; + } + prevCode = code; + + decodedLength += currentSequenceLength; + if (estimatedDecodedSize < decodedLength) { + do { + estimatedDecodedSize += decodedSizeDelta; + } while (estimatedDecodedSize < decodedLength); + buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + } + for (j = 0; j < currentSequenceLength; j++) + buffer[currentBufferLength++] = currentSequence[j]; + } + lzwState.nextCode = nextCode; + lzwState.codeLength = codeLength; + lzwState.prevCode = prevCode; + lzwState.currentSequenceLength = currentSequenceLength; - params = params || new Dict(); + this.bufferLength = currentBufferLength; + }; - this.encoding = params.get('K') || 0; - this.eoline = params.get('EndOfLine') || false; - this.byteAlign = params.get('EncodedByteAlign') || false; - this.columns = params.get('Columns') || 1728; - this.rows = params.get('Rows') || 0; - var eoblock = params.get('EndOfBlock'); - if (eoblock == null) - eoblock = true; - this.eoblock = eoblock; - this.black = params.get('BlackIs1') || false; + return LZWStream; +})(); - this.codingLine = new Uint32Array(this.columns + 1); - this.refLine = new Uint32Array(this.columns + 2); +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ - this.codingLine[0] = this.columns; - this.codingPos = 0; +'use strict'; - this.row = 0; - this.nextLine2D = this.encoding < 0; - this.inputBits = 0; - this.inputBuf = 0; - this.outputBits = 0; - this.buf = EOF; +function MessageHandler(name, comObj) { + this.name = name; + this.comObj = comObj; + this.callbackIndex = 1; + var callbacks = this.callbacks = {}; + var ah = this.actionHandler = {}; - var code1; - while ((code1 = this.lookBits(12)) == 0) { - this.eatBits(1); + ah['console_log'] = [function ahConsoleLog(data) { + console.log.apply(console, data); + }]; + ah['console_error'] = [function ahConsoleError(data) { + console.error.apply(console, data); + }]; + + comObj.onmessage = function messageHandlerComObjOnMessage(event) { + var data = event.data; + if (data.isReply) { + var callbackId = data.callbackId; + if (data.callbackId in callbacks) { + var callback = callbacks[callbackId]; + delete callbacks[callbackId]; + callback(data.data); + } else { + error('Cannot resolve callback ' + callbackId); + } + } else if (data.action in ah) { + var action = ah[data.action]; + if (data.callbackId) { + var promise = new Promise(); + promise.then(function(resolvedData) { + comObj.postMessage({ + isReply: true, + callbackId: data.callbackId, + data: resolvedData + }); + }); + action[0].call(action[1], data.data, promise); + } else { + action[0].call(action[1], data.data); + } + } else { + error('Unkown action from worker: ' + data.action); } - if (code1 == 1) { - this.eatBits(12); + }; +} + +MessageHandler.prototype = { + on: function messageHandlerOn(actionName, handler, scope) { + var ah = this.actionHandler; + if (ah[actionName]) { + error('There is already an actionName called "' + actionName + '"'); } - if (this.encoding > 0) { - this.nextLine2D = !this.lookBits(1); - this.eatBits(1); + ah[actionName] = [handler, scope]; + }, + /** + * Sends a message to the comObj to invoke the action with the supplied data. + * @param {String} actionName Action to call. + * @param {JSON} data JSON data to send. + * @param {function} [callback] Optional callback that will handle a reply. + */ + send: function messageHandlerSend(actionName, data, callback) { + var message = { + action: actionName, + data: data + }; + if (callback) { + var callbackId = this.callbackIndex++; + this.callbacks[callbackId] = callback; + message.callbackId = callbackId; } - - DecodeStream.call(this); + this.comObj.postMessage(message); } +}; - constructor.prototype = Object.create(DecodeStream.prototype); +var WorkerMessageHandler = { + setup: function wphSetup(handler) { + var pdfModel = null; - constructor.prototype.readBlock = function ccittFaxStreamReadBlock() { - while (!this.eof) { - var c = this.lookChar(); - this.buf = EOF; - this.ensureBuffer(this.bufferLength + 1); - this.buffer[this.bufferLength++] = c; - } - }; + handler.on('test', function wphSetupTest(data) { + handler.send('test', data instanceof Uint8Array); + }); - constructor.prototype.addPixels = - function ccittFaxStreamAddPixels(a1, blackPixels) { - var codingLine = this.codingLine; - var codingPos = this.codingPos; + handler.on('doc', function wphSetupDoc(data) { + // Create only the model of the PDFDoc, which is enough for + // processing the content of the pdf. + pdfModel = new PDFDocModel(new Stream(data)); + }); - if (a1 > codingLine[codingPos]) { - if (a1 > this.columns) { - warn('row is wrong length'); - this.err = true; - a1 = this.columns; - } - if ((codingPos & 1) ^ blackPixels) { - ++codingPos; - } + handler.on('page_request', function wphSetupPageRequest(pageNum) { + pageNum = parseInt(pageNum); - codingLine[codingPos] = a1; - } - this.codingPos = codingPos; - }; - constructor.prototype.addPixelsNeg = - function ccittFaxStreamAddPixelsNeg(a1, blackPixels) { - var codingLine = this.codingLine; - var codingPos = this.codingPos; + // The following code does quite the same as + // Page.prototype.startRendering, but stops at one point and sends the + // result back to the main thread. + var gfx = new CanvasGraphics(null); - if (a1 > codingLine[codingPos]) { - if (a1 > this.columns) { - warn('row is wrong length'); - this.err = true; - a1 = this.columns; + var start = Date.now(); + + var dependency = []; + var operatorList = null; + try { + var page = pdfModel.getPage(pageNum); + // Pre compile the pdf page and fetch the fonts/images. + operatorList = page.getOperatorList(handler, dependency); + } catch (e) { + var minimumStackMessage = + 'worker.js: while trying to getPage() and getOperatorList()'; + + // Turn the error into an obj that can be serialized + if (typeof e === 'string') { + e = { + message: e, + stack: minimumStackMessage + }; + } else if (typeof e === 'object') { + e = { + message: e.message || e.toString(), + stack: e.stack || minimumStackMessage + }; + } else { + e = { + message: 'Unknown exception type: ' + (typeof e), + stack: minimumStackMessage + }; + } + + handler.send('page_error', { + pageNum: pageNum, + error: e + }); + return; } - if ((codingPos & 1) ^ blackPixels) - ++codingPos; - codingLine[codingPos] = a1; - } else if (a1 < codingLine[codingPos]) { - if (a1 < 0) { - warn('invalid code'); - this.err = true; - a1 = 0; + console.log('page=%d - getOperatorList: time=%dms, len=%d', pageNum, + Date.now() - start, operatorList.fnArray.length); + + // Filter the dependecies for fonts. + var fonts = {}; + for (var i = 0, ii = dependency.length; i < ii; i++) { + var dep = dependency[i]; + if (dep.indexOf('font_') == 0) { + fonts[dep] = true; + } } - while (codingPos > 0 && a1 < codingLine[codingPos - 1]) - --codingPos; - codingLine[codingPos] = a1; - } - this.codingPos = codingPos; - }; + handler.send('page', { + pageNum: pageNum, + operatorList: operatorList, + depFonts: Object.keys(fonts) + }); + }, this); + } +}; - constructor.prototype.lookChar = function ccittFaxStreamLookChar() { - if (this.buf != EOF) - return this.buf; +var consoleTimer = {}; - var refLine = this.refLine; - var codingLine = this.codingLine; - var columns = this.columns; +var workerConsole = { + log: function log() { + var args = Array.prototype.slice.call(arguments); + postMessage({ + action: 'console_log', + data: args + }); + }, - var refPos, blackPixels, bits; + error: function error() { + var args = Array.prototype.slice.call(arguments); + postMessage({ + action: 'console_error', + data: args + }); + throw 'pdf.js execution error'; + }, - if (this.outputBits == 0) { - if (this.eof) - return null; + time: function time(name) { + consoleTimer[name] = Date.now(); + }, - this.err = false; + timeEnd: function timeEnd(name) { + var time = consoleTimer[name]; + if (time == null) { + error('Unkown timer name ' + name); + } + this.log('Timer:', name, Date.now() - time); + } +}; - var code1, code2, code3; - if (this.nextLine2D) { - for (var i = 0; codingLine[i] < columns; ++i) - refLine[i] = codingLine[i]; +// Worker thread? +if (typeof window === 'undefined') { + globalScope.console = workerConsole; + + var handler = new MessageHandler('worker_processor', this); + WorkerMessageHandler.setup(handler); +} + +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +// - The JPEG specification can be found in the ITU CCITT Recommendation T.81 +// (www.w3.org/Graphics/JPEG/itu-t81.pdf) +// - The JFIF specification can be found in the JPEG File Interchange Format +// (www.w3.org/Graphics/JPEG/jfif3.pdf) +// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters +// in PostScript Level 2, Technical Note #5116 +// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf) + +var JpegImage = (function jpegImage() { + "use strict"; + var dctZigZag = new Int32Array([ + 0, + 1, 8, + 16, 9, 2, + 3, 10, 17, 24, + 32, 25, 18, 11, 4, + 5, 12, 19, 26, 33, 40, + 48, 41, 34, 27, 20, 13, 6, + 7, 14, 21, 28, 35, 42, 49, 56, + 57, 50, 43, 36, 29, 22, 15, + 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, + 39, 46, 53, 60, + 61, 54, 47, + 55, 62, + 63 + ]); - refLine[i++] = columns; - refLine[i] = columns; - codingLine[0] = 0; - this.codingPos = 0; - refPos = 0; - blackPixels = 0; + var dctCos1 = 4017 // cos(pi/16) + var dctSin1 = 799 // sin(pi/16) + var dctCos3 = 3406 // cos(3*pi/16) + var dctSin3 = 2276 // sin(3*pi/16) + var dctCos6 = 1567 // cos(6*pi/16) + var dctSin6 = 3784 // sin(6*pi/16) + var dctSqrt2 = 5793 // sqrt(2) + var dctSqrt1d2 = 2896 // sqrt(2) / 2 - while (codingLine[this.codingPos] < columns) { - code1 = this.getTwoDimCode(); - switch (code1) { - case twoDimPass: - this.addPixels(refLine[refPos + 1], blackPixels); - if (refLine[refPos + 1] < columns) - refPos += 2; - break; - case twoDimHoriz: - code1 = code2 = 0; - if (blackPixels) { - do { - code1 += (code3 = this.getBlackCode()); - } while (code3 >= 64); - do { - code2 += (code3 = this.getWhiteCode()); - } while (code3 >= 64); - } else { - do { - code1 += (code3 = this.getWhiteCode()); - } while (code3 >= 64); - do { - code2 += (code3 = this.getBlackCode()); - } while (code3 >= 64); - } - this.addPixels(codingLine[this.codingPos] + - code1, blackPixels); - if (codingLine[this.codingPos] < columns) { - this.addPixels(codingLine[this.codingPos] + code2, - blackPixels ^ 1); - } - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) { - refPos += 2; - } - break; - case twoDimVertR3: - this.addPixels(refLine[refPos] + 3, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case twoDimVertR2: - this.addPixels(refLine[refPos] + 2, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) { - refPos += 2; - } - } - break; - case twoDimVertR1: - this.addPixels(refLine[refPos] + 1, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case twoDimVert0: - this.addPixels(refLine[refPos], blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case twoDimVertL3: - this.addPixelsNeg(refLine[refPos] - 3, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - if (refPos > 0) - --refPos; - else - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case twoDimVertL2: - this.addPixelsNeg(refLine[refPos] - 2, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - if (refPos > 0) - --refPos; - else - ++refPos; - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case twoDimVertL1: - this.addPixelsNeg(refLine[refPos] - 1, blackPixels); - blackPixels ^= 1; - if (codingLine[this.codingPos] < columns) { - if (refPos > 0) - --refPos; - else - ++refPos; + function constructor() { + } - while (refLine[refPos] <= codingLine[this.codingPos] && - refLine[refPos] < columns) - refPos += 2; - } - break; - case EOF: - this.addPixels(columns, 0); - this.eof = true; - break; - default: - warn('bad 2d code'); - this.addPixels(columns, 0); - this.err = true; - } + function buildHuffmanTable(codeLengths, values) { + var k = 0, code = [], i, j, length = 16; + while (length > 0 && !codeLengths[length - 1]) + length--; + code.push({children: [], index: 0}); + var p = code[0], q; + for (i = 0; i < length; i++) { + for (j = 0; j < codeLengths[i]; j++) { + p = code.pop(); + p.children[p.index] = values[k]; + while (p.index > 0) { + p = code.pop(); } - } else { - codingLine[0] = 0; - this.codingPos = 0; - blackPixels = 0; - while (codingLine[this.codingPos] < columns) { - code1 = 0; - if (blackPixels) { - do { - code1 += (code3 = this.getBlackCode()); - } while (code3 >= 64); - } else { - do { - code1 += (code3 = this.getWhiteCode()); - } while (code3 >= 64); - } - this.addPixels(codingLine[this.codingPos] + code1, blackPixels); - blackPixels ^= 1; + p.index++; + code.push(p); + while (code.length <= i) { + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; } + k++; } + if (i + 1 < length) { + // p here points to last code + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; + } + } + return code[0].children; + } - if (this.byteAlign) - this.inputBits &= ~7; - - var gotEOL = false; + function decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successivePrev, successive) { + var precision = frame.precision; + var samplesPerLine = frame.samplesPerLine; + var scanLines = frame.scanLines; + var mcusPerLine = frame.mcusPerLine; + var progressive = frame.progressive; + var maxH = frame.maxH, maxV = frame.maxV; - if (!this.eoblock && this.row == this.rows - 1) { - this.eof = true; - } else { - code1 = this.lookBits(12); - while (code1 == 0) { - this.eatBits(1); - code1 = this.lookBits(12); + var startOffset = offset, bitsData = 0, bitsCount = 0; + function readBit() { + if (bitsCount > 0) { + bitsCount--; + return (bitsData >> bitsCount) & 1; + } + bitsData = data[offset++]; + if (bitsData == 0xFF) { + var nextByte = data[offset++]; + if (nextByte) { + throw "unexpected marker: " + ((bitsData << 8) | nextByte).toString(16); } - if (code1 == 1) { - this.eatBits(12); - gotEOL = true; - } else if (code1 == EOF) { - this.eof = true; + // unstuff 0 + } + bitsCount = 7; + return bitsData >>> 7; + } + function decodeHuffman(tree) { + var node = tree, bit; + while ((bit = readBit()) !== null) { + node = node[bit]; + if (typeof node === 'number') + return node; + if (typeof node !== 'object') + throw "invalid huffman sequence"; + } + return null; + } + function receive(length) { + var n = 0; + while (length > 0) { + var bit = readBit(); + if (bit === null) return; + n = (n << 1) | bit; + length--; + } + return n; + } + function receiveAndExtend(length) { + var n = receive(length); + if (n >= 1 << (length - 1)) + return n; + return n + (-1 << length) + 1; + } + function decodeBaseline(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : receiveAndExtend(t); + zz[0]= (component.pred += diff); + var k = 1; + while (k < 64) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) + break; + k += 16; + continue; } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s); + k++; } - - if (!this.eof && this.encoding > 0) { - this.nextLine2D = !this.lookBits(1); - this.eatBits(1); + } + function decodeDCFirst(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive); + zz[0] = (component.pred += diff); + } + function decodeDCSuccessive(component, zz) { + zz[0] |= readBit() << successive; + } + var eobrun = 0; + function decodeACFirst(component, zz) { + if (eobrun > 0) { + eobrun--; + return; } - - if (this.eoblock && gotEOL) { - code1 = this.lookBits(12); - if (code1 == 1) { - this.eatBits(12); - if (this.encoding > 0) { - this.lookBits(1); - this.eatBits(1); + var k = spectralStart, e = spectralEnd; + while (k <= e) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r) - 1; + break; } - if (this.encoding >= 0) { - for (var i = 0; i < 4; ++i) { - code1 = this.lookBits(12); - if (code1 != 1) - warn('bad rtc code: ' + code1); - this.eatBits(12); - if (this.encoding > 0) { - this.lookBits(1); - this.eatBits(1); - } + k += 16; + continue; + } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s) * (1 << successive); + k++; + } + } + var successiveACState = 0, successiveACNextValue; + function decodeACSuccessive(component, zz) { + var k = spectralStart, e = spectralEnd, r = 0; + while (k <= e) { + var z = dctZigZag[k]; + switch (successiveACState) { + case 0: // initial state + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r); + successiveACState = 4; + } else { + r = 16; + successiveACState = 1; } + } else { + if (s !== 1) + throw "invalid ACn encoding"; + successiveACNextValue = receiveAndExtend(s); + successiveACState = r ? 2 : 3; } - this.eof = true; - } - } else if (this.err && this.eoline) { - while (true) { - code1 = this.lookBits(13); - if (code1 == EOF) { - this.eof = true; - return null; + continue; + case 1: // skipping r zero items + case 2: + if (zz[z]) + zz[z] += (readBit() << successive); + else { + r--; + if (r === 0) + successiveACState = successiveACState == 2 ? 3 : 0; } - if ((code1 >> 1) == 1) { - break; + break; + case 3: // set value for a zero item + if (zz[z]) + zz[z] += (readBit() << successive); + else { + zz[z] = successiveACNextValue << successive; + successiveACState = 0; } - this.eatBits(1); - } - this.eatBits(12); - if (this.encoding > 0) { - this.eatBits(1); - this.nextLine2D = !(code1 & 1); + break; + case 4: // eob + if (zz[z]) + zz[z] += (readBit() << successive); + break; } + k++; + } + if (successiveACState === 4) { + eobrun--; + if (eobrun === 0) + successiveACState = 0; } + } + function decodeMcu(component, decode, mcu, row, col) { + var mcuRow = (mcu / mcusPerLine) | 0; + var mcuCol = mcu % mcusPerLine; + var blockRow = mcuRow * component.v + row; + var blockCol = mcuCol * component.h + col; + decode(component, component.blocks[blockRow][blockCol]); + } + function decodeBlock(component, decode, mcu) { + var blockRow = (mcu / component.blocksPerLine) | 0; + var blockCol = mcu % component.blocksPerLine; + decode(component, component.blocks[blockRow][blockCol]); + } - if (codingLine[0] > 0) - this.outputBits = codingLine[this.codingPos = 0]; + var componentsLength = components.length; + var component, i, j, k, n; + var decodeFn; + if (progressive) { + if (spectralStart === 0) + decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; else - this.outputBits = codingLine[this.codingPos = 1]; - this.row++; + decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; + } else { + decodeFn = decodeBaseline; } - if (this.outputBits >= 8) { - this.buf = (this.codingPos & 1) ? 0 : 0xFF; - this.outputBits -= 8; - if (this.outputBits == 0 && codingLine[this.codingPos] < columns) { - this.codingPos++; - this.outputBits = (codingLine[this.codingPos] - - codingLine[this.codingPos - 1]); - } + var mcu = 0, marker; + var mcuExpected; + if (componentsLength == 1) { + mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; } else { - var bits = 8; - this.buf = 0; - do { - if (this.outputBits > bits) { - this.buf <<= bits; - if (!(this.codingPos & 1)) { - this.buf |= 0xFF >> (8 - bits); - } - this.outputBits -= bits; - bits = 0; - } else { - this.buf <<= this.outputBits; - if (!(this.codingPos & 1)) { - this.buf |= 0xFF >> (8 - this.outputBits); - } - bits -= this.outputBits; - this.outputBits = 0; - if (codingLine[this.codingPos] < columns) { - this.codingPos++; - this.outputBits = (codingLine[this.codingPos] - - codingLine[this.codingPos - 1]); - } else if (bits > 0) { - this.buf <<= bits; - bits = 0; - } - } - } while (bits); - } - if (this.black) { - this.buf ^= 0xFF; + mcuExpected = mcusPerLine * frame.mcusPerColumn; } - return this.buf; - }; + if (!resetInterval) resetInterval = mcuExpected; - // This functions returns the code found from the table. - // The start and end parameters set the boundaries for searching the table. - // The limit parameter is optional. Function returns an array with three - // values. The first array element indicates whether a valid code is being - // returned. The second array element is the actual code. The third array - // element indicates whether EOF was reached. - var findTableCode = function ccittFaxStreamFindTableCode(start, end, table, - limit) { - var limitValue = limit || 0; + var h, v; + while (mcu < mcuExpected) { + // reset interval stuff + for (i = 0; i < componentsLength; i++) + components[i].pred = 0; + eobrun = 0; - for (var i = start; i <= end; ++i) { - var code = this.lookBits(i); - if (code == EOF) - return [true, 1, false]; - if (i < end) - code <<= end - i; - if (!limitValue || code >= limitValue) { - var p = table[code - limitValue]; - if (p[0] == i) { - this.eatBits(i); - return [true, p[1], true]; + if (componentsLength == 1) { + component = components[0]; + for (n = 0; n < resetInterval; n++) { + decodeBlock(component, decodeFn, mcu); + mcu++; + } + } else { + for (n = 0; n < resetInterval; n++) { + for (i = 0; i < componentsLength; i++) { + component = components[i]; + h = component.h; + v = component.v; + for (j = 0; j < v; j++) { + for (k = 0; k < h; k++) { + decodeMcu(component, decodeFn, mcu, j, k); + } + } + } + mcu++; } } - } - return [false, 0, false]; - }; - constructor.prototype.getTwoDimCode = function ccittFaxStreamGetTwoDimCode() { - var code = 0; - var p; - if (this.eoblock) { - code = this.lookBits(7); - p = twoDimTable[code]; - if (p[0] > 0) { - this.eatBits(p[0]); - return p[1]; + // find marker + bitsCount = 0; + marker = (data[offset] << 8) | data[offset + 1]; + if (marker <= 0xFF00) { + throw "marker was not found"; + } + + if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx + offset += 2; } - } else { - var result = findTableCode(1, 7, twoDimTable); - if (result[0] && result[2]) - return result[1]; + else + break; } - warn('Bad two dim code'); - return EOF; - }; - constructor.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() { - var code = 0; - var p; - var n; - if (this.eoblock) { - code = this.lookBits(12); - if (code == EOF) - return 1; + return offset - startOffset; + } - if ((code >> 5) == 0) - p = whiteTable1[code]; - else - p = whiteTable2[code >> 3]; + function buildComponentData(frame, component) { + var lines = []; + var blocksPerLine = component.blocksPerLine; + var blocksPerColumn = component.blocksPerColumn; + var samplesPerLine = blocksPerLine << 3; + var R = new Int32Array(64), r = new Uint8Array(64); - if (p[0] > 0) { - this.eatBits(p[0]); - return p[1]; - } - } else { - var result = findTableCode(1, 9, whiteTable2); - if (result[0]) - return result[1]; + // A port of poppler's IDCT method which in turn is taken from: + // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz, + // "Practical Fast 1-D DCT Algorithms with 11 Multiplications", + // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989, + // 988-991. + function quantizeAndInverse(zz, dataOut, dataIn) { + var qt = component.quantizationTable; + var v0, v1, v2, v3, v4, v5, v6, v7, t; + var p = dataIn; + var i; - result = findTableCode(11, 12, whiteTable1); - if (result[0]) - return result[1]; - } - warn('bad white code'); - this.eatBits(1); - return 1; - }; + // dequant + for (i = 0; i < 64; i++) + p[i] = zz[i] * qt[i]; - constructor.prototype.getBlackCode = function ccittFaxStreamGetBlackCode() { - var code, p; - if (this.eoblock) { - code = this.lookBits(13); - if (code == EOF) - return 1; - if ((code >> 7) == 0) - p = blackTable1[code]; - else if ((code >> 9) == 0 && (code >> 7) != 0) - p = blackTable2[(code >> 1) - 64]; - else - p = blackTable3[code >> 7]; + // inverse DCT on rows + for (i = 0; i < 8; ++i) { + var row = 8 * i; - if (p[0] > 0) { - this.eatBits(p[0]); - return p[1]; - } - } else { - var result = findTableCode(2, 6, blackTable3); - if (result[0]) - return result[1]; + // check for all-zero AC coefficients + if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && + p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && + p[7 + row] == 0) { + t = (dctSqrt2 * p[0 + row] + 512) >> 10; + p[0 + row] = t; + p[1 + row] = t; + p[2 + row] = t; + p[3 + row] = t; + p[4 + row] = t; + p[5 + row] = t; + p[6 + row] = t; + p[7 + row] = t; + continue; + } - result = findTableCode(7, 12, blackTable2, 64); - if (result[0]) - return result[1]; + // stage 4 + v0 = (dctSqrt2 * p[0 + row] + 128) >> 8; + v1 = (dctSqrt2 * p[4 + row] + 128) >> 8; + v2 = p[2 + row]; + v3 = p[6 + row]; + v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8; + v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8; + v5 = p[3 + row] << 4; + v6 = p[5 + row] << 4; - result = findTableCode(10, 13, blackTable1); - if (result[0]) - return result[1]; - } - warn('bad black code'); - this.eatBits(1); - return 1; - }; + // stage 3 + t = (v0 - v1+ 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; - constructor.prototype.lookBits = function ccittFaxStreamLookBits(n) { - var c; - while (this.inputBits < n) { - if ((c = this.str.getByte()) == null) { - if (this.inputBits == 0) - return EOF; - return ((this.inputBuf << (n - this.inputBits)) & - (0xFFFF >> (16 - n))); + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + // stage 1 + p[0 + row] = v0 + v7; + p[7 + row] = v0 - v7; + p[1 + row] = v1 + v6; + p[6 + row] = v1 - v6; + p[2 + row] = v2 + v5; + p[5 + row] = v2 - v5; + p[3 + row] = v3 + v4; + p[4 + row] = v3 - v4; } - this.inputBuf = (this.inputBuf << 8) + c; - this.inputBits += 8; - } - return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n)); - }; - constructor.prototype.eatBits = function ccittFaxStreamEatBits(n) { - if ((this.inputBits -= n) < 0) - this.inputBits = 0; - }; + // inverse DCT on columns + for (i = 0; i < 8; ++i) { + var col = i; - return constructor; -})(); + // check for all-zero AC coefficients + if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 && + p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 && + p[7*8 + col] == 0) { + t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; + p[0*8 + col] = t; + p[1*8 + col] = t; + p[2*8 + col] = t; + p[3*8 + col] = t; + p[4*8 + col] = t; + p[5*8 + col] = t; + p[6*8 + col] = t; + p[7*8 + col] = t; + continue; + } -var LZWStream = (function lzwStream() { - function constructor(str, earlyChange) { - this.str = str; - this.dict = str.dict; - this.cachedData = 0; - this.bitsCached = 0; + // stage 4 + v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12; + v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12; + v2 = p[2*8 + col]; + v3 = p[6*8 + col]; + v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12; + v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12; + v5 = p[3*8 + col]; + v6 = p[5*8 + col]; - var maxLzwDictionarySize = 4096; - var lzwState = { - earlyChange: earlyChange, - codeLength: 9, - nextCode: 258, - dictionaryValues: new Uint8Array(maxLzwDictionarySize), - dictionaryLengths: new Uint16Array(maxLzwDictionarySize), - dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize), - currentSequence: new Uint8Array(maxLzwDictionarySize), - currentSequenceLength: 0 - }; - for (var i = 0; i < 256; ++i) { - lzwState.dictionaryValues[i] = i; - lzwState.dictionaryLengths[i] = 1; - } - this.lzwState = lzwState; + // stage 3 + t = (v0 - v1 + 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; - DecodeStream.call(this); - } + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; - constructor.prototype = Object.create(DecodeStream.prototype); + // stage 1 + p[0*8 + col] = v0 + v7; + p[7*8 + col] = v0 - v7; + p[1*8 + col] = v1 + v6; + p[6*8 + col] = v1 - v6; + p[2*8 + col] = v2 + v5; + p[5*8 + col] = v2 - v5; + p[3*8 + col] = v3 + v4; + p[4*8 + col] = v3 - v4; + } - constructor.prototype.readBits = function lzwStreamReadBits(n) { - var bitsCached = this.bitsCached; - var cachedData = this.cachedData; - while (bitsCached < n) { - var c = this.str.getByte(); - if (c == null) { - this.eof = true; - return null; + // convert to 8-bit integers + for (i = 0; i < 64; ++i) { + var sample = 128 + ((p[i] + 8) >> 4); + dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample; } - cachedData = (cachedData << 8) | c; - bitsCached += 8; } - this.bitsCached = (bitsCached -= n); - this.cachedData = cachedData; - this.lastCode = null; - return (cachedData >>> bitsCached) & ((1 << n) - 1); - }; - - constructor.prototype.readBlock = function lzwStreamReadBlock() { - var blockSize = 512; - var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize; - var i, j, q; - - var lzwState = this.lzwState; - if (!lzwState) - return; // eof was found - - var earlyChange = lzwState.earlyChange; - var nextCode = lzwState.nextCode; - var dictionaryValues = lzwState.dictionaryValues; - var dictionaryLengths = lzwState.dictionaryLengths; - var dictionaryPrevCodes = lzwState.dictionaryPrevCodes; - var codeLength = lzwState.codeLength; - var prevCode = lzwState.prevCode; - var currentSequence = lzwState.currentSequence; - var currentSequenceLength = lzwState.currentSequenceLength; - var decodedLength = 0; - var currentBufferLength = this.bufferLength; - var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + var i, j; + for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { + var scanLine = blockRow << 3; + for (i = 0; i < 8; i++) + lines.push(new Uint8Array(samplesPerLine)); + for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { + quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); - for (i = 0; i < blockSize; i++) { - var code = this.readBits(codeLength); - var hasPrev = currentSequenceLength > 0; - if (code < 256) { - currentSequence[0] = code; - currentSequenceLength = 1; - } else if (code >= 258) { - if (code < nextCode) { - currentSequenceLength = dictionaryLengths[code]; - for (j = currentSequenceLength - 1, q = code; j >= 0; j--) { - currentSequence[j] = dictionaryValues[q]; - q = dictionaryPrevCodes[q]; - } - } else { - currentSequence[currentSequenceLength++] = currentSequence[0]; + var offset = 0, sample = blockCol << 3; + for (j = 0; j < 8; j++) { + var line = lines[scanLine + j]; + for (i = 0; i < 8; i++) + line[sample + i] = r[offset++]; } - } else if (code == 256) { - codeLength = 9; - nextCode = 258; - currentSequenceLength = 0; - continue; - } else { - this.eof = true; - delete this.lzwState; - break; } + } + return lines; + } - if (hasPrev) { - dictionaryPrevCodes[nextCode] = prevCode; - dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1; - dictionaryValues[nextCode] = currentSequence[0]; - nextCode++; - codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ? - codeLength : Math.min(Math.log(nextCode + earlyChange) / - 0.6931471805599453 + 1, 12) | 0; + constructor.prototype = { + load: function load(path) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", path, true); + xhr.responseType = "arraybuffer"; + xhr.onload = (function() { + // TODO catch parse error + var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function parse(data) { + var offset = 0, length = data.length; + function readUint16() { + var value = (data[offset] << 8) | data[offset + 1]; + offset += 2; + return value; } - prevCode = code; - - decodedLength += currentSequenceLength; - if (estimatedDecodedSize < decodedLength) { - do { - estimatedDecodedSize += decodedSizeDelta; - } while (estimatedDecodedSize < decodedLength); - buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize); + function readDataBlock() { + var length = readUint16(); + var array = data.subarray(offset, offset + length - 2); + offset += array.length; + return array; + } + function prepareComponents(frame) { + var maxH = 0, maxV = 0; + var component, componentId; + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + if (maxH < component.h) maxH = component.h; + if (maxV < component.v) maxV = component.v; + } + } + var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH); + var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV); + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH); + var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV); + var blocksPerLineForMcu = mcusPerLine * component.h; + var blocksPerColumnForMcu = mcusPerColumn * component.v; + var blocks = []; + for (var i = 0; i < blocksPerColumnForMcu; i++) { + var row = []; + for (var j = 0; j < blocksPerLineForMcu; j++) + row.push(new Int32Array(64)); + blocks.push(row); + } + component.blocksPerLine = blocksPerLine; + component.blocksPerColumn = blocksPerColumn; + component.blocks = blocks; + } + } + frame.maxH = maxH; + frame.maxV = maxV; + frame.mcusPerLine = mcusPerLine; + frame.mcusPerColumn = mcusPerColumn; + } + var jfif = null; + var adobe = null; + var pixels = null; + var frame, resetInterval; + var quantizationTables = [], frames = []; + var huffmanTablesAC = [], huffmanTablesDC = []; + var fileMarker = readUint16(); + if (fileMarker != 0xFFD8) { // SOI (Start of Image) + throw "SOI not found"; } - for (j = 0; j < currentSequenceLength; j++) - buffer[currentBufferLength++] = currentSequence[j]; - } - lzwState.nextCode = nextCode; - lzwState.codeLength = codeLength; - lzwState.prevCode = prevCode; - lzwState.currentSequenceLength = currentSequenceLength; - - this.bufferLength = currentBufferLength; - }; - return constructor; -})(); + fileMarker = readUint16(); + while (fileMarker != 0xFFD9) { // EOI (End of image) + var i, j, l; + switch(fileMarker) { + case 0xFFE0: // APP0 (Application Specific) + case 0xFFE1: // APP1 + case 0xFFE2: // APP2 + case 0xFFE3: // APP3 + case 0xFFE4: // APP4 + case 0xFFE5: // APP5 + case 0xFFE6: // APP6 + case 0xFFE7: // APP7 + case 0xFFE8: // APP8 + case 0xFFE9: // APP9 + case 0xFFEA: // APP10 + case 0xFFEB: // APP11 + case 0xFFEC: // APP12 + case 0xFFED: // APP13 + case 0xFFEE: // APP14 + case 0xFFEF: // APP15 + case 0xFFFE: // COM (Comment) + var appData = readDataBlock(); -/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + if (fileMarker === 0xFFE0) { + if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && + appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00' + jfif = { + version: { major: appData[5], minor: appData[6] }, + densityUnits: appData[7], + xDensity: (appData[8] << 8) | appData[9], + yDensity: (appData[10] << 8) | appData[11], + thumbWidth: appData[12], + thumbHeight: appData[13], + thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) + }; + } + } + // TODO APP1 - Exif + if (fileMarker === 0xFFEE) { + if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && + appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00' + adobe = { + version: appData[6], + flags0: (appData[7] << 8) | appData[8], + flags1: (appData[9] << 8) | appData[10], + transformCode: appData[11] + }; + } + } + break; -'use strict'; + case 0xFFDB: // DQT (Define Quantization Tables) + var quantizationTableCount = Math.floor((readUint16() - 2) / 65); + for (i = 0; i < quantizationTableCount; i++) { + var quantizationTableSpec = data[offset++]; + var tableData = new Int32Array(64); + if ((quantizationTableSpec >> 4) === 0) { // 8 bit values + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = data[offset++]; + } + } else if ((quantizationTableSpec >> 4) === 1) { //16 bit + tableData[j] = readUint16(); + } else + throw "DQT: invalid table spec"; + quantizationTables[quantizationTableSpec & 15] = tableData; + } + break; -function MessageHandler(name, comObj) { - this.name = name; - this.comObj = comObj; - var ah = this.actionHandler = {}; + case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT) + case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT) + readUint16(); // skip data length + frame = {}; + frame.progressive = (fileMarker === 0xFFC2); + frame.precision = data[offset++]; + frame.scanLines = readUint16(); + frame.samplesPerLine = readUint16(); + frame.components = []; + var componentsCount = data[offset++], componentId; + var maxH = 0, maxV = 0; + for (i = 0; i < componentsCount; i++) { + componentId = data[offset]; + var h = data[offset + 1] >> 4; + var v = data[offset + 1] & 15; + var qId = data[offset + 2]; + frame.components[componentId] = { + h: h, + v: v, + quantizationTable: quantizationTables[qId] + }; + offset += 3; + } + prepareComponents(frame); + frames.push(frame); + break; - ah['console_log'] = [function ahConsoleLog(data) { - console.log.apply(console, data); - }]; - ah['console_error'] = [function ahConsoleError(data) { - console.error.apply(console, data); - }]; + case 0xFFC4: // DHT (Define Huffman Tables) + var huffmanLength = readUint16(); + for (i = 2; i < huffmanLength;) { + var huffmanTableSpec = data[offset++]; + var codeLengths = new Uint8Array(16); + var codeLengthSum = 0; + for (j = 0; j < 16; j++, offset++) + codeLengthSum += (codeLengths[j] = data[offset]); + var huffmanValues = new Uint8Array(codeLengthSum); + for (j = 0; j < codeLengthSum; j++, offset++) + huffmanValues[j] = data[offset]; + i += 17 + codeLengthSum; - comObj.onmessage = function messageHandlerComObjOnMessage(event) { - var data = event.data; - if (data.action in ah) { - var action = ah[data.action]; - action[0].call(action[1], data.data); - } else { - throw 'Unkown action from worker: ' + data.action; - } - }; -} + ((huffmanTableSpec >> 4) === 0 ? + huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = + buildHuffmanTable(codeLengths, huffmanValues); + } + break; -MessageHandler.prototype = { - on: function messageHandlerOn(actionName, handler, scope) { - var ah = this.actionHandler; - if (ah[actionName]) { - throw 'There is already an actionName called "' + actionName + '"'; - } - ah[actionName] = [handler, scope]; - }, + case 0xFFDD: // DRI (Define Restart Interval) + readUint16(); // skip data length + resetInterval = readUint16(); + break; - send: function messageHandlerSend(actionName, data) { - this.comObj.postMessage({ - action: actionName, - data: data - }); - } -}; + case 0xFFDA: // SOS (Start of Scan) + var scanLength = readUint16(); + var selectorsCount = data[offset++]; + var components = [], component; + for (i = 0; i < selectorsCount; i++) { + component = frame.components[data[offset++]]; + var tableSpec = data[offset++]; + component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; + component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; + components.push(component); + } + var spectralStart = data[offset++]; + var spectralEnd = data[offset++]; + var successiveApproximation = data[offset++]; + var processed = decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successiveApproximation >> 4, successiveApproximation & 15); + offset += processed; + break; + default: + throw "unknown JPEG marker " + fileMarker.toString(16); + } + fileMarker = readUint16(); + } + if (frames.length != 1) + throw "only single frame JPEGs supported"; -var WorkerMessageHandler = { - setup: function wphSetup(handler) { - var pdfDoc = null; + this.width = frame.samplesPerLine; + this.height = frame.scanLines; + this.jfif = jfif; + this.adobe = adobe; + this.components = []; + for (var id in frame.components) { + if (frame.components.hasOwnProperty(id)) { + this.components.push({ + lines: buildComponentData(frame, frame.components[id]), + scaleX: frame.components[id].h / frame.maxH, + scaleY: frame.components[id].v / frame.maxV + }); + } + } + }, + getData: function getData(width, height) { + function clampTo8bit(a) { + return a < 0 ? 0 : a > 255 ? 255 : a; + } + var scaleX = this.width / width, scaleY = this.height / height; - handler.on('test', function wphSetupTest(data) { - handler.send('test', data instanceof Uint8Array); - }); + var component1, component2, component3, component4; + var component1Line, component2Line, component3Line, component4Line; + var x, y; + var offset = 0; + var Y, Cb, Cr, K, C, M, Ye, R, G, B; + var colorTransform; + var dataLength = width * height * this.components.length; + var data = new Uint8Array(dataLength); + switch (this.components.length) { + case 1: + component1 = this.components[0]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; - handler.on('workerSrc', function wphSetupWorkerSrc(data) { - // In development, the `workerSrc` message is handled in the - // `worker_loader.js` file. In production the workerProcessHandler is - // called for this. This servers as a dummy to prevent calling an - // undefined action `workerSrc`. - }); + data[offset++] = Y; + } + } + break; + case 3: + // The default transform for three components is true + colorTransform = true; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.colorTransform !== 'undefined') + colorTransform = !!this.colorTransform; - handler.on('doc', function wphSetupDoc(data) { - // Create only the model of the PDFDoc, which is enough for - // processing the content of the pdf. - pdfDoc = new PDFDocModel(new Stream(data)); - }); + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + R = component1Line[0 | (x * component1.scaleX * scaleX)]; + G = component2Line[0 | (x * component2.scaleX * scaleX)]; + B = component3Line[0 | (x * component3.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; - handler.on('page_request', function wphSetupPageRequest(pageNum) { - pageNum = parseInt(pageNum); + R = clampTo8bit(Y + 1.402 * (Cr - 128)); + G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + B = clampTo8bit(Y + 1.772 * (Cb - 128)); + } - var page = pdfDoc.getPage(pageNum); + data[offset++] = R; + data[offset++] = G; + data[offset++] = B; + } + } + break; + case 4: + if (!this.adobe) + throw 'Unsupported color mode (4 components)'; + // The default transform for four components is false + colorTransform = false; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.colorTransform !== 'undefined') + colorTransform = !!this.colorTransform; - // The following code does quite the same as - // Page.prototype.startRendering, but stops at one point and sends the - // result back to the main thread. - var gfx = new CanvasGraphics(null); + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + component4 = this.components[3]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + C = component1Line[0 | (x * component1.scaleX * scaleX)]; + M = component2Line[0 | (x * component2.scaleX * scaleX)]; + Ye = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; - var start = Date.now(); + C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); + M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); + } + data[offset++] = C; + data[offset++] = M; + data[offset++] = Ye; + data[offset++] = K; + } + } + break; + default: + throw 'Unsupported color mode'; + } + return data; + }, + copyToImageData: function copyToImageData(imageData) { + var width = imageData.width, height = imageData.height; + var imageDataArray = imageData.data; + var data = this.getData(width, height); + var i = 0, j = 0, x, y; + var Y, K, C, M, R, G, B; + switch (this.components.length) { + case 1: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + Y = data[i++]; - var dependency = []; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + imageDataArray[j++] = 255; + } + } + break; + case 3: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + R = data[i++]; + G = data[i++]; + B = data[i++]; - // Pre compile the pdf page and fetch the fonts/images. - var IRQueue = page.getIRQueue(handler, dependency); + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + imageDataArray[j++] = 255; + } + } + break; + case 4: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + C = data[i++]; + M = data[i++]; + Y = data[i++]; + K = data[i++]; - console.log('page=%d - getIRQueue: time=%dms, len=%d', pageNum, - Date.now() - start, IRQueue.fnArray.length); + R = 255 - clampTo8bit(C * (1 - K / 255) + K); + G = 255 - clampTo8bit(M * (1 - K / 255) + K); + B = 255 - clampTo8bit(Y * (1 - K / 255) + K); - // Filter the dependecies for fonts. - var fonts = {}; - for (var i = 0, ii = dependency.length; i < ii; i++) { - var dep = dependency[i]; - if (dep.indexOf('font_') == 0) { - fonts[dep] = true; - } + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + imageDataArray[j++] = 255; + } + } + break; + default: + throw 'Unsupported color mode'; } + } + }; - handler.send('page', { - pageNum: pageNum, - IRQueue: IRQueue, - depFonts: Object.keys(fonts) - }); - }, this); + return constructor; +})();/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ - handler.on('font', function wphSetupFont(data) { - var objId = data[0]; - var name = data[1]; - var file = data[2]; - var properties = data[3]; +'use strict'; - var font = { - name: name, - file: file, - properties: properties - }; +var JpxImage = (function JpxImageClosure() { + // Table E.1 + var SubbandsGainLog2 = { + 'LL': 0, + 'LH': 1, + 'HL': 1, + 'HH': 2 + }; + function JpxImage() { + this.failOnCorruptedImage = false; + } + JpxImage.prototype = { + load: function JpxImage_load(url) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = (function() { + // TODO catch parse error + var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function JpxImage_parse(data) { + function ReadUint(data, offset, bytes) { + var n = 0; + for (var i = 0; i < bytes; i++) + n = n * 256 + (data[offset + i] & 0xFF); + return n; + } + var position = 0, length = data.length; + while (position < length) { + var headerSize = 8; + var lbox = ReadUint(data, position, 4); + var tbox = ReadUint(data, position + 4, 4); + position += headerSize; + if (lbox == 1) { + lbox = ReadUint(data, position, 8); + position += 8; + headerSize += 8; + } + if (lbox == 0) + lbox = length - position + headerSize; + if (lbox < headerSize) + error('JPX error: Invalid box field size'); + var dataLength = lbox - headerSize; + var jumpDataLength = true; + switch (tbox) { + case 0x6A501A1A: // 'jP\032\032' + // TODO + break; + case 0x6A703268: // 'jp2h' + jumpDataLength = false; // parsing child boxes + break; + case 0x636F6C72: // 'colr' + // TODO + break; + case 0x6A703263: // 'jp2c' + this.parseCodestream(data, position, position + dataLength); + break; + } + if (jumpDataLength) + position += dataLength; + } + }, + parseCodestream: function JpxImage_parseCodestream(data, start, end) { + var context = {}; + try { + var position = start; + while (position < end) { + var code = readUint16(data, position); + position += 2; + + var length = 0, j; + switch (code) { + case 0xFF4F: // Start of codestream (SOC) + context.mainHeader = true; + break; + case 0xFFD9: // End of codestream (EOC) + break; + case 0xFF51: // Image and tile size (SIZ) + length = readUint16(data, position); + var siz = {}; + siz.Xsiz = readUint32(data, position + 4); + siz.Ysiz = readUint32(data, position + 8); + siz.XOsiz = readUint32(data, position + 12); + siz.YOsiz = readUint32(data, position + 16); + siz.XTsiz = readUint32(data, position + 20); + siz.YTsiz = readUint32(data, position + 24); + siz.XTOsiz = readUint32(data, position + 28); + siz.YTOsiz = readUint32(data, position + 32); + var componentsCount = readUint16(data, position + 36); + siz.Csiz = componentsCount; + var components = []; + j = position + 38; + for (var i = 0; i < componentsCount; i++) { + var component = { + precision: (data[j] & 0x7F) + 1, + isSigned: !!(data[j] & 0x80), + XRsiz: data[j + 1], + YRsiz: data[j + 1] + }; + calculateComponentDimensions(component, siz); + components.push(component); + } + context.SIZ = siz; + context.components = components; + calculateTileGrids(context, components); + context.QCC = []; + context.COC = []; + break; + case 0xFF5C: // Quantization default (QCD) + length = readUint16(data, position); + var qcd = {}; + j = position + 2; + var sqcd = data[j++]; + var spqcdSize, scalarExpounded; + switch (sqcd & 0x1F) { + case 0: + spqcdSize = 8; + scalarExpounded = true; + break; + case 1: + spqcdSize = 16; + scalarExpounded = false; + break; + case 2: + spqcdSize = 16; + scalarExpounded = true; + break; + default: + throw 'Invalid SQcd value ' + sqcd; + } + qcd.noQuantization = spqcdSize == 8; + qcd.scalarExpounded = scalarExpounded; + qcd.guardBits = sqcd >> 5; + var spqcds = []; + while (j < length + position) { + var spqcd = {}; + if (spqcdSize == 8) { + spqcd.epsilon = data[j++] >> 3; + spqcd.mu = 0; + } else { + spqcd.epsilon = data[j] >> 3; + spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1]; + j += 2; + } + spqcds.push(spqcd); + } + qcd.SPqcds = spqcds; + if (context.mainHeader) + context.QCD = qcd; + else { + context.currentTile.QCD = qcd; + context.currentTile.QCC = []; + } + break; + case 0xFF5D: // Quantization component (QCC) + length = readUint16(data, position); + var qcc = {}; + j = position + 2; + var cqcc; + if (context.SIZ.Csiz < 257) + cqcc = data[j++]; + else { + cqcc = readUint16(data, j); + j += 2; + } + var sqcd = data[j++]; + var spqcdSize, scalarExpounded; + switch (sqcd & 0x1F) { + case 0: + spqcdSize = 8; + scalarExpounded = true; + break; + case 1: + spqcdSize = 16; + scalarExpounded = false; + break; + case 2: + spqcdSize = 16; + scalarExpounded = true; + break; + default: + throw 'Invalid SQcd value ' + sqcd; + } + qcc.noQuantization = spqcdSize == 8; + qcc.scalarExpounded = scalarExpounded; + qcc.guardBits = sqcd >> 5; + var spqcds = []; + while (j < length + position) { + var spqcd = {}; + if (spqcdSize == 8) { + spqcd.epsilon = data[j++] >> 3; + spqcd.mu = 0; + } else { + spqcd.epsilon = data[j] >> 3; + spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1]; + j += 2; + } + spqcds.push(spqcd); + } + qcc.SPqcds = spqcds; + if (context.mainHeader) + context.QCC[cqcc] = qcc; + else + context.currentTile.QCC[cqcc] = qcc; + break; + case 0xFF52: // Coding style default (COD) + length = readUint16(data, position); + var cod = {}; + j = position + 2; + var scod = data[j++]; + cod.entropyCoderWithCustomPrecincts = !!(scod & 1); + cod.sopMarkerUsed = !!(scod & 2); + cod.ephMarkerUsed = !!(scod & 4); + var codingStyle = {}; + cod.progressionOrder = data[j++]; + cod.layersCount = readUint16(data, j); + j += 2; + cod.multipleComponentTransform = data[j++]; + + cod.decompositionLevelsCount = data[j++]; + cod.xcb = (data[j++] & 0xF) + 2; + cod.ycb = (data[j++] & 0xF) + 2; + var blockStyle = data[j++]; + cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1); + cod.resetContextProbabilities = !!(blockStyle & 2); + cod.terminationOnEachCodingPass = !!(blockStyle & 4); + cod.verticalyStripe = !!(blockStyle & 8); + cod.predictableTermination = !!(blockStyle & 16); + cod.segmentationSymbolUsed = !!(blockStyle & 32); + cod.transformation = data[j++]; + if (cod.entropyCoderWithCustomPrecincts) { + var precinctsSizes = {}; + while (j < length + position) { + var precinctsSize = data[j]; + precinctsSizes.push({ + PPx: precinctsSize & 0xF, + PPy: precinctsSize >> 4 + }); + } + cod.precinctsSizes = precinctsSizes; + } - // Some fonts don't have a file, e.g. the build in ones like Arial. - if (file) { - var fontFileDict = new Dict(); - fontFileDict.map = file.dict.map; + if (cod.sopMarkerUsed || cod.ephMarkerUsed || + cod.selectiveArithmeticCodingBypass || + cod.resetContextProbabilities || + cod.terminationOnEachCodingPass || + cod.verticalyStripe || cod.predictableTermination || + cod.segmentationSymbolUsed) + throw 'Unsupported COD options: ' + uneval(cod); + + if (context.mainHeader) + context.COD = cod; + else { + context.currentTile.COD = cod; + context.currentTile.COC = []; + } + break; + case 0xFF90: // Start of tile-part (SOT) + length = readUint16(data, position); + var tile = {}; + tile.index = readUint16(data, position + 2); + tile.length = readUint32(data, position + 4); + tile.dataEnd = tile.length + position - 2; + tile.partIndex = data[position + 8]; + tile.partsCount = data[position + 9]; + + context.mainHeader = false; + if (tile.partIndex == 0) { + // reset component specific settings + tile.COD = context.COD; + tile.COC = context.COC.slice(0); // clone of the global COC + tile.QCD = context.QCD; + tile.QCC = context.QCC.slice(0); // clone of the global COC + } + context.currentTile = tile; + break; + case 0xFF93: // Start of data (SOD) + var tile = context.currentTile; + if (tile.partIndex == 0) { + initializeTile(context, tile.index); + buildPackets(context); + } - var fontFile = new Stream(file.bytes, file.start, - file.end - file.start, fontFileDict); + // moving to the end of the data + length = tile.dataEnd - position; - // Check if this is a FlateStream. Otherwise just use the created - // Stream one. This makes complex_ttf_font.pdf work. - var cmf = file.bytes[0]; - if ((cmf & 0x0f) == 0x08) { - font.file = new FlateStream(fontFile); - } else { - font.file = fontFile; + parseTilePackets(context, data, position, length); + break; + case 0xFF64: // Comment (COM) + length = readUint16(data, position); + // skipping content + break; + default: + throw 'Unknown codestream code: ' + code.toString(16); + } + position += length; } + } catch (e) { + if (this.failOnCorruptedImage) + error('JPX error: ' + e); + else + warn('JPX error: ' + e + '. Trying to recover'); } - - var obj = new Font(font.name, font.file, font.properties); - - var str = ''; - var objData = obj.data; - if (objData) { - var length = objData.length; - for (var j = 0; j < length; ++j) - str += String.fromCharCode(objData[j]); + this.tiles = transformComponents(context); + this.width = context.SIZ.Xsiz - context.SIZ.XOsiz; + this.height = context.SIZ.Ysiz - context.SIZ.YOsiz; + this.componentsCount = context.SIZ.Csiz; + } + }; + function readUint32(data, offset) { + return (data[offset] << 24) | (data[offset + 1] << 16) | + (data[offset + 2] << 8) | data[offset + 3]; + } + function readUint16(data, offset) { + return (data[offset] << 8) | data[offset + 1]; + } + function log2(x) { + var n = 1, i = 0; + while (x > n) { + n <<= 1; + i++; + } + return i; + } + function calculateComponentDimensions(component, siz) { + // Section B.2 Component mapping + component.x0 = Math.ceil(siz.XOsiz / component.XRsiz); + component.x1 = Math.ceil(siz.Xsiz / component.XRsiz); + component.y0 = Math.ceil(siz.YOsiz / component.YRsiz); + component.y1 = Math.ceil(siz.Ysiz / component.YRsiz); + component.width = component.x1 - component.x0; + component.height = component.y1 - component.y0; + } + function calculateTileGrids(context, components) { + var siz = context.SIZ; + // Section B.3 Division into tile and tile-components + var tiles = []; + var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz); + var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz); + for (var q = 0; q < numYtiles; q++) { + for (var p = 0; p < numXtiles; p++) { + var tile = {}; + tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz); + tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz); + tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz); + tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz); + tile.width = tile.tx1 - tile.tx0; + tile.height = tile.ty1 - tile.ty0; + tile.components = []; + tiles.push(tile); } - - obj.str = str; - - // Remove the data array form the font object, as it's not needed - // anymore as we sent over the ready str. - delete obj.data; - - handler.send('font_ready', [objId, obj]); - }); + } + context.tiles = tiles; + + var componentsCount = siz.Csiz; + for (var i = 0, ii = componentsCount; i < ii; i++) { + var component = components[i]; + var tileComponents = []; + for (var j = 0, jj = tiles.length; j < jj; j++) { + var tileComponent = {}, tile = tiles[j]; + tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz); + tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz); + tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz); + tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz); + tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0; + tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0; + tile.components[i] = tileComponent; + } + } } -}; - -var consoleTimer = {}; - -var workerConsole = { - log: function log() { - var args = Array.prototype.slice.call(arguments); - postMessage({ - action: 'console_log', - data: args - }); - }, - - error: function error() { - var args = Array.prototype.slice.call(arguments); - postMessage({ - action: 'console_error', - data: args - }); - }, - - time: function time(name) { - consoleTimer[name] = Date.now(); - }, - - timeEnd: function timeEnd(name) { - var time = consoleTimer[name]; - if (time == null) { - throw 'Unkown timer name ' + name; + function getBlocksDimensions(context, component, r) { + var codOrCoc = component.codingStyleParameters; + var result = {}; + if (!codOrCoc.entropyCoderWithCustomPrecincts) { + result.PPx = 15; + result.PPy = 15; + } else { + result.PPx = codOrCoc.precinctsSizes[r].PPx; + result.PPy = codOrCoc.precinctsSizes[r].PPy; } - this.log('Timer:', name, Date.now() - time); + // calculate codeblock size as described in section B.7 + result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : + Math.min(codOrCoc.xcb, result.PPx); + result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : + Math.min(codOrCoc.ycb, result.PPy); + return result; } -}; - -// Worker thread? -if (typeof window === 'undefined') { - globalScope.console = workerConsole; + function buildPrecincts(context, resolution, dimensions) { + // Section B.6 Division resolution to precincts + var precinctWidth = 1 << dimensions.PPx; + var precinctHeight = 1 << dimensions.PPy; + var numprecinctswide = resolution.trx1 > resolution.trx0 ? + Math.ceil(resolution.trx1 / precinctWidth) - + Math.floor(resolution.trx0 / precinctWidth) : 0; + var numprecinctshigh = resolution.try1 > resolution.try0 ? + Math.ceil(resolution.try1 / precinctHeight) - + Math.floor(resolution.try0 / precinctHeight) : 0; + var numprecincts = numprecinctswide * numprecinctshigh; + var precinctXOffset = Math.floor(resolution.trx0 / precinctWidth) * + precinctWidth; + var precinctYOffset = Math.floor(resolution.try0 / precinctHeight) * + precinctHeight; + resolution.precinctParameters = { + precinctXOffset: precinctXOffset, + precinctYOffset: precinctYOffset, + precinctWidth: precinctWidth, + precinctHeight: precinctHeight, + numprecinctswide: numprecinctswide, + numprecinctshigh: numprecinctshigh, + numprecincts: numprecincts + }; + } + function buildCodeblocks(context, subband, dimensions) { + // Section B.7 Division sub-band into code-blocks + var xcb_ = dimensions.xcb_; + var ycb_ = dimensions.ycb_; + var codeblockWidth = 1 << xcb_; + var codeblockHeight = 1 << ycb_; + var cbx0 = Math.floor(subband.tbx0 / codeblockWidth); + var cby0 = Math.floor(subband.tby0 / codeblockHeight); + var cbx1 = Math.ceil(subband.tbx1 / codeblockWidth); + var cby1 = Math.ceil(subband.tby1 / codeblockHeight); + var precinctParameters = subband.resolution.precinctParameters; + var codeblocks = []; + var precincts = []; + for (var j = cby0; j < cby1; j++) { + for (var i = cbx0; i < cbx1; i++) { + var codeblock = { + cbx: i, + cby: j, + tbx0: codeblockWidth * i, + tby0: codeblockHeight * j, + tbx1: codeblockWidth * (i + 1), + tby1: codeblockHeight * (j + 1) + }; + // calculate precinct number + var pi = Math.floor((codeblock.tbx0 - + precinctParameters.precinctXOffset) / + precinctParameters.precinctWidth); + var pj = Math.floor((codeblock.tby0 - + precinctParameters.precinctYOffset) / + precinctParameters.precinctHeight); + var precinctNumber = pj + + pi * precinctParameters.numprecinctswide; + codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0); + codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0); + codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1); + codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1); + codeblock.precinctNumber = precinctNumber; + codeblock.subbandType = subband.type; + var coefficientsLength = (codeblock.tbx1_ - codeblock.tbx0_) * + (codeblock.tby1_ - codeblock.tby0_); + codeblock.Lblock = 3; + codeblocks.push(codeblock); + // building precinct for the sub-band + var precinct; + if (precinctNumber in precincts) { + precinct = precincts[precinctNumber]; + precinct.cbxMin = Math.min(precinct.cbxMin, i); + precinct.cbyMin = Math.min(precinct.cbyMin, j); + precinct.cbxMax = Math.max(precinct.cbxMax, i); + precinct.cbyMax = Math.max(precinct.cbyMax, j); + } else { + precincts[precinctNumber] = precinct = { + cbxMin: i, + cbyMin: j, + cbxMax: i, + cbyMax: j + }; + } + codeblock.precinct = precinct; + } + } + subband.codeblockParameters = { + codeblockWidth: xcb_, + codeblockHeight: ycb_, + numcodeblockwide: cbx1 - cbx0 + 1, + numcodeblockhigh: cby1 - cby1 + 1 + }; + subband.codeblocks = codeblocks; + for (var i = 0, ii = codeblocks.length; i < ii; i++) { + var codeblock = codeblocks[i]; + var precinctNumber = codeblock.precinctNumber; + } + subband.precincts = precincts; + } + function createPacket(resolution, precinctNumber, layerNumber) { + var precinctCodeblocks = []; + // Section B.10.8 Order of info in packet + var subbands = resolution.subbands; + // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence + for (var i = 0, ii = subbands.length; i < ii; i++) { + var subband = subbands[i]; + var codeblocks = subband.codeblocks; + for (var j = 0, jj = codeblocks.length; j < jj; j++) { + var codeblock = codeblocks[j]; + if (codeblock.precinctNumber != precinctNumber) + continue; + precinctCodeblocks.push(codeblock); + } + } + return { + layerNumber: layerNumber, + codeblocks: precinctCodeblocks + }; + } + function LayerResolutionComponentPositionIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var maxDecompositionLevelsCount = 0; + for (var q = 0; q < componentsCount; q++) { + maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, + tile.components[q].codingStyleParameters.decompositionLevelsCount); + } - var handler = new MessageHandler('worker_processor', this); - WorkerMessageHandler.setup(handler); -} + var l = 0, r = 0, i = 0, k = 0; -/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.1 Layer-resolution-component-position + for (; l < layersCount; l++) { + for (; r <= maxDecompositionLevelsCount; r++) { + for (; i < componentsCount; i++) { + var component = tile.components[i]; + if (r > component.codingStyleParameters.decompositionLevelsCount) + continue; -// - The JPEG specification can be found in the ITU CCITT Recommendation T.81 -// (www.w3.org/Graphics/JPEG/itu-t81.pdf) -// - The JFIF specification can be found in the JPEG File Interchange Format -// (www.w3.org/Graphics/JPEG/jfif3.pdf) -// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters -// in PostScript Level 2, Technical Note #5116 -// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf) + var resolution = component.resolutions[r]; + var numprecincts = resolution.precinctParameters.numprecincts; + for (; k < numprecincts;) { + var packet = createPacket(resolution, k, l); + k++; + return packet; + } + k = 0; + } + i = 0; + } + r = 0; + } + throw 'Out of packets'; + }; + } + function ResolutionLayerComponentPositionIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var maxDecompositionLevelsCount = 0; + for (var q = 0; q < componentsCount; q++) { + maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, + tile.components[q].codingStyleParameters.decompositionLevelsCount); + } -var JpegImage = (function jpegImage() { - "use strict"; - var dctZigZag = new Int32Array([ - 0, - 1, 8, - 16, 9, 2, - 3, 10, 17, 24, - 32, 25, 18, 11, 4, - 5, 12, 19, 26, 33, 40, - 48, 41, 34, 27, 20, 13, 6, - 7, 14, 21, 28, 35, 42, 49, 56, - 57, 50, 43, 36, 29, 22, 15, - 23, 30, 37, 44, 51, 58, - 59, 52, 45, 38, 31, - 39, 46, 53, 60, - 61, 54, 47, - 55, 62, - 63 - ]); + var r = 0, l = 0, i = 0, k = 0; - var dctCos1 = 4017 // cos(pi/16) - var dctSin1 = 799 // sin(pi/16) - var dctCos3 = 3406 // cos(3*pi/16) - var dctSin3 = 2276 // sin(3*pi/16) - var dctCos6 = 1567 // cos(6*pi/16) - var dctSin6 = 3784 // sin(6*pi/16) - var dctSqrt2 = 5793 // sqrt(2) - var dctSqrt1d2 = 2896 // sqrt(2) / 2 + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.2 Resolution-layer-component-position + for (; r <= maxDecompositionLevelsCount; r++) { + for (; l < layersCount; l++) { + for (; i < componentsCount; i++) { + var component = tile.components[i]; + if (r > component.codingStyleParameters.decompositionLevelsCount) + continue; - function constructor() { + var resolution = component.resolutions[r]; + var numprecincts = resolution.precinctParameters.numprecincts; + for (; k < numprecincts;) { + var packet = createPacket(resolution, k, l); + k++; + return packet; + } + k = 0; + } + i = 0; + } + l = 0; + } + throw 'Out of packets'; + }; + } + function buildPackets(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var componentsCount = siz.Csiz; + // Creating resolutions and sub-bands for each component + for (var c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + var decompositionLevelsCount = + component.codingStyleParameters.decompositionLevelsCount; + // Section B.5 Resolution levels and sub-bands + var resolutions = []; + var subbands = []; + for (var r = 0; r <= decompositionLevelsCount; r++) { + var blocksDimensions = getBlocksDimensions(context, component, r); + var resolution = {}; + var scale = 1 << (decompositionLevelsCount - r); + resolution.trx0 = Math.ceil(component.tcx0 / scale); + resolution.try0 = Math.ceil(component.tcy0 / scale); + resolution.trx1 = Math.ceil(component.tcx1 / scale); + resolution.try1 = Math.ceil(component.tcy1 / scale); + buildPrecincts(context, resolution, blocksDimensions); + resolutions.push(resolution); + + var subband; + if (r == 0) { + // one sub-band (LL) with last decomposition + subband = {}; + subband.type = 'LL'; + subband.tbx0 = Math.ceil(component.tcx0 / scale); + subband.tby0 = Math.ceil(component.tcy0 / scale); + subband.tbx1 = Math.ceil(component.tcx1 / scale); + subband.tby1 = Math.ceil(component.tcy1 / scale); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolution.subbands = [subband]; + } else { + var bscale = 1 << (decompositionLevelsCount - r + 1); + var resolutionSubbands = []; + // three sub-bands (HL, LH and HH) with rest of decompositions + subband = {}; + subband.type = 'HL'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5); + subband.tby0 = Math.ceil(component.tcy0 / bscale); + subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5); + subband.tby1 = Math.ceil(component.tcy1 / bscale); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + subband = {}; + subband.type = 'LH'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale); + subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5); + subband.tbx1 = Math.ceil(component.tcx1 / bscale); + subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + subband = {}; + subband.type = 'HH'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5); + subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5); + subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5); + subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + resolution.subbands = resolutionSubbands; + } + } + component.resolutions = resolutions; + component.subbands = subbands; + } + // Generate the packets sequence + var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder; + var packetsIterator; + switch (progressionOrder) { + case 0: + tile.packetsIterator = + new LayerResolutionComponentPositionIterator(context); + break; + case 1: + tile.packetsIterator = + new ResolutionLayerComponentPositionIterator(context); + break; + default: + throw 'Unsupported progression order ' + progressionOrder; + } } + function parseTilePackets(context, data, offset, dataLength) { + var position = 0; + var buffer, bufferSize = 0, skipNextBit = false; + function readBits(count) { + while (bufferSize < count) { + var b = data[offset + position]; + position++; + if (skipNextBit) { + buffer = (buffer << 7) | b; + bufferSize += 7; + skipNextBit = false; + } else { + buffer = (buffer << 8) | b; + bufferSize += 8; + } + if (b == 0xFF) { + skipNextBit = true; + } + } + bufferSize -= count; + return (buffer >>> bufferSize) & ((1 << count) - 1); + } + function alignToByte() { + bufferSize = 0; + if (skipNextBit) { + position++; + skipNextBit = false; + } + } + function readCodingpasses() { + var value = readBits(1); + if (value == 0) + return 1; + value = (value << 1) | readBits(1); + if (value == 0x02) + return 2; + value = (value << 2) | readBits(2); + if (value <= 0x0E) + return (value & 0x03) + 3; + value = (value << 5) | readBits(5); + if (value <= 0x1FE) + return (value & 0x1F) + 6; + value = (value << 7) | readBits(7); + return (value & 0x7F) + 37; + } + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var packetsIterator = tile.packetsIterator; + while (position < dataLength) { + var packet = packetsIterator.nextPacket(); + if (!readBits(1)) { + alignToByte(); + continue; + } + var layerNumber = packet.layerNumber; + var queue = []; + for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) { + var codeblock = packet.codeblocks[i]; + var precinct = codeblock.precinct; + var codeblockColumn = codeblock.cbx - precinct.cbxMin; + var codeblockRow = codeblock.cby - precinct.cbyMin; + var codeblockIncluded = false; + var firstTimeInclusion = false; + if ('included' in codeblock) { + codeblockIncluded = !!readBits(1); + } else { + // reading inclusion tree + var precinct = codeblock.precinct; + var inclusionTree, zeroBitPlanesTree; + if ('inclusionTree' in precinct) { + inclusionTree = precinct.inclusionTree; + } else { + // building inclusion and zero bit-planes trees + var width = precinct.cbxMax - precinct.cbxMin + 1; + var height = precinct.cbyMax - precinct.cbyMin + 1; + inclusionTree = new InclusionTree(width, height, layerNumber); + zeroBitPlanesTree = new TagTree(width, height); + precinct.inclusionTree = inclusionTree; + precinct.zeroBitPlanesTree = zeroBitPlanesTree; + } - function buildHuffmanTable(codeLengths, values) { - var k = 0, code = [], i, j, length = 16; - while (length > 0 && !codeLengths[length - 1]) - length--; - code.push({children: [], index: 0}); - var p = code[0], q; - for (i = 0; i < length; i++) { - for (j = 0; j < codeLengths[i]; j++) { - p = code.pop(); - p.children[p.index] = values[k]; - while (p.index > 0) { - p = code.pop(); + if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) { + while (true) { + if (readBits(1)) { + var valueReady = !inclusionTree.nextLevel(); + if (valueReady) { + codeblock.included = true; + codeblockIncluded = firstTimeInclusion = true; + break; + } + } else { + inclusionTree.incrementValue(layerNumber); + break; + } + } + } } - p.index++; - code.push(p); - while (code.length <= i) { - code.push(q = {children: [], index: 0}); - p.children[p.index] = q.children; - p = q; + if (!codeblockIncluded) + continue; + if (firstTimeInclusion) { + zeroBitPlanesTree = precinct.zeroBitPlanesTree; + zeroBitPlanesTree.reset(codeblockColumn, codeblockRow); + while (true) { + if (readBits(1)) { + var valueReady = !zeroBitPlanesTree.nextLevel(); + if (valueReady) + break; + } else + zeroBitPlanesTree.incrementValue(); + } + codeblock.zeroBitPlanes = zeroBitPlanesTree.value; } - k++; + var codingpasses = readCodingpasses(); + while (readBits(1)) + codeblock.Lblock++; + var codingpassesLog2 = log2(codingpasses); + // rounding down log2 + var bits = ((codingpasses < (1 << codingpassesLog2)) ? + codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock; + var codedDataLength = readBits(bits); + queue.push({ + codeblock: codeblock, + codingpasses: codingpasses, + dataLength: codedDataLength + }); } - if (i + 1 < length) { - // p here points to last code - code.push(q = {children: [], index: 0}); - p.children[p.index] = q.children; - p = q; + alignToByte(); + while (queue.length > 0) { + var packetItem = queue.shift(); + var codeblock = packetItem.codeblock; + if (!('data' in codeblock)) + codeblock.data = []; + codeblock.data.push({ + data: data, + start: offset + position, + end: offset + position + packetItem.dataLength, + codingpasses: packetItem.codingpasses + }); + position += packetItem.dataLength; } } - return code[0].children; + return position; } + function copyCoefficients(coefficients, x0, y0, width, height, + delta, mb, codeblocks, transformation) { + var r = 0.5; // formula (E-6) + for (var i = 0, ii = codeblocks.length; i < ii; ++i) { + var codeblock = codeblocks[i]; + var blockWidth = codeblock.tbx1_ - codeblock.tbx0_; + var blockHeight = codeblock.tby1_ - codeblock.tby0_; + if (blockWidth == 0 || blockHeight == 0) + continue; + if (!('data' in codeblock)) + continue; - function decodeScan(data, offset, - frame, components, resetInterval, - spectralStart, spectralEnd, - successivePrev, successive) { - var precision = frame.precision; - var samplesPerLine = frame.samplesPerLine; - var scanLines = frame.scanLines; - var mcusPerLine = frame.mcusPerLine; - var progressive = frame.progressive; - var maxH = frame.maxH, maxV = frame.maxV; - - var startOffset = offset, bitsData = 0, bitsCount = 0; - function readBit() { - if (bitsCount > 0) { - bitsCount--; - return (bitsData >> bitsCount) & 1; - } - bitsData = data[offset++]; - if (bitsData == 0xFF) { - var nextByte = data[offset++]; - if (nextByte) { - throw "unexpected marker: " + ((bitsData << 8) | nextByte).toString(16); + var bitModel, currentCodingpassType; + bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, + codeblock.zeroBitPlanes); + currentCodingpassType = 2; // first bit plane starts from cleanup + + // collect data + var data = codeblock.data, totalLength = 0, codingpasses = 0; + for (var q = 0, qq = data.length; q < qq; q++) { + var dataItem = data[q]; + totalLength += dataItem.end - dataItem.start; + codingpasses += dataItem.codingpasses; + } + var encodedData = new Uint8Array(totalLength), k = 0; + for (var q = 0, qq = data.length; q < qq; q++) { + var dataItem = data[q]; + var chunk = dataItem.data.subarray(dataItem.start, dataItem.end); + encodedData.set(chunk, k); + k += chunk.length; + } + // decoding the item + var decoder = new ArithmeticDecoder(encodedData, 0, totalLength); + bitModel.setDecoder(decoder); + + for (var q = 0; q < codingpasses; q++) { + switch (currentCodingpassType) { + case 0: + bitModel.runSignificancePropogationPass(); + break; + case 1: + bitModel.runMagnitudeRefinementPass(); + break; + case 2: + bitModel.runCleanupPass(); + break; } - // unstuff 0 + currentCodingpassType = (currentCodingpassType + 1) % 3; + } + + var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width; + var position = 0; + for (var j = 0; j < blockHeight; j++) { + for (var k = 0; k < blockWidth; k++) { + var n = (bitModel.coefficentsSign[position] ? -1 : 1) * + bitModel.coefficentsMagnitude[position]; + var nb = bitModel.bitsDecoded[position], correction; + if (transformation == 0 || mb > nb) { + // use r only if transformation is irreversible or + // not all bitplanes were decoded for reversible transformation + n += n < 0 ? n - r : n > 0 ? n + r : 0; + correction = 1 << (mb - nb); + } else + correction = 1; + coefficients[offset++] = n * correction * delta; + position++; + } + offset += width - blockWidth; } - bitsCount = 7; - return bitsData >>> 7; } - function decodeHuffman(tree) { - var node = tree, bit; - while ((bit = readBit()) !== null) { - node = node[bit]; - if (typeof node === 'number') - return node; - if (typeof node !== 'object') - throw "invalid huffman sequence"; + } + function transformTile(context, tile, c) { + var component = tile.components[c]; + var codingStyleParameters = component.codingStyleParameters; + var quantizationParameters = component.quantizationParameters; + var decompositionLevelsCount = + codingStyleParameters.decompositionLevelsCount; + var spqcds = quantizationParameters.SPqcds; + var scalarExpounded = quantizationParameters.scalarExpounded; + var guardBits = quantizationParameters.guardBits; + var transformation = codingStyleParameters.transformation; + var precision = context.components[c].precision; + + var subbandCoefficients = []; + var k = 0, b = 0; + for (var i = 0; i <= decompositionLevelsCount; i++) { + var resolution = component.resolutions[i]; + + for (var j = 0, jj = resolution.subbands.length; j < jj; j++) { + var mu, epsilon; + if (!scalarExpounded) { + // formula E-5 + mu = spqcds[0].mu; + epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0); + } else { + mu = spqcds[b].mu; + epsilon = spqcds[b].epsilon; + } + + var subband = resolution.subbands[j]; + var width = subband.tbx1 - subband.tbx0; + var height = subband.tby1 - subband.tby0; + var gainLog2 = SubbandsGainLog2[subband.type]; + + // calulate quantization coefficient (Section E.1.1.1) + var delta = Math.pow(2, (precision + gainLog2) - epsilon) * + (1 + mu / 2048); + var mb = (guardBits + epsilon - 1); + + var coefficients = new Float32Array(width * height); + copyCoefficients(coefficients, subband.tbx0, subband.tby0, + width, height, delta, mb, subband.codeblocks, transformation); + + subbandCoefficients.push({ + width: width, + height: height, + items: coefficients + }); + + b++; } - return null; } - function receive(length) { - var n = 0; - while (length > 0) { - var bit = readBit(); - if (bit === null) return; - n = (n << 1) | bit; - length--; + + var transformation = codingStyleParameters.transformation; + var transform = transformation == 0 ? new IrreversibleTransform() : + new ReversibleTransform(); + var result = transform.calculate(subbandCoefficients, + component.tcx0, component.tcy0); + return { + left: component.tcx0, + top: component.tcy0, + width: result.width, + height: result.height, + items: result.items + }; + } + function transformComponents(context) { + var siz = context.SIZ; + var components = context.components; + var componentsCount = siz.Csiz; + var resultImages = []; + for (var i = 0, ii = context.tiles.length; i < ii; i++) { + var tile = context.tiles[i]; + var result = []; + for (var c = 0; c < componentsCount; c++) { + var image = transformTile(context, tile, c); + result.push(image); + } + + // Section G.2.2 Inverse multi component transform + if (tile.codingStyleDefaultParameters.multipleComponentTransform) { + var y0items = result[0].items; + var y1items = result[1].items; + var y2items = result[2].items; + for (var j = 0, jj = y0items.length; j < jj; j++) { + var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j]; + var i1 = y0 - ((y2 + y1) >> 2); + y1items[j] = i1; + y0items[j] = y2 + i1; + y2items[j] = y1 + i1; + } } - return n; - } - function receiveAndExtend(length) { - var n = receive(length); - if (n >= 1 << (length - 1)) - return n; - return n + (-1 << length) + 1; - } - function decodeBaseline(component, zz) { - var t = decodeHuffman(component.huffmanTableDC); - var diff = t === 0 ? 0 : receiveAndExtend(t); - zz[0]= (component.pred += diff); - var k = 1; - while (k < 64) { - var rs = decodeHuffman(component.huffmanTableAC); - var s = rs & 15, r = rs >> 4; - if (s === 0) { - if (r < 15) - break; - k += 16; + + // Section G.1 DC level shifting to unsigned component values + for (var c = 0; c < componentsCount; c++) { + var component = components[c]; + if (component.isSigned) continue; + + var offset = 1 << (component.precision - 1); + var tileImage = result[c]; + var items = tileImage.items; + for (var j = 0, jj = items.length; j < jj; j++) + items[j] += offset; + } + + // To simplify things: shift and clamp output to 8 bit unsigned + for (var c = 0; c < componentsCount; c++) { + var component = components[c]; + var offset = component.isSigned ? 128 : 0; + var shift = component.precision - 8; + var tileImage = result[c]; + var items = tileImage.items; + var data = new Uint8Array(items.length); + for (var j = 0, jj = items.length; j < jj; j++) { + var value = (items[j] >> shift) + offset; + data[j] = value < 0 ? 0 : value > 255 ? 255 : value; } - k += r; - var z = dctZigZag[k]; - zz[z] = receiveAndExtend(s); - k++; + result[c].items = data; } + + resultImages.push(result); } - function decodeDCFirst(component, zz) { - var t = decodeHuffman(component.huffmanTableDC); - var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive); - zz[0] = (component.pred += diff); + return resultImages; + } + function initializeTile(context, tileIndex) { + var siz = context.SIZ; + var componentsCount = siz.Csiz; + var tile = context.tiles[tileIndex]; + var resultTiles = []; + for (var c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + var qcdOrQcc = c in context.currentTile.QCC ? + context.currentTile.QCC[c] : context.currentTile.QCD; + component.quantizationParameters = qcdOrQcc; + var codOrCoc = c in context.currentTile.COC ? + context.currentTile.COC[c] : context.currentTile.COD; + component.codingStyleParameters = codOrCoc; } - function decodeDCSuccessive(component, zz) { - zz[0] |= readBit() << successive; + tile.codingStyleDefaultParameters = context.currentTile.COD; + } + + // Section B.10.2 Tag trees + var TagTree = (function TagTreeClosure() { + function TagTree(width, height) { + var levelsLength = log2(Math.max(width, height)) + 1; + this.levels = []; + for (var i = 0; i < levelsLength; i++) { + var level = { + width: width, + height: height, + items: [] + }; + this.levels.push(level); + width = Math.ceil(width / 2); + height = Math.ceil(height / 2); + } } - var eobrun = 0; - function decodeACFirst(component, zz) { - if (eobrun > 0) { - eobrun--; - return; + TagTree.prototype = { + reset: function TagTree_reset(i, j) { + var currentLevel = 0, value = 0; + while (currentLevel < this.levels.length) { + var level = this.levels[currentLevel]; + var index = i + j * level.width; + if (index in level.items) { + value = level.items[index]; + break; + } + level.index = index; + i >>= 1; + j >>= 1; + currentLevel++; + } + currentLevel--; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + this.currentLevel = currentLevel; + delete this.value; + }, + incrementValue: function TagTree_incrementValue() { + var level = this.levels[this.currentLevel]; + level.items[level.index]++; + }, + nextLevel: function TagTree_nextLevel() { + var currentLevel = this.currentLevel; + var level = this.levels[currentLevel]; + var value = level.items[level.index]; + currentLevel--; + if (currentLevel < 0) { + this.value = value; + return false; + } + + this.currentLevel = currentLevel; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + return true; } - var k = spectralStart, e = spectralEnd; - while (k <= e) { - var rs = decodeHuffman(component.huffmanTableAC); - var s = rs & 15, r = rs >> 4; - if (s === 0) { - if (r < 15) { - eobrun = receive(r) + (1 << r) - 1; + }; + return TagTree; + })(); + + var InclusionTree = (function InclusionTreeClosure() { + function InclusionTree(width, height, defaultValue) { + var levelsLength = log2(Math.max(width, height)) + 1; + this.levels = []; + for (var i = 0; i < levelsLength; i++) { + var items = new Uint8Array(width * height); + for (var j = 0, jj = items.length; j < jj; j++) + items[j] = defaultValue; + + var level = { + width: width, + height: height, + items: items + }; + this.levels.push(level); + + width = Math.ceil(width / 2); + height = Math.ceil(height / 2); + } + } + InclusionTree.prototype = { + reset: function InclusionTree_reset(i, j, stopValue) { + var currentLevel = 0; + while (currentLevel < this.levels.length) { + var level = this.levels[currentLevel]; + var index = i + j * level.width; + level.index = index; + var value = level.items[index]; + + if (value == 0xFF) break; + + if (value > stopValue) { + this.currentLevel = currentLevel; + // already know about this one, propagating the value to top levels + this.propagateValues(); + return false; } - k += 16; - continue; + + i >>= 1; + j >>= 1; + currentLevel++; } - k += r; - var z = dctZigZag[k]; - zz[z] = receiveAndExtend(s) * (1 << successive); - k++; + this.currentLevel = currentLevel - 1; + return true; + }, + incrementValue: function InclusionTree_incrementValue(stopValue) { + var level = this.levels[this.currentLevel]; + level.items[level.index] = stopValue + 1; + this.propagateValues(); + }, + propagateValues: function InclusionTree_propagateValues() { + var levelIndex = this.currentLevel; + var level = this.levels[levelIndex]; + var currentValue = level.items[level.index]; + while (--levelIndex >= 0) { + var level = this.levels[levelIndex]; + level.items[level.index] = currentValue; + } + }, + nextLevel: function InclusionTree_nextLevel() { + var currentLevel = this.currentLevel; + var level = this.levels[currentLevel]; + var value = level.items[level.index]; + level.items[level.index] = 0xFF; + currentLevel--; + if (currentLevel < 0) + return false; + + this.currentLevel = currentLevel; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + return true; } + }; + return InclusionTree; + })(); + + // Implements C.3. Arithmetic decoding procedures + var ArithmeticDecoder = (function ArithmeticDecoderClosure() { + var QeTable = [ + {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1}, + {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0}, + {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0}, + {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0}, + {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0}, + {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0}, + {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1}, + {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0}, + {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0}, + {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0}, + {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0}, + {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0}, + {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0}, + {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0}, + {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1}, + {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0}, + {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0}, + {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0}, + {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0}, + {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0}, + {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0}, + {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0}, + {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0}, + {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0}, + {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0}, + {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0}, + {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0}, + {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0}, + {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0}, + {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0}, + {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0}, + {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0}, + {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0}, + {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0}, + {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0}, + {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0}, + {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0}, + {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0}, + {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0}, + {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0}, + {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0}, + {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0}, + {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0}, + {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0}, + {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0}, + {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0}, + {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0} + ]; + + function ArithmeticDecoder(data, start, end) { + this.data = data; + this.bp = start; + this.dataEnd = end; + + this.chigh = data[start]; + this.clow = 0; + + this.byteIn(); + + this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F); + this.clow = (this.clow << 7) & 0xFFFF; + this.ct -= 7; + this.a = 0x8000; } - var successiveACState = 0, successiveACNextValue; - function decodeACSuccessive(component, zz) { - var k = spectralStart, e = spectralEnd, r = 0; - while (k <= e) { - var z = dctZigZag[k]; - switch (successiveACState) { - case 0: // initial state - var rs = decodeHuffman(component.huffmanTableAC); - var s = rs & 15, r = rs >> 4; - if (s === 0) { - if (r < 15) { - eobrun = receive(r) + (1 << r); - successiveACState = 4; - } else { - r = 16; - successiveACState = 1; - } + + ArithmeticDecoder.prototype = { + byteIn: function ArithmeticDecoder_byteIn() { + var data = this.data; + var bp = this.bp; + if (data[bp] == 0xFF) { + var b1 = data[bp + 1]; + if (b1 > 0x8F) { + this.clow += 0xFF00; + this.ct = 8; } else { - if (s !== 1) - throw "invalid ACn encoding"; - successiveACNextValue = receiveAndExtend(s); - successiveACState = r ? 2 : 3; + bp++; + this.clow += (data[bp] << 9); + this.ct = 7; + this.bp = bp; } - continue; - case 1: // skipping r zero items - case 2: - if (zz[z]) - zz[z] += (readBit() << successive); - else { - r--; - if (r === 0) - successiveACState = successiveACState == 2 ? 3 : 0; + } else { + bp++; + this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00; + this.ct = 8; + this.bp = bp; + } + if (this.clow > 0xFFFF) { + this.chigh += (this.clow >> 16); + this.clow &= 0xFFFF; + } + }, + readBit: function ArithmeticDecoder_readBit(cx) { + var qeIcx = QeTable[cx.index].qe; + this.a -= qeIcx; + + if (this.chigh < qeIcx) { + var d = this.exchangeLps(cx); + this.renormD(); + return d; + } else { + this.chigh -= qeIcx; + if ((this.a & 0x8000) == 0) { + var d = this.exchangeMps(cx); + this.renormD(); + return d; + } else { + return cx.mps; } - break; - case 3: // set value for a zero item - if (zz[z]) - zz[z] += (readBit() << successive); - else { - zz[z] = successiveACNextValue << successive; - successiveACState = 0; + } + }, + renormD: function ArithmeticDecoder_renormD() { + do { + if (this.ct == 0) + this.byteIn(); + + this.a <<= 1; + this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1); + this.clow = (this.clow << 1) & 0xFFFF; + this.ct--; + } while ((this.a & 0x8000) == 0); + }, + exchangeMps: function ArithmeticDecoder_exchangeMps(cx) { + var d; + var qeTableIcx = QeTable[cx.index]; + if (this.a < qeTableIcx.qe) { + d = 1 - cx.mps; + + if (qeTableIcx.switchFlag == 1) { + cx.mps = 1 - cx.mps; } - break; - case 4: // eob - if (zz[z]) - zz[z] += (readBit() << successive); - break; + cx.index = qeTableIcx.nlps; + } else { + d = cx.mps; + cx.index = qeTableIcx.nmps; } - k++; - } - if (successiveACState === 4) { - eobrun--; - if (eobrun === 0) - successiveACState = 0; + return d; + }, + exchangeLps: function ArithmeticDecoder_exchangeLps(cx) { + var d; + var qeTableIcx = QeTable[cx.index]; + if (this.a < qeTableIcx.qe) { + this.a = qeTableIcx.qe; + d = cx.mps; + cx.index = qeTableIcx.nmps; + } else { + this.a = qeTableIcx.qe; + d = 1 - cx.mps; + + if (qeTableIcx.switchFlag == 1) { + cx.mps = 1 - cx.mps; + } + cx.index = qeTableIcx.nlps; + } + return d; } - } - function decodeMcu(component, decode, mcu, row, col) { - var mcuRow = (mcu / mcusPerLine) | 0; - var mcuCol = mcu % mcusPerLine; - var blockRow = mcuRow * component.v + row; - var blockCol = mcuCol * component.h + col; - decode(component, component.blocks[blockRow][blockCol]); - } - function decodeBlock(component, decode, mcu) { - var blockRow = (mcu / component.blocksPerLine) | 0; - var blockCol = mcu % component.blocksPerLine; - decode(component, component.blocks[blockRow][blockCol]); - } + }; - var componentsLength = components.length; - var component, i, j, k, n; - var decodeFn; - if (progressive) { - if (spectralStart === 0) - decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; - else - decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; - } else { - decodeFn = decodeBaseline; + return ArithmeticDecoder; + })(); + + // Section D. Coefficient bit modeling + var BitModel = (function BitModelClosure() { + // Table D-1 + // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4), + // vv - sum of Vi (0..2), and hh - sum of Hi (0..2) + var LLAndLHContextsLabel = new Uint8Array([ + 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4, + 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, + 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8 + ]); + var HLContextLabel = new Uint8Array([ + 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8, + 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, + 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8 + ]); + var HHContextLabel = new Uint8Array([ + 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5, + 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8, + 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8 + ]); + + // Table D-2 + function calcSignContribution(significance0, sign0, significance1, sign1) { + if (significance1) { + if (!sign1) + return significance0 ? (!sign0 ? 1 : 0) : 1; + else + return significance0 ? (!sign0 ? 0 : -1) : -1; + } else + return significance0 ? (!sign0 ? 1 : -1) : 0; } + // Table D-3 + var SignContextLabels = [ + {contextLabel: 13, xorBit: 0}, + {contextLabel: 12, xorBit: 0}, + {contextLabel: 11, xorBit: 0}, + {contextLabel: 10, xorBit: 0}, + {contextLabel: 9, xorBit: 0}, + {contextLabel: 10, xorBit: 1}, + {contextLabel: 11, xorBit: 1}, + {contextLabel: 12, xorBit: 1}, + {contextLabel: 13, xorBit: 1} + ]; - var mcu = 0, marker; - var mcuExpected; - if (componentsLength == 1) { - mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; - } else { - mcuExpected = mcusPerLine * frame.mcusPerColumn; + function BitModel(width, height, subband, zeroBitPlanes) { + this.width = width; + this.height = height; + + this.contextLabelTable = subband == 'HH' ? HHContextLabel : + subband == 'HL' ? HLContextLabel : LLAndLHContextsLabel; + + var coefficientCount = width * height; + + // coefficients outside the encoding region treated as insignificant + // add border state cells for significanceState + this.neighborsSignificance = new Uint8Array(coefficientCount); + this.coefficentsSign = new Uint8Array(coefficientCount); + this.coefficentsMagnitude = new Uint32Array(coefficientCount); + this.processingFlags = new Uint8Array(coefficientCount); + + var bitsDecoded = new Uint8Array(this.width * this.height); + for (var i = 0, ii = bitsDecoded.length; i < ii; i++) + bitsDecoded[i] = zeroBitPlanes; + this.bitsDecoded = bitsDecoded; + + this.reset(); } - if (!resetInterval) resetInterval = mcuExpected; - var h, v; - while (mcu < mcuExpected) { - // reset interval stuff - for (i = 0; i < componentsLength; i++) - components[i].pred = 0; - eobrun = 0; + BitModel.prototype = { + setDecoder: function BitModel_setDecoder(decoder) { + this.decoder = decoder; + }, + reset: function BitModel_reset() { + this.uniformContext = {index: 46, mps: 0}; + this.runLengthContext = {index: 3, mps: 0}; + this.contexts = []; + this.contexts.push({index: 4, mps: 0}); + for (var i = 1; i <= 16; i++) + this.contexts.push({index: 0, mps: 0}); + }, + setNeighborsSignificance: + function BitModel_setNeighborsSignificance(row, column) { + var neighborsSignificance = this.neighborsSignificance; + var width = this.width, height = this.height; + var index = row * width + column; + if (row > 0) { + if (column > 0) + neighborsSignificance[index - width - 1] += 0x10; + if (column + 1 < width) + neighborsSignificance[index - width + 1] += 0x10; + neighborsSignificance[index - width] += 0x04; + } + if (row + 1 < height) { + if (column > 0) + neighborsSignificance[index + width - 1] += 0x10; + if (column + 1 < width) + neighborsSignificance[index + width + 1] += 0x10; + neighborsSignificance[index + width] += 0x04; + } + if (column > 0) + neighborsSignificance[index - 1] += 0x01; + if (column + 1 < width) + neighborsSignificance[index + 1] += 0x01; + neighborsSignificance[index] |= 0x80; + }, + runSignificancePropogationPass: + function BitModel_runSignificancePropogationPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var contextLabels = this.contextLabels; + var neighborsSignificance = this.neighborsSignificance; + var processingFlags = this.processingFlags; + var contexts = this.contexts; + var labels = this.contextLabelTable; + var bitsDecoded = this.bitsDecoded; + // clear processed flag + var processedInverseMask = ~1; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + for (var q = 0, qq = width * height; q < qq; q++) + processingFlags[q] &= processedInverseMask; + + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + var index = i0 * width + j; + for (var i1 = 0; i1 < 4; i1++, index += width) { + var i = i0 + i1; + if (i >= height) + break; - if (componentsLength == 1) { - component = components[0]; - for (n = 0; n < resetInterval; n++) { - decodeBlock(component, decodeFn, mcu); - mcu++; + if (coefficentsMagnitude[index] || !neighborsSignificance[index]) + continue; + + var contextLabel = labels[neighborsSignificance[index]]; + var cx = contexts[contextLabel]; + var decision = decoder.readBit(cx); + if (decision) { + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + } + bitsDecoded[index]++; + processingFlags[index] |= processedMask; + } + } } - } else { - for (n = 0; n < resetInterval; n++) { - for (i = 0; i < componentsLength; i++) { - component = components[i]; - h = component.h; - v = component.v; - for (j = 0; j < v; j++) { - for (k = 0; k < h; k++) { - decodeMcu(component, decodeFn, mcu, j, k); + }, + decodeSignBit: function BitModel_decodeSignBit(row, column) { + var width = this.width, height = this.height; + var index = row * width + column; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var horizontalContribution = calcSignContribution( + column > 0 && coefficentsMagnitude[index - 1], + coefficentsSign[index - 1], + column + 1 < width && coefficentsMagnitude[index + 1], + coefficentsSign[index + 1]); + var verticalContribution = calcSignContribution( + row > 0 && coefficentsMagnitude[index - width], + coefficentsSign[index - width], + row + 1 < height && coefficentsMagnitude[index + width], + coefficentsSign[index + width]); + + var contextLabelAndXor = SignContextLabels[ + 3 * (1 - horizontalContribution) + (1 - verticalContribution)]; + var contextLabel = contextLabelAndXor.contextLabel; + var cx = this.contexts[contextLabel]; + var decoded = this.decoder.readBit(cx); + return decoded ^ contextLabelAndXor.xorBit; + }, + runMagnitudeRefinementPass: + function BitModel_runMagnitudeRefinementPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var coefficentsMagnitude = this.coefficentsMagnitude; + var neighborsSignificance = this.neighborsSignificance; + var contexts = this.contexts; + var bitsDecoded = this.bitsDecoded; + var processingFlags = this.processingFlags; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + for (var i1 = 0; i1 < 4; i1++) { + var i = i0 + i1; + if (i >= height) + break; + var index = i * width + j; + + // significant but not those that have just become + if (!coefficentsMagnitude[index] || + (processingFlags[index] & processedMask) != 0) + continue; + + var contextLabel = 16; + if ((processingFlags[index] & + firstMagnitudeBitMask) != 0) { + processingFlags[i * width + j] ^= firstMagnitudeBitMask; + // first refinement + var significance = neighborsSignificance[index]; + var sumOfSignificance = (significance & 3) + + ((significance >> 2) & 3) + ((significance >> 4) & 7); + contextLabel = sumOfSignificance >= 1 ? 15 : 14; } + + var cx = contexts[contextLabel]; + var bit = decoder.readBit(cx); + coefficentsMagnitude[index] = + (coefficentsMagnitude[index] << 1) | bit; + bitsDecoded[index]++; + processingFlags[index] |= processedMask; } } - mcu++; } - } + }, + runCleanupPass: function BitModel_runCleanupPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var neighborsSignificance = this.neighborsSignificance; + var significanceState = this.significanceState; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var contexts = this.contexts; + var labels = this.contextLabelTable; + var bitsDecoded = this.bitsDecoded; + var processingFlags = this.processingFlags; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + var oneRowDown = width; + var twoRowsDown = width * 2; + var threeRowsDown = width * 3; + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + var index0 = i0 * width + j; + // using the property: labels[neighborsSignificance[index]] == 0 + // when neighborsSignificance[index] == 0 + var allEmpty = i0 + 3 < height && + processingFlags[index0] == 0 && + processingFlags[index0 + oneRowDown] == 0 && + processingFlags[index0 + twoRowsDown] == 0 && + processingFlags[index0 + threeRowsDown] == 0 && + neighborsSignificance[index0] == 0 && + neighborsSignificance[index0 + oneRowDown] == 0 && + neighborsSignificance[index0 + twoRowsDown] == 0 && + neighborsSignificance[index0 + threeRowsDown] == 0; + var i1 = 0, index = index0; + var cx, i; + if (allEmpty) { + cx = this.runLengthContext; + var hasSignificantCoefficent = decoder.readBit(cx); + if (!hasSignificantCoefficent) { + bitsDecoded[index0]++; + bitsDecoded[index0 + oneRowDown]++; + bitsDecoded[index0 + twoRowsDown]++; + bitsDecoded[index0 + threeRowsDown]++; + continue; // next column + } + cx = this.uniformContext; + i1 = (decoder.readBit(cx) << 1) | decoder.readBit(cx); + i = i0 + i1; + index += i1 * width; + + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + + index = index0; + for (var i2 = i0; i2 <= i; i2++, index += width) + bitsDecoded[index]++; + + i1++; + } + for (; i1 < 4; i1++, index += width) { + i = i0 + i1; + if (i >= height) + break; - // find marker - bitsCount = 0; - marker = (data[offset] << 8) | data[offset + 1]; - if (marker <= 0xFF00) { - throw "marker was not found"; + if (coefficentsMagnitude[index] || + (processingFlags[index] & processedMask) != 0) + continue; + + var contextLabel = labels[neighborsSignificance[index]]; + cx = contexts[contextLabel]; + var decision = decoder.readBit(cx); + if (decision == 1) { + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + } + bitsDecoded[index]++; + } + } + } } + }; - if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx - offset += 2; + return BitModel; + })(); + + // Section F, Discrete wavelet transofrmation + var Transform = (function TransformClosure() { + function Transform() { + } + Transform.prototype.calculate = + function transformCalculate(subbands, u0, v0) { + var ll = subbands[0]; + for (var i = 1, ii = subbands.length, j = 1; i < ii; i += 3, j++) { + ll = this.iterate(ll, subbands[i], subbands[i + 1], + subbands[i + 2], u0, v0); + } + return ll; + }; + Transform.prototype.iterate = function Transform_iterate(ll, hl, lh, hh, + u0, v0) { + var llWidth = ll.width, llHeight = ll.height, llItems = ll.items; + var hlWidth = hl.width, hlHeight = hl.height, hlItems = hl.items; + var lhWidth = lh.width, lhHeight = lh.height, lhItems = lh.items; + var hhWidth = hh.width, hhHeight = hh.height, hhItems = hh.items; + + // Section F.3.3 interleave + var width = llWidth + hlWidth; + var height = llHeight + lhHeight; + var items = new Float32Array(width * height); + for (var i = 0, ii = llHeight; i < ii; i++) { + var k = i * llWidth, l = i * 2 * width; + for (var j = 0, jj = llWidth; j < jj; j++, k++, l += 2) + items[l] = llItems[k]; + } + for (var i = 0, ii = hlHeight; i < ii; i++) { + var k = i * hlWidth, l = i * 2 * width + 1; + for (var j = 0, jj = hlWidth; j < jj; j++, k++, l += 2) + items[l] = hlItems[k]; + } + for (var i = 0, ii = lhHeight; i < ii; i++) { + var k = i * lhWidth, l = (i * 2 + 1) * width; + for (var j = 0, jj = lhWidth; j < jj; j++, k++, l += 2) + items[l] = lhItems[k]; + } + for (var i = 0, ii = hhHeight; i < ii; i++) { + var k = i * hhWidth, l = (i * 2 + 1) * width + 1; + for (var j = 0, jj = hhWidth; j < jj; j++, k++, l += 2) + items[l] = hhItems[k]; + } + + var bufferPadding = 4; + var bufferLength = new Float32Array(Math.max(width, height) + + 2 * bufferPadding); + var buffer = new Float32Array(bufferLength); + var bufferOut = new Float32Array(bufferLength); + + // Section F.3.4 HOR_SR + for (var v = 0; v < height; v++) { + if (width == 1) { + // if width = 1, when u0 even keep items as is, when odd divide by 2 + if ((u0 % 1) != 0) { + items[v * width] /= 2; + } + continue; + } + + var k = v * width; + var l = bufferPadding; + for (var u = 0; u < width; u++, k++, l++) + buffer[l] = items[k]; + + // Section F.3.7 extending... using max extension of 4 + var i1 = bufferPadding - 1, j1 = bufferPadding + 1; + var i2 = bufferPadding + width - 2, j2 = bufferPadding + width; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + + this.filter(buffer, bufferPadding, width, u0, bufferOut); + + k = v * width; + l = bufferPadding; + for (var u = 0; u < width; u++, k++, l++) + items[k] = bufferOut[l]; + } + + // Section F.3.5 VER_SR + for (var u = 0; u < width; u++) { + if (height == 1) { + // if height = 1, when v0 even keep items as is, when odd divide by 2 + if ((v0 % 1) != 0) { + items[u] /= 2; + } + continue; + } + + var k = u; + var l = bufferPadding; + for (var v = 0; v < height; v++, k += width, l++) + buffer[l] = items[k]; + + // Section F.3.7 extending... using max extension of 4 + var i1 = bufferPadding - 1, j1 = bufferPadding + 1; + var i2 = bufferPadding + height - 2, j2 = bufferPadding + height; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + + this.filter(buffer, bufferPadding, height, v0, bufferOut); + + k = u; + l = bufferPadding; + for (var v = 0; v < height; v++, k += width, l++) + items[k] = bufferOut[l]; } - else - break; + return { + width: width, + height: height, + items: items + }; + }; + return Transform; + })(); + + // Section 3.8.2 Irreversible 9-7 filter + var IrreversibleTransform = (function IrreversibleTransformClosure() { + function IrreversibleTransform() { + Transform.call(this); } - return offset - startOffset; - } + IrreversibleTransform.prototype = Object.create(Transform.prototype); + IrreversibleTransform.prototype.filter = + function irreversibleTransformFilter(y, offset, length, i0, x) { + var i0_ = Math.floor(i0 / 2); + var i1_ = Math.floor((i0 + length) / 2); + var offset_ = offset - (i0 % 1); + + var alpha = -1.586134342059924; + var beta = -0.052980118572961; + var gamma = 0.882911075530934; + var delta = 0.443506852043971; + var K = 1.230174104914001; + var K_ = 1 / K; + + // step 1 + var j = offset_ - 2; + for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] = K * y[j]; + + // step 2 + var j = offset_ - 3; + for (var n = i0_ - 2, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] = K_ * y[j]; + + // step 3 + var j = offset_ - 2; + for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] -= delta * (x[j - 1] + x[j + 1]); + + // step 4 + var j = offset_ - 1; + for (var n = i0_ - 1, nn = i1_ + 1; n < nn; n++, j += 2) + x[j] -= gamma * (x[j - 1] + x[j + 1]); + + // step 5 + var j = offset_; + for (var n = i0_, nn = i1_ + 1; n < nn; n++, j += 2) + x[j] -= beta * (x[j - 1] + x[j + 1]); + + // step 6 + var j = offset_ + 1; + for (var n = i0_, nn = i1_; n < nn; n++, j += 2) + x[j] -= alpha * (x[j - 1] + x[j + 1]); + }; - function buildComponentData(frame, component) { - var lines = []; - var blocksPerLine = component.blocksPerLine; - var blocksPerColumn = component.blocksPerColumn; - var samplesPerLine = blocksPerLine << 3; - var R = new Int32Array(64), r = new Uint8Array(64); + return IrreversibleTransform; + })(); - // A port of poppler's IDCT method which in turn is taken from: - // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz, - // "Practical Fast 1-D DCT Algorithms with 11 Multiplications", - // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989, - // 988-991. - function quantizeAndInverse(zz, dataOut, dataIn) { - var qt = component.quantizationTable; - var v0, v1, v2, v3, v4, v5, v6, v7, t; - var p = dataIn; - var i; + // Section 3.8.1 Reversible 5-3 filter + var ReversibleTransform = (function ReversibleTransformClosure() { + function ReversibleTransform() { + Transform.call(this); + } - // dequant - for (i = 0; i < 64; i++) - p[i] = zz[i] * qt[i]; + ReversibleTransform.prototype = Object.create(Transform.prototype); + ReversibleTransform.prototype.filter = + function reversibleTransformFilter(y, offset, length, i0, x) { + var i0_ = Math.floor(i0 / 2); + var i1_ = Math.floor((i0 + length) / 2); + var offset_ = offset - (i0 % 1); - // inverse DCT on rows - for (i = 0; i < 8; ++i) { - var row = 8 * i; + for (var n = i0_, nn = i1_ + 1, j = offset_; n < nn; n++, j += 2) + x[j] = y[j] - Math.floor((y[j - 1] + y[j + 1] + 2) / 4); - // check for all-zero AC coefficients - if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && - p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && - p[7 + row] == 0) { - t = (dctSqrt2 * p[0 + row] + 512) >> 10; - p[0 + row] = t; - p[1 + row] = t; - p[2 + row] = t; - p[3 + row] = t; - p[4 + row] = t; - p[5 + row] = t; - p[6 + row] = t; - p[7 + row] = t; - continue; - } + for (var n = i0_, nn = i1_, j = offset_ + 1; n < nn; n++, j += 2) + x[j] = y[j] + Math.floor((x[j - 1] + x[j + 1]) / 2); + }; - // stage 4 - v0 = (dctSqrt2 * p[0 + row] + 128) >> 8; - v1 = (dctSqrt2 * p[4 + row] + 128) >> 8; - v2 = p[2 + row]; - v3 = p[6 + row]; - v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8; - v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8; - v5 = p[3 + row] << 4; - v6 = p[5 + row] << 4; + return ReversibleTransform; + })(); - // stage 3 - t = (v0 - v1+ 1) >> 1; - v0 = (v0 + v1 + 1) >> 1; - v1 = t; - t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; - v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; - v3 = t; - t = (v4 - v6 + 1) >> 1; - v4 = (v4 + v6 + 1) >> 1; - v6 = t; - t = (v7 + v5 + 1) >> 1; - v5 = (v7 - v5 + 1) >> 1; - v7 = t; + return JpxImage; +})(); - // stage 2 - t = (v0 - v3 + 1) >> 1; - v0 = (v0 + v3 + 1) >> 1; - v3 = t; - t = (v1 - v2 + 1) >> 1; - v1 = (v1 + v2 + 1) >> 1; - v2 = t; - t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; - v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; - v7 = t; - t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; - v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; - v6 = t; +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ - // stage 1 - p[0 + row] = v0 + v7; - p[7 + row] = v0 - v7; - p[1 + row] = v1 + v6; - p[6 + row] = v1 - v6; - p[2 + row] = v2 + v5; - p[5 + row] = v2 - v5; - p[3 + row] = v3 + v4; - p[4 + row] = v3 - v4; - } +'use strict'; - // inverse DCT on columns - for (i = 0; i < 8; ++i) { - var col = i; +var bidi = PDFJS.bidi = (function bidiClosure() { + // Character types for symbols from 0000 to 00FF. + var baseTypes = [ + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS', + 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON', + 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN', + 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON', + 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', + 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN', + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON', + 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON', + 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L' + ]; - // check for all-zero AC coefficients - if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 && - p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 && - p[7*8 + col] == 0) { - t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; - p[0*8 + col] = t; - p[1*8 + col] = t; - p[2*8 + col] = t; - p[3*8 + col] = t; - p[4*8 + col] = t; - p[5*8 + col] = t; - p[6*8 + col] = t; - p[7*8 + col] = t; - continue; - } + // Character types for symbols from 0600 to 06FF + var arabicTypes = [ + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', + 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', + 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', + 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM', + 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL' + ]; - // stage 4 - v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12; - v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12; - v2 = p[2*8 + col]; - v3 = p[6*8 + col]; - v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12; - v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12; - v5 = p[3*8 + col]; - v6 = p[5*8 + col]; + function isOdd(i) { + return (i & 1) != 0; + } + + function isEven(i) { + return (i & 1) == 0; + } + + function findUnequal(arr, start, value) { + var j; + for (var j = start, jj = arr.length; j < jj; ++j) { + if (arr[j] != value) + return j; + } + return j; + } + + function setValues(arr, start, end, value) { + for (var j = start; j < end; ++j) { + arr[j] = value; + } + } + + function reverseValues(arr, start, end) { + for (var i = start, j = end - 1; i < j; ++i, --j) { + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + function mirrorGlyphs(c) { + /* + # BidiMirroring-1.txt + 0028; 0029 # LEFT PARENTHESIS + 0029; 0028 # RIGHT PARENTHESIS + 003C; 003E # LESS-THAN SIGN + 003E; 003C # GREATER-THAN SIGN + 005B; 005D # LEFT SQUARE BRACKET + 005D; 005B # RIGHT SQUARE BRACKET + 007B; 007D # LEFT CURLY BRACKET + 007D; 007B # RIGHT CURLY BRACKET + 00AB; 00BB # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 00BB; 00AB # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + */ + switch (c) { + case '(': + return ')'; + case ')': + return '('; + case '<': + return '>'; + case '>': + return '<'; + case ']': + return '['; + case '[': + return ']'; + case '}': + return '{'; + case '{': + return '}'; + case '\u00AB': + return '\u00BB'; + case '\u00BB': + return '\u00AB'; + default: + return c; + } + } + + function bidi(text, startLevel) { + var str = text.str; + var strLength = str.length; + if (strLength == 0) + return str; + + // get types, fill arrays + + var chars = []; + var types = []; + var oldtypes = []; + var numBidi = 0; + + for (var i = 0; i < strLength; ++i) { + chars[i] = str.charAt(i); + + var charCode = str.charCodeAt(i); + var charType = 'L'; + if (charCode <= 0x00ff) + charType = baseTypes[charCode]; + else if (0x0590 <= charCode && charCode <= 0x05f4) + charType = 'R'; + else if (0x0600 <= charCode && charCode <= 0x06ff) + charType = arabicTypes[charCode & 0xff]; + else if (0x0700 <= charCode && charCode <= 0x08AC) + charType = 'AL'; + + if (charType == 'R' || charType == 'AL' || charType == 'AN') + numBidi++; - // stage 3 - t = (v0 - v1 + 1) >> 1; - v0 = (v0 + v1 + 1) >> 1; - v1 = t; - t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; - v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; - v3 = t; - t = (v4 - v6 + 1) >> 1; - v4 = (v4 + v6 + 1) >> 1; - v6 = t; - t = (v7 + v5 + 1) >> 1; - v5 = (v7 - v5 + 1) >> 1; - v7 = t; + oldtypes[i] = types[i] = charType; + } - // stage 2 - t = (v0 - v3 + 1) >> 1; - v0 = (v0 + v3 + 1) >> 1; - v3 = t; - t = (v1 - v2 + 1) >> 1; - v1 = (v1 + v2 + 1) >> 1; - v2 = t; - t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; - v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; - v7 = t; - t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; - v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; - v6 = t; + // detect the bidi method + // if there are no rtl characters then no bidi needed + // if less than 30% chars are rtl then string is primarily ltr + // if more than 30% chars are rtl then string is primarily rtl + if (numBidi == 0) { + text.direction = 'ltr'; + return str; + } - // stage 1 - p[0*8 + col] = v0 + v7; - p[7*8 + col] = v0 - v7; - p[1*8 + col] = v1 + v6; - p[6*8 + col] = v1 - v6; - p[2*8 + col] = v2 + v5; - p[5*8 + col] = v2 - v5; - p[3*8 + col] = v3 + v4; - p[4*8 + col] = v3 - v4; + if (startLevel == -1) { + if ((strLength / numBidi) < 0.3) { + text.direction = 'ltr'; + startLevel = 0; + } else { + text.direction = 'rtl'; + startLevel = 1; } + } - // convert to 8-bit integers - for (i = 0; i < 64; ++i) { - var sample = 128 + ((p[i] + 8) >> 4); - dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample; - } + var levels = []; + + for (var i = 0; i < strLength; ++i) { + levels[i] = startLevel; } - var i, j; - for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { - var scanLine = blockRow << 3; - for (i = 0; i < 8; i++) - lines.push(new Uint8Array(samplesPerLine)); - for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { - quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); + /* + X1-X10: skip most of this, since we are NOT doing the embeddings. + */ - var offset = 0, sample = blockCol << 3; - for (j = 0; j < 8; j++) { - var line = lines[scanLine + j]; - for (i = 0; i < 8; i++) - line[sample + i] = r[offset++]; - } - } + var e = isOdd(startLevel) ? 'R' : 'L'; + var sor = e; + var eor = sor; + + /* + W1. Examine each non-spacing mark (NSM) in the level run, and change the + type of the NSM to the type of the previous character. If the NSM is at the + start of the level run, it will get the type of sor. + */ + + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'NSM') + types[i] = lastType; + else + lastType = types[i]; } - return lines; - } - constructor.prototype = { - load: function load(path) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", path, true); - xhr.responseType = "arraybuffer"; - xhr.onload = (function() { - // TODO catch parse error - var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); - this.parse(data); - if (this.onload) - this.onload(); - }).bind(this); - xhr.send(null); - }, - parse: function parse(data) { - var offset = 0, length = data.length; - function readUint16() { - var value = (data[offset] << 8) | data[offset + 1]; - offset += 2; - return value; - } - function readDataBlock() { - var length = readUint16(); - var array = data.subarray(offset, offset + length - 2); - offset += array.length; - return array; - } - function prepareComponents(frame) { - var maxH = 0, maxV = 0; - var component, componentId; - for (componentId in frame.components) { - if (frame.components.hasOwnProperty(componentId)) { - component = frame.components[componentId]; - if (maxH < component.h) maxH = component.h; - if (maxV < component.v) maxV = component.v; - } + /* + W2. Search backwards from each instance of a European number until the + first strong type (R, L, AL, or sor) is found. If an AL is found, change + the type of the European number to Arabic number. + */ + + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'EN') + types[i] = (lastType == 'AL') ? 'AN' : 'EN'; + else if (t == 'R' || t == 'L' || t == 'AL') + lastType = t; + } + + /* + W3. Change all ALs to R. + */ + + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'AL') + types[i] = 'R'; + } + + /* + W4. A single European separator between two European numbers changes to a + European number. A single common separator between two numbers of the same + type changes to that type: + */ + + for (var i = 1; i < strLength - 1; ++i) { + if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN') + types[i] = 'EN'; + if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') && + types[i + 1] == types[i - 1]) + types[i] = types[i - 1]; + } + + /* + W5. A sequence of European terminators adjacent to European numbers changes + to all European numbers: + */ + + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'EN') { + // do before + for (var j = i - 1; j >= 0; --j) { + if (types[j] != 'ET') + break; + types[j] = 'EN'; } - var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH); - var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV); - for (componentId in frame.components) { - if (frame.components.hasOwnProperty(componentId)) { - component = frame.components[componentId]; - var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH); - var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV); - var blocksPerLineForMcu = mcusPerLine * component.h; - var blocksPerColumnForMcu = mcusPerColumn * component.v; - var blocks = []; - for (var i = 0; i < blocksPerColumnForMcu; i++) { - var row = []; - for (var j = 0; j < blocksPerLineForMcu; j++) - row.push(new Int32Array(64)); - blocks.push(row); - } - component.blocksPerLine = blocksPerLine; - component.blocksPerColumn = blocksPerColumn; - component.blocks = blocks; - } + // do after + for (var j = i + 1; j < strLength; --j) { + if (types[j] != 'ET') + break; + types[j] = 'EN'; } - frame.maxH = maxH; - frame.maxV = maxV; - frame.mcusPerLine = mcusPerLine; - frame.mcusPerColumn = mcusPerColumn; - } - var jfif = null; - var adobe = null; - var pixels = null; - var frame, resetInterval; - var quantizationTables = [], frames = []; - var huffmanTablesAC = [], huffmanTablesDC = []; - var fileMarker = readUint16(); - if (fileMarker != 0xFFD8) { // SOI (Start of Image) - throw "SOI not found"; } + } - fileMarker = readUint16(); - while (fileMarker != 0xFFD9) { // EOI (End of image) - var i, j, l; - switch(fileMarker) { - case 0xFFE0: // APP0 (Application Specific) - case 0xFFE1: // APP1 - case 0xFFE2: // APP2 - case 0xFFE3: // APP3 - case 0xFFE4: // APP4 - case 0xFFE5: // APP5 - case 0xFFE6: // APP6 - case 0xFFE7: // APP7 - case 0xFFE8: // APP8 - case 0xFFE9: // APP9 - case 0xFFEA: // APP10 - case 0xFFEB: // APP11 - case 0xFFEC: // APP12 - case 0xFFED: // APP13 - case 0xFFEE: // APP14 - case 0xFFEF: // APP15 - case 0xFFFE: // COM (Comment) - var appData = readDataBlock(); + /* + W6. Otherwise, separators and terminators change to Other Neutral: + */ - if (fileMarker === 0xFFE0) { - if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && - appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00' - jfif = { - version: { major: appData[5], minor: appData[6] }, - densityUnits: appData[7], - xDensity: (appData[8] << 8) | appData[9], - yDensity: (appData[10] << 8) | appData[11], - thumbWidth: appData[12], - thumbHeight: appData[13], - thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) - }; - } - } - // TODO APP1 - Exif - if (fileMarker === 0xFFEE) { - if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && - appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00' - adobe = { - version: appData[6], - flags0: (appData[7] << 8) | appData[8], - flags1: (appData[9] << 8) | appData[10], - transformCode: appData[11] - }; - } - } - break; + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS') + types[i] = 'ON'; + } - case 0xFFDB: // DQT (Define Quantization Tables) - var quantizationTableCount = Math.floor((readUint16() - 2) / 65); - for (i = 0; i < quantizationTableCount; i++) { - var quantizationTableSpec = data[offset++]; - var tableData = new Int32Array(64); - if ((quantizationTableSpec >> 4) === 0) { // 8 bit values - for (j = 0; j < 64; j++) { - var z = dctZigZag[j]; - tableData[z] = data[offset++]; - } - } else if ((quantizationTableSpec >> 4) === 1) { //16 bit - tableData[j] = readUint16(); - } else - throw "DQT: invalid table spec"; - quantizationTables[quantizationTableSpec & 15] = tableData; - } - break; + /* + W7. Search backwards from each instance of a European number until the + first strong type (R, L, or sor) is found. If an L is found, then change + the type of the European number to L. + */ - case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT) - case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT) - readUint16(); // skip data length - frame = {}; - frame.progressive = (fileMarker === 0xFFC2); - frame.precision = data[offset++]; - frame.scanLines = readUint16(); - frame.samplesPerLine = readUint16(); - frame.components = []; - var componentsCount = data[offset++], componentId; - var maxH = 0, maxV = 0; - for (i = 0; i < componentsCount; i++) { - componentId = data[offset]; - var h = data[offset + 1] >> 4; - var v = data[offset + 1] & 15; - var qId = data[offset + 2]; - frame.components[componentId] = { - h: h, - v: v, - quantizationTable: quantizationTables[qId] - }; - offset += 3; - } - prepareComponents(frame); - frames.push(frame); - break; + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'EN') + types[i] = (lastType == 'L') ? 'L' : 'EN'; + else if (t == 'R' || t == 'L') + lastType = t; + } + + /* + N1. A sequence of neutrals takes the direction of the surrounding strong + text if the text on both sides has the same direction. European and Arabic + numbers are treated as though they were R. Start-of-level-run (sor) and + end-of-level-run (eor) are used at level run boundaries. + */ + + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'ON') { + var end = findUnequal(types, i + 1, 'ON'); + var before = sor; + if (i > 0) + before = types[i - 1]; + var after = eor; + if (end + 1 < strLength) + after = types[end + 1]; + if (before != 'L') + before = 'R'; + if (after != 'L') + after = 'R'; + if (before == after) + setValues(types, i, end, before); + i = end - 1; // reset to end (-1 so next iteration is ok) + } + } - case 0xFFC4: // DHT (Define Huffman Tables) - var huffmanLength = readUint16(); - for (i = 2; i < huffmanLength;) { - var huffmanTableSpec = data[offset++]; - var codeLengths = new Uint8Array(16); - var codeLengthSum = 0; - for (j = 0; j < 16; j++, offset++) - codeLengthSum += (codeLengths[j] = data[offset]); - var huffmanValues = new Uint8Array(codeLengthSum); - for (j = 0; j < codeLengthSum; j++, offset++) - huffmanValues[j] = data[offset]; - i += 17 + codeLengthSum; + /* + N2. Any remaining neutrals take the embedding direction. + */ - ((huffmanTableSpec >> 4) === 0 ? - huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = - buildHuffmanTable(codeLengths, huffmanValues); - } - break; + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'ON') + types[i] = e; + } - case 0xFFDD: // DRI (Define Restart Interval) - readUint16(); // skip data length - resetInterval = readUint16(); - break; + /* + I1. For all characters with an even (left-to-right) embedding direction, + those of type R go up one level and those of type AN or EN go up two + levels. + I2. For all characters with an odd (right-to-left) embedding direction, + those of type L, EN or AN go up one level. + */ - case 0xFFDA: // SOS (Start of Scan) - var scanLength = readUint16(); - var selectorsCount = data[offset++]; - var components = [], component; - for (i = 0; i < selectorsCount; i++) { - component = frame.components[data[offset++]]; - var tableSpec = data[offset++]; - component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; - component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; - components.push(component); - } - var spectralStart = data[offset++]; - var spectralEnd = data[offset++]; - var successiveApproximation = data[offset++]; - var processed = decodeScan(data, offset, - frame, components, resetInterval, - spectralStart, spectralEnd, - successiveApproximation >> 4, successiveApproximation & 15); - offset += processed; - break; - default: - throw "unknown JPEG marker " + fileMarker.toString(16); + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (isEven(levels[i])) { + if (t == 'R') { + levels[i] += 1; + } else if (t == 'AN' || t == 'EN') { + levels[i] += 2; + } + } else { // isOdd, so + if (t == 'L' || t == 'AN' || t == 'EN') { + levels[i] += 1; } - fileMarker = readUint16(); } - if (frames.length != 1) - throw "only single frame JPEGs supported"; + } - this.width = frame.samplesPerLine; - this.height = frame.scanLines; - this.jfif = jfif; - this.adobe = adobe; - this.components = []; - for (var id in frame.components) { - if (frame.components.hasOwnProperty(id)) { - this.components.push({ - lines: buildComponentData(frame, frame.components[id]), - scaleX: frame.components[id].h / frame.maxH, - scaleY: frame.components[id].v / frame.maxV - }); + /* + L1. On each line, reset the embedding level of the following characters to + the paragraph embedding level: + + segment separators, + paragraph separators, + any sequence of whitespace characters preceding a segment separator or + paragraph separator, and any sequence of white space characters at the end + of the line. + */ + + // don't bother as text is only single line + + /* + L2. From the highest level found in the text to the lowest odd level on + each line, reverse any contiguous sequence of characters that are at that + level or higher. + */ + + // find highest level & lowest odd level + + var highestLevel = -1; + var lowestOddLevel = 99; + for (var i = 0, ii = levels.length; i < ii; ++i) { + var level = levels[i]; + if (highestLevel < level) + highestLevel = level; + if (lowestOddLevel > level && isOdd(level)) + lowestOddLevel = level; + } + + // now reverse between those limits + + for (var level = highestLevel; level >= lowestOddLevel; --level) { + // find segments to reverse + var start = -1; + for (var i = 0, ii = levels.length; i < ii; ++i) { + if (levels[i] < level) { + if (start >= 0) { + reverseValues(chars, start, i); + start = -1; + } + } else if (start < 0) { + start = i; } } - }, - getData: function getData(width, height) { - function clampTo8bit(a) { - return a < 0 ? 0 : a > 255 ? 255 : a; + if (start >= 0) { + reverseValues(chars, start, levels.length); } - var scaleX = this.width / width, scaleY = this.height / height; + } - var component1, component2, component3, component4; - var component1Line, component2Line, component3Line, component4Line; - var x, y; - var offset = 0; - var Y, Cb, Cr, K, C, M, Ye, R, G, B; - var colorTransform; - var dataLength = width * height * this.components.length; - var data = new Uint8Array(dataLength); - switch (this.components.length) { - case 1: - component1 = this.components[0]; - for (y = 0; y < height; y++) { - component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; - for (x = 0; x < width; x++) { - Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + /* + L3. Combining marks applied to a right-to-left base character will at this + point precede their base character. If the rendering engine expects them to + follow the base characters in the final display process, then the ordering + of the marks and the base character must be reversed. + */ - data[offset++] = Y; - } - } - break; - case 3: - // The default transform for three components is true - colorTransform = true; - // The adobe transform marker overrides any previous setting - if (this.adobe && this.adobe.transformCode) - colorTransform = true; - else if (typeof this.colorTransform !== 'undefined') - colorTransform = !!this.colorTransform; + // don't bother for now - component1 = this.components[0]; - component2 = this.components[1]; - component3 = this.components[2]; - for (y = 0; y < height; y++) { - component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; - component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; - component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; - for (x = 0; x < width; x++) { - if (!colorTransform) { - R = component1Line[0 | (x * component1.scaleX * scaleX)]; - G = component2Line[0 | (x * component2.scaleX * scaleX)]; - B = component3Line[0 | (x * component3.scaleX * scaleX)]; - } else { - Y = component1Line[0 | (x * component1.scaleX * scaleX)]; - Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; - Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + /* + L4. A character that possesses the mirrored property as specified by + Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved + directionality of that character is R. + */ - R = clampTo8bit(Y + 1.402 * (Cr - 128)); - G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); - B = clampTo8bit(Y + 1.772 * (Cb - 128)); - } + // don't mirror as characters are already mirrored in the pdf - data[offset++] = R; - data[offset++] = G; - data[offset++] = B; - } - } - break; - case 4: - if (!this.adobe) - throw 'Unsupported color mode (4 components)'; - // The default transform for four components is false - colorTransform = false; - // The adobe transform marker overrides any previous setting - if (this.adobe && this.adobe.transformCode) - colorTransform = true; - else if (typeof this.colorTransform !== 'undefined') - colorTransform = !!this.colorTransform; + // Finally, return string - component1 = this.components[0]; - component2 = this.components[1]; - component3 = this.components[2]; - component4 = this.components[3]; - for (y = 0; y < height; y++) { - component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; - component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; - component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; - component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)]; - for (x = 0; x < width; x++) { - if (!colorTransform) { - C = component1Line[0 | (x * component1.scaleX * scaleX)]; - M = component2Line[0 | (x * component2.scaleX * scaleX)]; - Ye = component3Line[0 | (x * component3.scaleX * scaleX)]; - K = component4Line[0 | (x * component4.scaleX * scaleX)]; - } else { - Y = component1Line[0 | (x * component1.scaleX * scaleX)]; - Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; - Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; - K = component4Line[0 | (x * component4.scaleX * scaleX)]; + var result = ''; + for (var i = 0, ii = chars.length; i < ii; ++i) { + var ch = chars[i]; + if (ch != '<' && ch != '>') + result += ch; + } + return result; + } - C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); - M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); - Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); - } - data[offset++] = C; - data[offset++] = M; - data[offset++] = Ye; - data[offset++] = K; - } - } - break; - default: - throw 'Unsupported color mode'; + return bidi; +})(); + +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +'use strict'; + +var Metadata = PDFJS.Metadata = (function MetadataClosure() { + function Metadata(meta) { + if (typeof meta === 'string') { + var parser = new DOMParser(); + meta = parser.parseFromString(meta, 'application/xml'); + } else if (!(meta instanceof Document)) { + error('Metadata: Invalid metadata object'); + } + + this.metaDocument = meta; + this.metadata = {}; + this.parse(); + } + + Metadata.prototype = { + parse: function Metadata_parse() { + var doc = this.metaDocument; + var rdf = doc.documentElement; + + if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in + rdf = rdf.firstChild; + while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') + rdf = rdf.nextSibling; } - return data; - }, - copyToImageData: function copyToImageData(imageData) { - var width = imageData.width, height = imageData.height; - var imageDataArray = imageData.data; - var data = this.getData(width, height); - var i = 0, j = 0, x, y; - var Y, K, C, M, R, G, B; - switch (this.components.length) { - case 1: - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - Y = data[i++]; - imageDataArray[j++] = Y; - imageDataArray[j++] = Y; - imageDataArray[j++] = Y; - imageDataArray[j++] = 255; - } - } - break; - case 3: - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - R = data[i++]; - G = data[i++]; - B = data[i++]; + var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; + if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) + return; - imageDataArray[j++] = R; - imageDataArray[j++] = G; - imageDataArray[j++] = B; - imageDataArray[j++] = 255; - } - } - break; - case 4: - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - C = data[i++]; - M = data[i++]; - Y = data[i++]; - K = data[i++]; + var childNodes = rdf.childNodes, desc, namespace, entries, entry; - R = 255 - clampTo8bit(C * (1 - K / 255) + K); - G = 255 - clampTo8bit(M * (1 - K / 255) + K); - B = 255 - clampTo8bit(Y * (1 - K / 255) + K); + for (var i = 0, length = childNodes.length; i < length; i++) { + desc = childNodes[i]; + if (desc.nodeName.toLowerCase() !== 'rdf:description') + continue; - imageDataArray[j++] = R; - imageDataArray[j++] = G; - imageDataArray[j++] = B; - imageDataArray[j++] = 255; - } - } - break; - default: - throw 'Unsupported color mode'; + entries = []; + for (var ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { + if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') + entries.push(desc.childNodes[ii]); + } + + for (ii = 0, iLength = entries.length; ii < iLength; ii++) { + var entry = entries[ii]; + var name = entry.nodeName.toLowerCase(); + this.metadata[name] = entry.textContent.trim(); + } } + }, + + get: function Metadata_get(name) { + return this.metadata[name] || null; + }, + + has: function Metadata_has(name) { + return typeof this.metadata[name] !== 'undefined'; } }; - return constructor; + return Metadata; })(); + }).call((typeof window === 'undefined') ? this : window); diff --git a/apps/files_pdfviewer/js/pdfjs/src/bidi.js b/apps/files_pdfviewer/js/pdfjs/src/bidi.js new file mode 100644 index 00000000000..5f18e53030d --- /dev/null +++ b/apps/files_pdfviewer/js/pdfjs/src/bidi.js @@ -0,0 +1,432 @@ +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +'use strict'; + +var bidi = PDFJS.bidi = (function bidiClosure() { + // Character types for symbols from 0000 to 00FF. + var baseTypes = [ + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS', + 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON', + 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN', + 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON', + 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', + 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN', + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', + 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON', + 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON', + 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', + 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L' + ]; + + // Character types for symbols from 0600 to 06FF + var arabicTypes = [ + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', + 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', + 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', + 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM', + 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', + 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL' + ]; + + function isOdd(i) { + return (i & 1) != 0; + } + + function isEven(i) { + return (i & 1) == 0; + } + + function findUnequal(arr, start, value) { + var j; + for (var j = start, jj = arr.length; j < jj; ++j) { + if (arr[j] != value) + return j; + } + return j; + } + + function setValues(arr, start, end, value) { + for (var j = start; j < end; ++j) { + arr[j] = value; + } + } + + function reverseValues(arr, start, end) { + for (var i = start, j = end - 1; i < j; ++i, --j) { + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + function mirrorGlyphs(c) { + /* + # BidiMirroring-1.txt + 0028; 0029 # LEFT PARENTHESIS + 0029; 0028 # RIGHT PARENTHESIS + 003C; 003E # LESS-THAN SIGN + 003E; 003C # GREATER-THAN SIGN + 005B; 005D # LEFT SQUARE BRACKET + 005D; 005B # RIGHT SQUARE BRACKET + 007B; 007D # LEFT CURLY BRACKET + 007D; 007B # RIGHT CURLY BRACKET + 00AB; 00BB # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 00BB; 00AB # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + */ + switch (c) { + case '(': + return ')'; + case ')': + return '('; + case '<': + return '>'; + case '>': + return '<'; + case ']': + return '['; + case '[': + return ']'; + case '}': + return '{'; + case '{': + return '}'; + case '\u00AB': + return '\u00BB'; + case '\u00BB': + return '\u00AB'; + default: + return c; + } + } + + function bidi(text, startLevel) { + var str = text.str; + var strLength = str.length; + if (strLength == 0) + return str; + + // get types, fill arrays + + var chars = []; + var types = []; + var oldtypes = []; + var numBidi = 0; + + for (var i = 0; i < strLength; ++i) { + chars[i] = str.charAt(i); + + var charCode = str.charCodeAt(i); + var charType = 'L'; + if (charCode <= 0x00ff) + charType = baseTypes[charCode]; + else if (0x0590 <= charCode && charCode <= 0x05f4) + charType = 'R'; + else if (0x0600 <= charCode && charCode <= 0x06ff) + charType = arabicTypes[charCode & 0xff]; + else if (0x0700 <= charCode && charCode <= 0x08AC) + charType = 'AL'; + + if (charType == 'R' || charType == 'AL' || charType == 'AN') + numBidi++; + + oldtypes[i] = types[i] = charType; + } + + // detect the bidi method + // if there are no rtl characters then no bidi needed + // if less than 30% chars are rtl then string is primarily ltr + // if more than 30% chars are rtl then string is primarily rtl + if (numBidi == 0) { + text.direction = 'ltr'; + return str; + } + + if (startLevel == -1) { + if ((strLength / numBidi) < 0.3) { + text.direction = 'ltr'; + startLevel = 0; + } else { + text.direction = 'rtl'; + startLevel = 1; + } + } + + var levels = []; + + for (var i = 0; i < strLength; ++i) { + levels[i] = startLevel; + } + + /* + X1-X10: skip most of this, since we are NOT doing the embeddings. + */ + + var e = isOdd(startLevel) ? 'R' : 'L'; + var sor = e; + var eor = sor; + + /* + W1. Examine each non-spacing mark (NSM) in the level run, and change the + type of the NSM to the type of the previous character. If the NSM is at the + start of the level run, it will get the type of sor. + */ + + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'NSM') + types[i] = lastType; + else + lastType = types[i]; + } + + /* + W2. Search backwards from each instance of a European number until the + first strong type (R, L, AL, or sor) is found. If an AL is found, change + the type of the European number to Arabic number. + */ + + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'EN') + types[i] = (lastType == 'AL') ? 'AN' : 'EN'; + else if (t == 'R' || t == 'L' || t == 'AL') + lastType = t; + } + + /* + W3. Change all ALs to R. + */ + + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'AL') + types[i] = 'R'; + } + + /* + W4. A single European separator between two European numbers changes to a + European number. A single common separator between two numbers of the same + type changes to that type: + */ + + for (var i = 1; i < strLength - 1; ++i) { + if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN') + types[i] = 'EN'; + if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') && + types[i + 1] == types[i - 1]) + types[i] = types[i - 1]; + } + + /* + W5. A sequence of European terminators adjacent to European numbers changes + to all European numbers: + */ + + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'EN') { + // do before + for (var j = i - 1; j >= 0; --j) { + if (types[j] != 'ET') + break; + types[j] = 'EN'; + } + // do after + for (var j = i + 1; j < strLength; --j) { + if (types[j] != 'ET') + break; + types[j] = 'EN'; + } + } + } + + /* + W6. Otherwise, separators and terminators change to Other Neutral: + */ + + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS') + types[i] = 'ON'; + } + + /* + W7. Search backwards from each instance of a European number until the + first strong type (R, L, or sor) is found. If an L is found, then change + the type of the European number to L. + */ + + var lastType = sor; + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (t == 'EN') + types[i] = (lastType == 'L') ? 'L' : 'EN'; + else if (t == 'R' || t == 'L') + lastType = t; + } + + /* + N1. A sequence of neutrals takes the direction of the surrounding strong + text if the text on both sides has the same direction. European and Arabic + numbers are treated as though they were R. Start-of-level-run (sor) and + end-of-level-run (eor) are used at level run boundaries. + */ + + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'ON') { + var end = findUnequal(types, i + 1, 'ON'); + var before = sor; + if (i > 0) + before = types[i - 1]; + var after = eor; + if (end + 1 < strLength) + after = types[end + 1]; + if (before != 'L') + before = 'R'; + if (after != 'L') + after = 'R'; + if (before == after) + setValues(types, i, end, before); + i = end - 1; // reset to end (-1 so next iteration is ok) + } + } + + /* + N2. Any remaining neutrals take the embedding direction. + */ + + for (var i = 0; i < strLength; ++i) { + if (types[i] == 'ON') + types[i] = e; + } + + /* + I1. For all characters with an even (left-to-right) embedding direction, + those of type R go up one level and those of type AN or EN go up two + levels. + I2. For all characters with an odd (right-to-left) embedding direction, + those of type L, EN or AN go up one level. + */ + + for (var i = 0; i < strLength; ++i) { + var t = types[i]; + if (isEven(levels[i])) { + if (t == 'R') { + levels[i] += 1; + } else if (t == 'AN' || t == 'EN') { + levels[i] += 2; + } + } else { // isOdd, so + if (t == 'L' || t == 'AN' || t == 'EN') { + levels[i] += 1; + } + } + } + + /* + L1. On each line, reset the embedding level of the following characters to + the paragraph embedding level: + + segment separators, + paragraph separators, + any sequence of whitespace characters preceding a segment separator or + paragraph separator, and any sequence of white space characters at the end + of the line. + */ + + // don't bother as text is only single line + + /* + L2. From the highest level found in the text to the lowest odd level on + each line, reverse any contiguous sequence of characters that are at that + level or higher. + */ + + // find highest level & lowest odd level + + var highestLevel = -1; + var lowestOddLevel = 99; + for (var i = 0, ii = levels.length; i < ii; ++i) { + var level = levels[i]; + if (highestLevel < level) + highestLevel = level; + if (lowestOddLevel > level && isOdd(level)) + lowestOddLevel = level; + } + + // now reverse between those limits + + for (var level = highestLevel; level >= lowestOddLevel; --level) { + // find segments to reverse + var start = -1; + for (var i = 0, ii = levels.length; i < ii; ++i) { + if (levels[i] < level) { + if (start >= 0) { + reverseValues(chars, start, i); + start = -1; + } + } else if (start < 0) { + start = i; + } + } + if (start >= 0) { + reverseValues(chars, start, levels.length); + } + } + + /* + L3. Combining marks applied to a right-to-left base character will at this + point precede their base character. If the rendering engine expects them to + follow the base characters in the final display process, then the ordering + of the marks and the base character must be reversed. + */ + + // don't bother for now + + /* + L4. A character that possesses the mirrored property as specified by + Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved + directionality of that character is R. + */ + + // don't mirror as characters are already mirrored in the pdf + + // Finally, return string + + var result = ''; + for (var i = 0, ii = chars.length; i < ii; ++i) { + var ch = chars[i]; + if (ch != '<' && ch != '>') + result += ch; + } + return result; + } + + return bidi; +})(); + diff --git a/apps/files_pdfviewer/js/pdfjs/src/canvas.js b/apps/files_pdfviewer/js/pdfjs/src/canvas.js old mode 100755 new mode 100644 index 9b3ed0ba9ad..8f29051fdad --- a/apps/files_pdfviewer/js/pdfjs/src/canvas.js +++ b/apps/files_pdfviewer/js/pdfjs/src/canvas.js @@ -6,12 +6,145 @@ // contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. -var CanvasExtraState = (function canvasExtraState() { - function constructor(old) { +var TextRenderingMode = { + FILL: 0, + STROKE: 1, + FILL_STROKE: 2, + INVISIBLE: 3, + FILL_ADD_TO_PATH: 4, + STROKE_ADD_TO_PATH: 5, + FILL_STROKE_ADD_TO_PATH: 6, + ADD_TO_PATH: 7 +}; + +// Minimal font size that would be used during canvas fillText operations. +var MIN_FONT_SIZE = 1; + +function createScratchCanvas(width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; +} + +function addContextCurrentTransform(ctx) { + // If the context doesn't expose a `mozCurrentTransform`, add a JS based on. + if (!ctx.mozCurrentTransform) { + // Store the original context + ctx._originalSave = ctx.save; + ctx._originalRestore = ctx.restore; + ctx._originalRotate = ctx.rotate; + ctx._originalScale = ctx.scale; + ctx._originalTranslate = ctx.translate; + ctx._originalTransform = ctx.transform; + + ctx._transformMatrix = [1, 0, 0, 1, 0, 0]; + ctx._transformStack = []; + + Object.defineProperty(ctx, 'mozCurrentTransform', { + get: function getCurrentTransform() { + return this._transformMatrix; + } + }); + + Object.defineProperty(ctx, 'mozCurrentTransformInverse', { + get: function getCurrentTransformInverse() { + // Calculation done using WolframAlpha: + // http://www.wolframalpha.com/input/? + // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} + + var m = this._transformMatrix; + var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; + + var ad_bc = a * d - b * c; + var bc_ad = b * c - a * d; + + return [ + d / ad_bc, + b / bc_ad, + c / bc_ad, + a / ad_bc, + (d * e - c * f) / bc_ad, + (b * e - a * f) / ad_bc + ]; + } + }); + + ctx.save = function ctxSave() { + var old = this._transformMatrix; + this._transformStack.push(old); + this._transformMatrix = old.slice(0, 6); + + this._originalSave(); + }; + + ctx.restore = function ctxRestore() { + var prev = this._transformStack.pop(); + if (prev) { + this._transformMatrix = prev; + this._originalRestore(); + } + }; + + ctx.translate = function ctxTranslate(x, y) { + var m = this._transformMatrix; + m[4] = m[0] * x + m[2] * y + m[4]; + m[5] = m[1] * x + m[3] * y + m[5]; + + this._originalTranslate(x, y); + }; + + ctx.scale = function ctxScale(x, y) { + var m = this._transformMatrix; + m[0] = m[0] * x; + m[1] = m[1] * x; + m[2] = m[2] * y; + m[3] = m[3] * y; + + this._originalScale(x, y); + }; + + ctx.transform = function ctxTransform(a, b, c, d, e, f) { + var m = this._transformMatrix; + this._transformMatrix = [ + m[0] * a + m[2] * b, + m[1] * a + m[3] * b, + m[0] * c + m[2] * d, + m[1] * c + m[3] * d, + m[0] * e + m[2] * f + m[4], + m[1] * e + m[3] * f + m[5] + ]; + + ctx._originalTransform(a, b, c, d, e, f); + }; + + ctx.rotate = function ctxRotate(angle) { + var cosValue = Math.cos(angle); + var sinValue = Math.sin(angle); + + var m = this._transformMatrix; + this._transformMatrix = [ + m[0] * cosValue + m[2] * sinValue, + m[1] * cosValue + m[3] * sinValue, + m[0] * (-sinValue) + m[2] * cosValue, + m[1] * (-sinValue) + m[3] * cosValue, + m[4], + m[5] + ]; + + this._originalRotate(angle); + }; + } +} + +var CanvasExtraState = (function CanvasExtraStateClosure() { + function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; + this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; + this.fontMatrix = IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; @@ -23,6 +156,7 @@ var CanvasExtraState = (function canvasExtraState() { this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; + this.textRenderingMode = TextRenderingMode.FILL; // Color spaces this.fillColorSpace = new DeviceGrayCS(); this.fillColorSpaceObj = null; @@ -36,47 +170,40 @@ var CanvasExtraState = (function canvasExtraState() { // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; + this.lineWidth = 1; this.old = old; } - constructor.prototype = { - clone: function canvasextra_clone() { + CanvasExtraState.prototype = { + clone: function CanvasExtraState_clone() { return Object.create(this); }, - setCurrentPoint: function canvasextra_setCurrentPoint(x, y) { + setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; - return constructor; + return CanvasExtraState; })(); -function ScratchCanvas(width, height) { - var canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - return canvas; -} - -var CanvasGraphics = (function canvasGraphics() { - // Defines the time the executeIRQueue is going to be executing +var CanvasGraphics = (function CanvasGraphicsClosure() { + // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. - var kExecutionTime = 50; - - // Number of IR commands to execute before checking - // if we execute longer then `kExecutionTime`. - var kExecutionTimeCheck = 500; + var kExecutionTime = 15; - function constructor(canvasCtx, objs) { + function CanvasGraphics(canvasCtx, objs, textLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.res = null; this.xobjs = null; - this.ScratchCanvas = ScratchCanvas; this.objs = objs; + this.textLayer = textLayer; + if (canvasCtx) { + addContextCurrentTransform(canvasCtx); + } } var LINE_CAP_STYLES = ['butt', 'round', 'square']; @@ -84,8 +211,37 @@ var CanvasGraphics = (function canvasGraphics() { var NORMAL_CLIP = {}; var EO_CLIP = {}; - constructor.prototype = { - beginDrawing: function canvasGraphicsBeginDrawing(mediaBox) { + CanvasGraphics.prototype = { + slowCommands: { + 'stroke': true, + 'closeStroke': true, + 'fill': true, + 'eoFill': true, + 'fillStroke': true, + 'eoFillStroke': true, + 'closeFillStroke': true, + 'closeEOFillStroke': true, + 'showText': true, + 'showSpacedText': true, + 'setStrokeColorSpace': true, + 'setFillColorSpace': true, + 'setStrokeColor': true, + 'setStrokeColorN': true, + 'setFillColor': true, + 'setFillColorN': true, + 'setStrokeGray': true, + 'setFillGray': true, + 'setStrokeRGBColor': true, + 'setFillRGBColor': true, + 'setStrokeCMYKColor': true, + 'setFillCMYKColor': true, + 'paintJpegXObject': true, + 'paintImageXObject': true, + 'paintImageMaskXObject': true, + 'shadingFill': true + }, + + beginDrawing: function CanvasGraphics_beginDrawing(mediaBox) { var cw = this.ctx.canvas.width, ch = this.ctx.canvas.height; this.ctx.save(); switch (mediaBox.rotate) { @@ -102,43 +258,63 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.transform(0, -1, -1, 0, cw, ch); break; } + // Scale so that canvas units are the same as PDF user space units this.ctx.scale(cw / mediaBox.width, ch / mediaBox.height); + // Move the media left-top corner to the (0,0) canvas position + this.ctx.translate(-mediaBox.x, -mediaBox.y); + + if (this.textLayer) + this.textLayer.beginLayout(); }, - executeIRQueue: function canvasGraphicsExecuteIRQueue(codeIR, - executionStartIdx, continueCallback) { - var argsArray = codeIR.argsArray; - var fnArray = codeIR.fnArray; + executeOperatorList: function CanvasGraphics_executeOperatorList( + operatorList, + executionStartIdx, continueCallback, + stepper) { + var argsArray = operatorList.argsArray; + var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; + // Sometimes the OperatorList to execute is empty. + if (argsArrayLen == i) { + return i; + } + var executionEndIdx; - var startTime = Date.now(); + var endTime = Date.now() + kExecutionTime; var objs = this.objs; + var fnName; + var slowCommands = this.slowCommands; - do { - executionEndIdx = Math.min(argsArrayLen, i + kExecutionTimeCheck); - - for (i; i < executionEndIdx; i++) { - if (fnArray[i] !== 'dependency') { - this[fnArray[i]].apply(this, argsArray[i]); - } else { - var deps = argsArray[i]; - for (var n = 0, nn = deps.length; n < nn; n++) { - var depObjId = deps[n]; - - // If the promise isn't resolved yet, add the continueCallback - // to the promise and bail out. - if (!objs.isResolved(depObjId)) { - objs.get(depObjId, continueCallback); - return i; - } + while (true) { + if (stepper && i === stepper.nextBreakPoint) { + stepper.breakIt(i, continueCallback); + return i; + } + + fnName = fnArray[i]; + + if (fnName !== 'dependency') { + this[fnName].apply(this, argsArray[i]); + } else { + var deps = argsArray[i]; + for (var n = 0, nn = deps.length; n < nn; n++) { + var depObjId = deps[n]; + + // If the promise isn't resolved yet, add the continueCallback + // to the promise and bail out. + if (!objs.isResolved(depObjId)) { + objs.get(depObjId, continueCallback); + return i; } } } - // If the entire IRQueue was executed, stop as were done. + i++; + + // If the entire operatorList was executed, stop as were done. if (i == argsArrayLen) { return i; } @@ -146,44 +322,50 @@ var CanvasGraphics = (function canvasGraphics() { // If the execution took longer then a certain amount of time, shedule // to continue exeution after a short delay. // However, this is only possible if a 'continueCallback' is passed in. - if (continueCallback && (Date.now() - startTime) > kExecutionTime) { + if (continueCallback && slowCommands[fnName] && Date.now() > endTime) { setTimeout(continueCallback, 0); return i; } - // If the IRQueue isn't executed completly yet OR the execution time - // was short enough, do another execution round. - } while (true); + // If the operatorList isn't executed completely yet OR the execution + // time was short enough, do another execution round. + } }, - endDrawing: function canvasGraphicsEndDrawing() { + endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); + + if (this.textLayer) + this.textLayer.endLayout(); }, // Graphics state - setLineWidth: function canvasGraphicsSetLineWidth(width) { + setLineWidth: function CanvasGraphics_setLineWidth(width) { + this.current.lineWidth = width; this.ctx.lineWidth = width; }, - setLineCap: function canvasGraphicsSetLineCap(style) { + setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, - setLineJoin: function canvasGraphicsSetLineJoin(style) { + setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, - setMiterLimit: function canvasGraphicsSetMiterLimit(limit) { + setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, - setDash: function canvasGraphicsSetDash(dashArray, dashPhase) { + setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { this.ctx.mozDash = dashArray; this.ctx.mozDashOffset = dashPhase; + this.ctx.webkitLineDash = dashArray; + this.ctx.webkitLineDashOffset = dashPhase; }, - setRenderingIntent: function canvasGraphicsSetRenderingIntent(intent) { + setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { TODO('set rendering intent: ' + intent); }, - setFlatness: function canvasGraphicsSetFlatness(flatness) { + setFlatness: function CanvasGraphics_setFlatness(flatness) { TODO('set flatness: ' + flatness); }, - setGState: function canvasGraphicsSetGState(states) { + setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; @@ -224,55 +406,57 @@ var CanvasGraphics = (function canvasGraphics() { } } }, - save: function canvasGraphicsSave() { + save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); }, - restore: function canvasGraphicsRestore() { + restore: function CanvasGraphics_restore() { var prev = this.stateStack.pop(); if (prev) { this.current = prev; this.ctx.restore(); } }, - transform: function canvasGraphicsTransform(a, b, c, d, e, f) { + transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); }, // Path - moveTo: function canvasGraphicsMoveTo(x, y) { + moveTo: function CanvasGraphics_moveTo(x, y) { this.ctx.moveTo(x, y); this.current.setCurrentPoint(x, y); }, - lineTo: function canvasGraphicsLineTo(x, y) { + lineTo: function CanvasGraphics_lineTo(x, y) { this.ctx.lineTo(x, y); this.current.setCurrentPoint(x, y); }, - curveTo: function canvasGraphicsCurveTo(x1, y1, x2, y2, x3, y3) { + curveTo: function CanvasGraphics_curveTo(x1, y1, x2, y2, x3, y3) { this.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3); this.current.setCurrentPoint(x3, y3); }, - curveTo2: function canvasGraphicsCurveTo2(x2, y2, x3, y3) { + curveTo2: function CanvasGraphics_curveTo2(x2, y2, x3, y3) { var current = this.current; this.ctx.bezierCurveTo(current.x, current.y, x2, y2, x3, y3); current.setCurrentPoint(x3, y3); }, - curveTo3: function canvasGraphicsCurveTo3(x1, y1, x3, y3) { + curveTo3: function CanvasGraphics_curveTo3(x1, y1, x3, y3) { this.curveTo(x1, y1, x3, y3, x3, y3); this.current.setCurrentPoint(x3, y3); }, - closePath: function canvasGraphicsClosePath() { + closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, - rectangle: function canvasGraphicsRectangle(x, y, width, height) { + rectangle: function CanvasGraphics_rectangle(x, y, width, height) { this.ctx.rect(x, y, width, height); }, - stroke: function canvasGraphicsStroke(consumePath) { + stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; + if (this.current.lineWidth === 0) + ctx.lineWidth = this.getSinglePixelWidth(); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; @@ -292,11 +476,11 @@ var CanvasGraphics = (function canvasGraphics() { // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, - closeStroke: function canvasGraphicsCloseStroke() { + closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, - fill: function canvasGraphicsFill(consumePath) { + fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; @@ -313,126 +497,204 @@ var CanvasGraphics = (function canvasGraphics() { if (consumePath) this.consumePath(); }, - eoFill: function canvasGraphicsEoFill() { + eoFill: function CanvasGraphics_eoFill() { var savedFillRule = this.setEOFillRule(); this.fill(); this.restoreFillRule(savedFillRule); }, - fillStroke: function canvasGraphicsFillStroke() { + fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, - eoFillStroke: function canvasGraphicsEoFillStroke() { + eoFillStroke: function CanvasGraphics_eoFillStroke() { var savedFillRule = this.setEOFillRule(); this.fillStroke(); this.restoreFillRule(savedFillRule); }, - closeFillStroke: function canvasGraphicsCloseFillStroke() { + closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, - closeEOFillStroke: function canvasGraphicsCloseEOFillStroke() { + closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { var savedFillRule = this.setEOFillRule(); this.closePath(); this.fillStroke(); this.restoreFillRule(savedFillRule); }, - endPath: function canvasGraphicsEndPath() { + endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping - clip: function canvasGraphicsClip() { + clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, - eoClip: function canvasGraphicsEoClip() { + eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text - beginText: function canvasGraphicsBeginText() { + beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, - endText: function canvasGraphicsEndText() { + endText: function CanvasGraphics_endText() { }, - setCharSpacing: function canvasGraphicsSetCharSpacing(spacing) { + setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, - setWordSpacing: function canvasGraphicsSetWordSpacing(spacing) { + setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, - setHScale: function canvasGraphicsSetHScale(scale) { + setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, - setLeading: function canvasGraphicsSetLeading(leading) { + setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, - setFont: function canvasGraphicsSetFont(fontRefName, size) { - var fontObj = this.objs.get(fontRefName).fontObj; + setFont: function CanvasGraphics_setFont(fontRefName, size) { + var fontObj = this.objs.get(fontRefName); + var current = this.current; + + if (!fontObj) + error('Can\'t find font for ' + fontRefName); + + // Slice-clone matrix so we can manipulate it without affecting original + if (fontObj.fontMatrix) + current.fontMatrix = fontObj.fontMatrix.slice(0); + else + current.fontMatrix = IDENTITY_MATRIX.slice(0); - if (!fontObj) { - throw 'Can\'t find font for ' + fontRefName; + // A valid matrix needs all main diagonal elements to be non-zero + // This also ensures we bypass FF bugzilla bug #719844. + if (current.fontMatrix[0] === 0 || + current.fontMatrix[3] === 0) { + warn('Invalid font matrix for font ' + fontRefName); } - var name = fontObj.loadedName || 'sans-serif'; + // The spec for Tf (setFont) says that 'size' specifies the font 'scale', + // and in some docs this can be negative (inverted x-y axes). + // We implement this condition with fontMatrix. + if (size < 0) { + size = -size; + current.fontMatrix[0] *= -1; + current.fontMatrix[3] *= -1; + } this.current.font = fontObj; this.current.fontSize = size; + if (fontObj.coded) + return; // we don't need ctx.font for Type3 fonts + var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; - var serif = fontObj.serif ? 'serif' : 'sans-serif'; + var serif = fontObj.isSerifFont ? 'serif' : 'sans-serif'; var typeface = '"' + name + '", ' + serif; - var rule = italic + ' ' + bold + ' ' + size + 'px ' + typeface; + + // Some font backends cannot handle fonts below certain size. + // Keeping the font at minimal size and using the fontSizeScale to change + // the current transformation matrix before the fillText/strokeText. + // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 + var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE; + this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 : + size / MIN_FONT_SIZE; + + var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, - setTextRenderingMode: function canvasGraphicsSetTextRenderingMode(mode) { - TODO('text rendering mode: ' + mode); + setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { + if (mode >= TextRenderingMode.FILL_ADD_TO_PATH) + TODO('unsupported text rendering mode: ' + mode); + this.current.textRenderingMode = mode; }, - setTextRise: function canvasGraphicsSetTextRise(rise) { + setTextRise: function CanvasGraphics_setTextRise(rise) { TODO('text rise: ' + rise); }, - moveText: function canvasGraphicsMoveText(x, y) { + moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, - setLeadingMoveText: function canvasGraphicsSetLeadingMoveText(x, y) { + setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, - setTextMatrix: function canvasGraphicsSetTextMatrix(a, b, c, d, e, f) { + setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, - nextLine: function canvasGraphicsNextLine() { + nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, - showText: function canvasGraphicsShowText(text) { + applyTextTransforms: function CanvasGraphics_applyTextTransforms() { + var ctx = this.ctx; + var current = this.current; + var textHScale = current.textHScale; + var fontMatrix = current.fontMatrix || IDENTITY_MATRIX; + + ctx.transform.apply(ctx, current.textMatrix); + ctx.scale(1, -1); + ctx.translate(current.x, -1 * current.y); + ctx.transform.apply(ctx, fontMatrix); + ctx.scale(textHScale, 1); + }, + getTextGeometry: function CanvasGraphics_getTextGeometry() { + var geometry = {}; + var ctx = this.ctx; + var font = this.current.font; + var ctxMatrix = ctx.mozCurrentTransform; + if (ctxMatrix) { + var bl = Util.applyTransform([0, 0], ctxMatrix); + var tr = Util.applyTransform([1, 1], ctxMatrix); + geometry.x = bl[0]; + geometry.y = bl[1]; + geometry.hScale = tr[0] - bl[0]; + geometry.vScale = tr[1] - bl[1]; + } + geometry.spaceWidth = font.spaceWidth; + return geometry; + }, + + showText: function CanvasGraphics_showText(str, skipTextSelection) { var ctx = this.ctx; var current = this.current; var font = current.font; - var glyphs = font.charsToGlyphs(text); + var glyphs = font.charsToGlyphs(str); var fontSize = current.fontSize; + var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale; + var fontMatrix = current.fontMatrix || IDENTITY_MATRIX; + var textHScale2 = textHScale * fontMatrix[0]; var glyphsLength = glyphs.length; + var textLayer = this.textLayer; + var text = {str: '', length: 0, canvasWidth: 0, geom: {}}; + var textSelection = textLayer && !skipTextSelection ? true : false; + var textRenderingMode = current.textRenderingMode; + + // Type3 fonts - each glyph is a "mini-PDF" if (font.coded) { ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); - var fontMatrix = font.fontMatrix || IDENTITY_MATRIX; - ctx.scale(1 / textHScale, 1); + ctx.scale(textHScale, 1); + + if (textSelection) { + this.save(); + ctx.scale(1, -1); + text.geom = this.getTextGeometry(); + this.restore(); + } for (var i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; @@ -445,85 +707,183 @@ var CanvasGraphics = (function canvasGraphics() { this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); - this.executeIRQueue(glyph.codeIRQueue); + this.executeOperatorList(glyph.operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); - var width = transformed[0] * fontSize + charSpacing; + var width = transformed[0] * fontSize + + Util.sign(current.fontMatrix[0]) * charSpacing; ctx.translate(width, 0); - current.x += width; + current.x += width * textHScale; + text.str += glyph.unicode; + text.length++; + text.canvasWidth += width; } ctx.restore(); } else { ctx.save(); - ctx.transform.apply(ctx, current.textMatrix); - ctx.scale(1, -1); - ctx.translate(current.x, -1 * current.y); - ctx.transform.apply(ctx, font.fontMatrix || IDENTITY_MATRIX); + this.applyTextTransforms(); + + var lineWidth = current.lineWidth; + var scale = Math.abs(current.textMatrix[0] * fontMatrix[0]); + if (scale == 0 || lineWidth == 0) + lineWidth = this.getSinglePixelWidth(); + else + lineWidth /= scale; - ctx.scale(1 / textHScale, 1); + if (textSelection) + text.geom = this.getTextGeometry(); - var width = 0; + if (fontSizeScale != 1.0) { + ctx.scale(fontSizeScale, fontSizeScale); + lineWidth /= fontSizeScale; + } + + ctx.lineWidth = lineWidth; + + var x = 0; for (var i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break - width += wordSpacing; + x += Util.sign(current.fontMatrix[0]) * wordSpacing; continue; } - var unicode = glyph.unicode; - var char = (unicode >= 0x10000) ? - String.fromCharCode(0xD800 | ((unicode - 0x10000) >> 10), - 0xDC00 | (unicode & 0x3FF)) : String.fromCharCode(unicode); + var character = glyph.fontChar; + var charWidth = glyph.width * fontSize * 0.001 + + Util.sign(current.fontMatrix[0]) * charSpacing; + + if (!glyph.disabled) { + var scaledX = x / fontSizeScale; + switch (textRenderingMode) { + default: // other unsupported rendering modes + case TextRenderingMode.FILL: + case TextRenderingMode.FILL_ADD_TO_PATH: + ctx.fillText(character, scaledX, 0); + break; + case TextRenderingMode.STROKE: + case TextRenderingMode.STROKE_ADD_TO_PATH: + ctx.strokeText(character, scaledX, 0); + break; + case TextRenderingMode.FILL_STROKE: + case TextRenderingMode.FILL_STROKE_ADD_TO_PATH: + ctx.fillText(character, scaledX, 0); + ctx.strokeText(character, scaledX, 0); + break; + case TextRenderingMode.INVISIBLE: + break; + } + } - ctx.fillText(char, width, 0); - width += glyph.width * fontSize * 0.001 + charSpacing; + x += charWidth; + + var glyphUnicode = glyph.unicode === ' ' ? '\u00A0' : glyph.unicode; + var glyphUnicodeLength = glyphUnicode.length; + //reverse an arabic ligature + if (glyphUnicodeLength > 1 && + isRTLRangeFor(glyphUnicode.charCodeAt(0))) { + for (var ii = glyphUnicodeLength - 1; ii >= 0; ii--) + text.str += glyphUnicode[ii]; + } else + text.str += glyphUnicode; + text.length += glyphUnicodeLength; + text.canvasWidth += charWidth; } - current.x += width; - + current.x += x * textHScale2; ctx.restore(); } - }, - showSpacedText: function canvasGraphicsShowSpacedText(arr) { + if (textSelection) + this.textLayer.appendText(text, font.loadedName, fontSize); + + return text; + }, + showSpacedText: function CanvasGraphics_showSpacedText(arr) { var ctx = this.ctx; var current = this.current; + var font = current.font; var fontSize = current.fontSize; var textHScale = current.textHScale; + if (!font.coded) + textHScale *= (current.fontMatrix || IDENTITY_MATRIX)[0]; var arrLength = arr.length; + var textLayer = this.textLayer; + var text = {str: '', length: 0, canvasWidth: 0, geom: {}}; + var textSelection = textLayer ? true : false; + + if (textSelection) { + ctx.save(); + // Type3 fonts - each glyph is a "mini-PDF" (see also showText) + if (font.coded) { + ctx.transform.apply(ctx, current.textMatrix); + ctx.scale(1, -1); + ctx.translate(current.x, -1 * current.y); + ctx.scale(textHScale, 1); + } else + this.applyTextTransforms(); + text.geom = this.getTextGeometry(); + ctx.restore(); + } + for (var i = 0; i < arrLength; ++i) { var e = arr[i]; if (isNum(e)) { - current.x -= e * 0.001 * fontSize * textHScale; + var spacingLength = -e * 0.001 * fontSize * textHScale; + current.x += spacingLength; + + if (textSelection) { + // Emulate precise spacing via HTML spaces + text.canvasWidth += spacingLength; + if (e < 0 && text.geom.spaceWidth > 0) { // avoid div by zero + var numFakeSpaces = Math.round(-e / text.geom.spaceWidth); + if (numFakeSpaces > 0) { + text.str += '\u00A0'; + text.length++; + } + } + } } else if (isString(e)) { - this.showText(e); + var shownText = this.showText(e, true); + + if (textSelection) { + if (shownText.str === ' ') { + text.str += '\u00A0'; + } else { + text.str += shownText.str; + } + text.canvasWidth += shownText.canvasWidth; + text.length += shownText.length; + } } else { malformed('TJ array element ' + e + ' is not string or num'); } } + + if (textSelection) + this.textLayer.appendText(text, font.loadedName, fontSize); }, - nextLineShowText: function canvasGraphicsNextLineShowText(text) { + nextLineShowText: function CanvasGraphics_nextLineShowText(text) { this.nextLine(); this.showText(text); }, nextLineSetSpacingShowText: - function canvasGraphicsNextLineSetSpacingShowText(wordSpacing, - charSpacing, - text) { + function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing, + charSpacing, + text) { this.setWordSpacing(wordSpacing); this.setCharSpacing(charSpacing); this.nextLineShowText(text); }, // Type3 fonts - setCharWidth: function canvasGraphicsSetCharWidth(xWidth, yWidth) { + setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, - setCharWidthAndBounds: function canvasGraphicsSetCharWidthAndBounds(xWidth, + setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, @@ -537,20 +897,20 @@ var CanvasGraphics = (function canvasGraphics() { }, // Color - setStrokeColorSpace: function canvasGraphicsSetStrokeColorSpace(raw) { + setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) { this.current.strokeColorSpace = ColorSpace.fromIR(raw); }, - setFillColorSpace: function canvasGraphicsSetFillColorSpace(raw) { + setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) { this.current.fillColorSpace = ColorSpace.fromIR(raw); }, - setStrokeColor: function canvasGraphicsSetStrokeColor(/*...*/) { + setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) { var cs = this.current.strokeColorSpace; - var color = cs.getRgb(arguments); - var color = Util.makeCssRgb.apply(null, cs.getRgb(arguments)); + var rgbColor = cs.getRgb(arguments); + var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, - getColorN_IR_Pattern: function canvasGraphicsGetColorN_IR_Pattern(IR, cs) { + getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) { if (IR[0] == 'TilingPattern') { var args = IR[1]; var base = cs.base; @@ -566,37 +926,38 @@ var CanvasGraphics = (function canvasGraphics() { } var pattern = new TilingPattern(IR, color, this.ctx, this.objs); } else if (IR[0] == 'RadialAxial' || IR[0] == 'Dummy') { - var pattern = Pattern.shadingFromIR(this.ctx, IR); + var pattern = Pattern.shadingFromIR(IR); } else { - throw 'Unkown IR type'; + error('Unkown IR type ' + IR[0]); } return pattern; }, - setStrokeColorN_IR: function canvasGraphicsSetStrokeColorN(/*...*/) { + setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { var cs = this.current.strokeColorSpace; if (cs.name == 'Pattern') { - this.current.strokeColor = this.getColorN_IR_Pattern(arguments, cs); + this.current.strokeColor = this.getColorN_Pattern(arguments, cs); } else { this.setStrokeColor.apply(this, arguments); } }, - setFillColor: function canvasGraphicsSetFillColor(/*...*/) { + setFillColor: function CanvasGraphics_setFillColor(/*...*/) { var cs = this.current.fillColorSpace; - var color = Util.makeCssRgb.apply(null, cs.getRgb(arguments)); + var rgbColor = cs.getRgb(arguments); + var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); this.ctx.fillStyle = color; this.current.fillColor = color; }, - setFillColorN_IR: function canvasGraphicsSetFillColorN(/*...*/) { + setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { var cs = this.current.fillColorSpace; if (cs.name == 'Pattern') { - this.current.fillColor = this.getColorN_IR_Pattern(arguments, cs); + this.current.fillColor = this.getColorN_Pattern(arguments, cs); } else { this.setFillColor.apply(this, arguments); } }, - setStrokeGray: function canvasGraphicsSetStrokeGray(gray) { + setStrokeGray: function CanvasGraphics_setStrokeGray(gray) { if (!(this.current.strokeColorSpace instanceof DeviceGrayCS)) this.current.strokeColorSpace = new DeviceGrayCS(); @@ -604,7 +965,7 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.strokeStyle = color; this.current.strokeColor = color; }, - setFillGray: function canvasGraphicsSetFillGray(gray) { + setFillGray: function CanvasGraphics_setFillGray(gray) { if (!(this.current.fillColorSpace instanceof DeviceGrayCS)) this.current.fillColorSpace = new DeviceGrayCS(); @@ -612,7 +973,7 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.fillStyle = color; this.current.fillColor = color; }, - setStrokeRGBColor: function canvasGraphicsSetStrokeRGBColor(r, g, b) { + setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { if (!(this.current.strokeColorSpace instanceof DeviceRgbCS)) this.current.strokeColorSpace = new DeviceRgbCS(); @@ -620,7 +981,7 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.strokeStyle = color; this.current.strokeColor = color; }, - setFillRGBColor: function canvasGraphicsSetFillRGBColor(r, g, b) { + setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { if (!(this.current.fillColorSpace instanceof DeviceRgbCS)) this.current.fillColorSpace = new DeviceRgbCS(); @@ -628,7 +989,7 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.fillStyle = color; this.current.fillColor = color; }, - setStrokeCMYKColor: function canvasGraphicsSetStrokeCMYKColor(c, m, y, k) { + setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) { if (!(this.current.strokeColorSpace instanceof DeviceCmykCS)) this.current.strokeColorSpace = new DeviceCmykCS(); @@ -636,7 +997,7 @@ var CanvasGraphics = (function canvasGraphics() { this.ctx.strokeStyle = color; this.current.strokeColor = color; }, - setFillCMYKColor: function canvasGraphicsSetFillCMYKColor(c, m, y, k) { + setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) { if (!(this.current.fillColorSpace instanceof DeviceCmykCS)) this.current.fillColorSpace = new DeviceCmykCS(); @@ -645,11 +1006,12 @@ var CanvasGraphics = (function canvasGraphics() { this.current.fillColor = color; }, - shadingFill: function canvasGraphicsShadingFill(patternIR) { + shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); - ctx.fillStyle = Pattern.shadingFromIR(ctx, patternIR); + var pattern = Pattern.shadingFromIR(patternIR); + ctx.fillStyle = pattern.getPattern(ctx); var inv = ctx.mozCurrentTransformInverse; if (inv) { @@ -658,9 +1020,9 @@ var CanvasGraphics = (function canvasGraphics() { var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); - var br = Util.applyTransform([0, width], inv); - var ul = Util.applyTransform([height, 0], inv); - var ur = Util.applyTransform([height, width], inv); + var br = Util.applyTransform([0, height], inv); + var ul = Util.applyTransform([width, 0], inv); + var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); @@ -682,14 +1044,14 @@ var CanvasGraphics = (function canvasGraphics() { }, // Images - beginInlineImage: function canvasGraphicsBeginInlineImage() { + beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, - beginImageData: function canvasGraphicsBeginImageData() { + beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, - paintFormXObjectBegin: function canvasGraphicsPaintFormXObjectBegin(matrix, + paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); @@ -705,13 +1067,13 @@ var CanvasGraphics = (function canvasGraphics() { } }, - paintFormXObjectEnd: function canvasGraphicsPaintFormXObjectEnd() { + paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); }, - paintJpegXObject: function canvasGraphicsPaintJpegXObject(objId, w, h) { - var image = this.objs.get(objId); - if (!image) { + paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { + var domImage = this.objs.get(objId); + if (!domImage) { error('Dependent image isn\'t ready yet'); } @@ -721,14 +1083,13 @@ var CanvasGraphics = (function canvasGraphics() { // scale the image to the unit square ctx.scale(1 / w, -1 / h); - var domImage = image.getImage(); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); this.restore(); }, - paintImageMaskXObject: function canvasGraphicsPaintImageMaskXObject( + paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject( imgArray, inverseDecode, width, height) { function applyStencilMask(buffer, inverseDecode) { var imgArrayPos = 0; @@ -758,7 +1119,7 @@ var CanvasGraphics = (function canvasGraphics() { // scale the image to the unit square ctx.scale(1 / w, -1 / h); - var tmpCanvas = new this.ScratchCanvas(w, h); + var tmpCanvas = createScratchCanvas(w, h); var tmpCtx = tmpCanvas.getContext('2d'); var fillColor = this.current.fillColor; @@ -777,7 +1138,11 @@ var CanvasGraphics = (function canvasGraphics() { this.restore(); }, - paintImageXObject: function canvasGraphicsPaintImageXObject(imgData) { + paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { + var imgData = this.objs.get(objId); + if (!imgData) + error('Dependent image isn\'t ready yet'); + this.save(); var ctx = this.ctx; var w = imgData.width; @@ -785,59 +1150,49 @@ var CanvasGraphics = (function canvasGraphics() { // scale the image to the unit square ctx.scale(1 / w, -1 / h); - var tmpCanvas = new this.ScratchCanvas(w, h); + var tmpCanvas = createScratchCanvas(w, h); var tmpCtx = tmpCanvas.getContext('2d'); - var tmpImgData; + this.putBinaryImageData(tmpCtx, imgData, w, h); - // Some browsers can set an UInt8Array directly as imageData, some - // can't. As long as we don't have proper feature detection, just - // copy over each pixel and set the imageData that way. - tmpImgData = tmpCtx.getImageData(0, 0, w, h); - - // Copy over the imageData. - var tmpImgDataPixels = tmpImgData.data; - var len = tmpImgDataPixels.length; - - while (len--) { - tmpImgDataPixels[len] = imgData.data[len]; - } - - tmpCtx.putImageData(tmpImgData, 0, 0); ctx.drawImage(tmpCanvas, 0, -h); this.restore(); }, + putBinaryImageData: function CanvasGraphics_putBinaryImageData() { + // + }, + // Marked content - markPoint: function canvasGraphicsMarkPoint(tag) { + markPoint: function CanvasGraphics_markPoint(tag) { TODO('Marked content'); }, - markPointProps: function canvasGraphicsMarkPointProps(tag, properties) { + markPointProps: function CanvasGraphics_markPointProps(tag, properties) { TODO('Marked content'); }, - beginMarkedContent: function canvasGraphicsBeginMarkedContent(tag) { + beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { TODO('Marked content'); }, - beginMarkedContentProps: - function canvasGraphicsBeginMarkedContentProps(tag, properties) { + beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( + tag, properties) { TODO('Marked content'); }, - endMarkedContent: function canvasGraphicsEndMarkedContent() { + endMarkedContent: function CanvasGraphics_endMarkedContent() { TODO('Marked content'); }, // Compatibility - beginCompat: function canvasGraphicsBeginCompat() { + beginCompat: function CanvasGraphics_beginCompat() { TODO('ignore undefined operators (should we do that anyway?)'); }, - endCompat: function canvasGraphicsEndCompat() { + endCompat: function CanvasGraphics_endCompat() { TODO('stop ignoring undefined operators'); }, // Helper functions - consumePath: function canvasGraphicsConsumePath() { + consumePath: function CanvasGraphics_consumePath() { if (this.pendingClip) { var savedFillRule = null; if (this.pendingClip == EO_CLIP) @@ -854,16 +1209,55 @@ var CanvasGraphics = (function canvasGraphics() { // We generally keep the canvas context set for // nonzero-winding, and just set evenodd for the operations // that need them. - setEOFillRule: function canvasGraphicsSetEOFillRule() { + setEOFillRule: function CanvasGraphics_setEOFillRule() { var savedFillRule = this.ctx.mozFillRule; this.ctx.mozFillRule = 'evenodd'; return savedFillRule; }, - restoreFillRule: function canvasGraphicsRestoreFillRule(rule) { + restoreFillRule: function CanvasGraphics_restoreFillRule(rule) { this.ctx.mozFillRule = rule; + }, + getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { + var inverse = this.ctx.mozCurrentTransformInverse; + return Math.abs(inverse[0] + inverse[2]); } }; - return constructor; + return CanvasGraphics; })(); +if (!isWorker) { + // Feature detection if the browser can use an Uint8Array directly as imgData. + var canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + var ctx = canvas.getContext('2d'); + + try { + ctx.putImageData({ + width: 1, + height: 1, + data: new Uint8Array(4) + }, 0, 0); + + CanvasGraphics.prototype.putBinaryImageData = + function CanvasGraphicsPutBinaryImageDataNative(ctx, imgData) { + ctx.putImageData(imgData, 0, 0); + }; + } catch (e) { + CanvasGraphics.prototype.putBinaryImageData = + function CanvasGraphicsPutBinaryImageDataShim(ctx, imgData, w, h) { + var tmpImgData = ctx.getImageData(0, 0, w, h); + + // Copy over the imageData pixel by pixel. + var tmpImgDataPixels = tmpImgData.data; + var len = tmpImgDataPixels.length; + + while (len--) { + tmpImgDataPixels[len] = imgData.data[len]; + } + + ctx.putImageData(tmpImgData, 0, 0); + }; + } +} diff --git a/apps/files_pdfviewer/js/pdfjs/src/charsets.js b/apps/files_pdfviewer/js/pdfjs/src/charsets.js old mode 100755 new mode 100644 diff --git a/apps/files_pdfviewer/js/pdfjs/src/cidmaps.js b/apps/files_pdfviewer/js/pdfjs/src/cidmaps.js old mode 100755 new mode 100644 diff --git a/apps/files_pdfviewer/js/pdfjs/src/colorspace.js b/apps/files_pdfviewer/js/pdfjs/src/colorspace.js old mode 100755 new mode 100644 index b369d0f884f..8d8290109de --- a/apps/files_pdfviewer/js/pdfjs/src/colorspace.js +++ b/apps/files_pdfviewer/js/pdfjs/src/colorspace.js @@ -3,34 +3,34 @@ 'use strict'; -var ColorSpace = (function colorSpaceColorSpace() { +var ColorSpace = (function ColorSpaceClosure() { // Constructor should define this.numComps, this.defaultColor, this.name - function constructor() { + function ColorSpace() { error('should not call ColorSpace constructor'); } - constructor.prototype = { + ColorSpace.prototype = { // Input: array of size numComps representing color component values // Output: array of rgb values, each value ranging from [0.1] - getRgb: function colorSpaceGetRgb(color) { + getRgb: function ColorSpace_getRgb(color) { error('Should not call ColorSpace.getRgb: ' + color); }, // Input: Uint8Array of component values, each value scaled to [0,255] // Output: Uint8Array of rgb values, each value scaled to [0,255] - getRgbBuffer: function colorSpaceGetRgbBuffer(input) { + getRgbBuffer: function ColorSpace_getRgbBuffer(input) { error('Should not call ColorSpace.getRgbBuffer: ' + input); } }; - constructor.parse = function colorSpaceParse(cs, xref, res) { - var IR = constructor.parseToIR(cs, xref, res); + ColorSpace.parse = function ColorSpace_parse(cs, xref, res) { + var IR = ColorSpace.parseToIR(cs, xref, res); if (IR instanceof AlternateCS) return IR; - return constructor.fromIR(IR); + return ColorSpace.fromIR(IR); }; - constructor.fromIR = function colorSpaceFromIR(IR) { + ColorSpace.fromIR = function ColorSpace_fromIR(IR) { var name = isArray(IR) ? IR[0] : IR; switch (name) { @@ -57,15 +57,20 @@ var ColorSpace = (function colorSpaceColorSpace() { return new AlternateCS(numComps, ColorSpace.fromIR(alt), PDFFunction.fromIR(tintFnIR)); + case 'LabCS': + var whitePoint = IR[1].WhitePoint; + var blackPoint = IR[1].BlackPoint; + var range = IR[1].Range; + return new LabCS(whitePoint, blackPoint, range); default: error('Unkown name ' + name); } return null; }; - constructor.parseToIR = function colorSpaceParseToIR(cs, xref, res) { + ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) { if (isName(cs)) { - var colorSpaces = xref.fetchIfRef(res.get('ColorSpace')); + var colorSpaces = res.get('ColorSpace'); if (isDict(colorSpaces)) { var refcs = colorSpaces.get(cs.name); if (refcs) @@ -130,6 +135,7 @@ var ColorSpace = (function colorSpaceColorSpace() { basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res); return ['PatternCS', basePatternCS]; case 'Indexed': + case 'I': var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res); var hiVal = cs[2] + 1; var lookup = xref.fetchIfRef(cs[3]); @@ -146,6 +152,8 @@ var ColorSpace = (function colorSpaceColorSpace() { var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3])); return ['AlternateCS', numComps, alt, tintFnIR]; case 'Lab': + var params = cs[1].getAll(); + return ['LabCS', params]; default: error('unimplemented color space object "' + mode + '"'); } @@ -154,8 +162,31 @@ var ColorSpace = (function colorSpaceColorSpace() { } return null; }; + /** + * Checks if a decode map matches the default decode map for a color space. + * This handles the general decode maps where there are two values per + * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color. + * This does not handle Lab, Indexed, or Pattern decode maps since they are + * slightly different. + * @param {Array} decode Decode map (usually from an image). + * @param {Number} n Number of components the color space has. + */ + ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) { + if (!decode) + return true; + + if (n * 2 !== decode.length) { + warning('The decode map is not the correct length'); + return true; + } + for (var i = 0, ii = decode.length; i < ii; i += 2) { + if (decode[i] != 0 || decode[i + 1] != 1) + return false; + } + return true; + }; - return constructor; + return ColorSpace; })(); /** @@ -164,8 +195,8 @@ var ColorSpace = (function colorSpaceColorSpace() { * Both color spaces use a tinting function to convert colors to a base color * space. */ -var AlternateCS = (function alternateCS() { - function constructor(numComps, base, tintFn) { +var AlternateCS = (function AlternateCSClosure() { + function AlternateCS(numComps, base, tintFn) { this.name = 'Alternate'; this.numComps = numComps; this.defaultColor = []; @@ -175,12 +206,12 @@ var AlternateCS = (function alternateCS() { this.tintFn = tintFn; } - constructor.prototype = { - getRgb: function altcs_getRgb(color) { + AlternateCS.prototype = { + getRgb: function AlternateCS_getRgb(color) { var tinted = this.tintFn(color); return this.base.getRgb(tinted); }, - getRgbBuffer: function altcs_getRgbBuffer(input, bits) { + getRgbBuffer: function AlternateCS_getRgbBuffer(input, bits) { var tintFn = this.tintFn; var base = this.base; var scale = 1 / ((1 << bits) - 1); @@ -189,7 +220,7 @@ var AlternateCS = (function alternateCS() { var baseNumComps = base.numComps; var baseBuf = new Uint8Array(baseNumComps * length); var numComps = this.numComps; - var scaled = new Array(numComps); + var scaled = []; for (var i = 0; i < length; i += numComps) { for (var z = 0; z < numComps; ++z) @@ -200,24 +231,27 @@ var AlternateCS = (function alternateCS() { baseBuf[pos++] = 255 * tinted[j]; } return base.getRgbBuffer(baseBuf, 8); + }, + isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) { + return ColorSpace.isDefaultDecode(decodeMap, this.numComps); } }; - return constructor; + return AlternateCS; })(); -var PatternCS = (function patternCS() { - function constructor(baseCS) { +var PatternCS = (function PatternCSClosure() { + function PatternCS(baseCS) { this.name = 'Pattern'; this.base = baseCS; } - constructor.prototype = {}; + PatternCS.prototype = {}; - return constructor; + return PatternCS; })(); -var IndexedCS = (function indexedCS() { - function constructor(base, highVal, lookup) { +var IndexedCS = (function IndexedCSClosure() { + function IndexedCS(base, highVal, lookup) { this.name = 'Indexed'; this.numComps = 1; this.defaultColor = [0]; @@ -240,8 +274,8 @@ var IndexedCS = (function indexedCS() { this.lookup = lookupArray; } - constructor.prototype = { - getRgb: function indexcs_getRgb(color) { + IndexedCS.prototype = { + getRgb: function IndexedCS_getRgb(color) { var numComps = this.base.numComps; var start = color[0] * numComps; var c = []; @@ -251,7 +285,7 @@ var IndexedCS = (function indexedCS() { return this.base.getRgb(c); }, - getRgbBuffer: function indexcs_getRgbBuffer(input) { + getRgbBuffer: function IndexedCS_getRgbBuffer(input) { var base = this.base; var numComps = base.numComps; var lookup = this.lookup; @@ -267,24 +301,28 @@ var IndexedCS = (function indexedCS() { } return base.getRgbBuffer(baseBuf, 8); + }, + isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) { + // indexed color maps shouldn't be changed + return true; } }; - return constructor; + return IndexedCS; })(); -var DeviceGrayCS = (function deviceGrayCS() { - function constructor() { +var DeviceGrayCS = (function DeviceGrayCSClosure() { + function DeviceGrayCS() { this.name = 'DeviceGray'; this.numComps = 1; this.defaultColor = [0]; } - constructor.prototype = { - getRgb: function graycs_getRgb(color) { + DeviceGrayCS.prototype = { + getRgb: function DeviceGrayCS_getRgb(color) { var c = color[0]; return [c, c, c]; }, - getRgbBuffer: function graycs_getRgbBuffer(input, bits) { + getRgbBuffer: function DeviceGrayCS_getRgbBuffer(input, bits) { var scale = 255 / ((1 << bits) - 1); var length = input.length; var rgbBuf = new Uint8Array(length * 3); @@ -295,22 +333,25 @@ var DeviceGrayCS = (function deviceGrayCS() { rgbBuf[j++] = c; } return rgbBuf; + }, + isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) { + return ColorSpace.isDefaultDecode(decodeMap, this.numComps); } }; - return constructor; + return DeviceGrayCS; })(); -var DeviceRgbCS = (function deviceRgbCS() { - function constructor() { +var DeviceRgbCS = (function DeviceRgbCSClosure() { + function DeviceRgbCS() { this.name = 'DeviceRGB'; this.numComps = 3; this.defaultColor = [0, 0, 0]; } - constructor.prototype = { - getRgb: function rgbcs_getRgb(color) { + DeviceRgbCS.prototype = { + getRgb: function DeviceRgbCS_getRgb(color) { return color; }, - getRgbBuffer: function rgbcs_getRgbBuffer(input, bits) { + getRgbBuffer: function DeviceRgbCS_getRgbBuffer(input, bits) { if (bits == 8) return input; var scale = 255 / ((1 << bits) - 1); @@ -319,73 +360,37 @@ var DeviceRgbCS = (function deviceRgbCS() { for (i = 0; i < length; ++i) rgbBuf[i] = (scale * input[i]) | 0; return rgbBuf; + }, + isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) { + return ColorSpace.isDefaultDecode(decodeMap, this.numComps); } }; - return constructor; + return DeviceRgbCS; })(); -var DeviceCmykCS = (function deviceCmykCS() { - function constructor() { +var DeviceCmykCS = (function DeviceCmykCSClosure() { + function DeviceCmykCS() { this.name = 'DeviceCMYK'; this.numComps = 4; this.defaultColor = [0, 0, 0, 1]; } - constructor.prototype = { - getRgb: function cmykcs_getRgb(color) { + DeviceCmykCS.prototype = { + getRgb: function DeviceCmykCS_getRgb(color) { var c = color[0], m = color[1], y = color[2], k = color[3]; - var c1 = 1 - c, m1 = 1 - m, y1 = 1 - y, k1 = 1 - k; - - var x, r, g, b; - // this is a matrix multiplication, unrolled for performance - // code is taken from the poppler implementation - x = c1 * m1 * y1 * k1; // 0 0 0 0 - r = g = b = x; - x = c1 * m1 * y1 * k; // 0 0 0 1 - r += 0.1373 * x; - g += 0.1216 * x; - b += 0.1255 * x; - x = c1 * m1 * y * k1; // 0 0 1 0 - r += x; - g += 0.9490 * x; - x = c1 * m1 * y * k; // 0 0 1 1 - r += 0.1098 * x; - g += 0.1020 * x; - x = c1 * m * y1 * k1; // 0 1 0 0 - r += 0.9255 * x; - b += 0.5490 * x; - x = c1 * m * y1 * k; // 0 1 0 1 - r += 0.1412 * x; - x = c1 * m * y * k1; // 0 1 1 0 - r += 0.9294 * x; - g += 0.1098 * x; - b += 0.1412 * x; - x = c1 * m * y * k; // 0 1 1 1 - r += 0.1333 * x; - x = c * m1 * y1 * k1; // 1 0 0 0 - g += 0.6784 * x; - b += 0.9373 * x; - x = c * m1 * y1 * k; // 1 0 0 1 - g += 0.0588 * x; - b += 0.1412 * x; - x = c * m1 * y * k1; // 1 0 1 0 - g += 0.6510 * x; - b += 0.3137 * x; - x = c * m1 * y * k; // 1 0 1 1 - g += 0.0745 * x; - x = c * m * y1 * k1; // 1 1 0 0 - r += 0.1804 * x; - g += 0.1922 * x; - b += 0.5725 * x; - x = c * m * y1 * k; // 1 1 0 1 - b += 0.0078 * x; - x = c * m * y * k1; // 1 1 1 0 - r += 0.2118 * x; - g += 0.2119 * x; - b += 0.2235 * x; + + // CMYK -> CMY: http://www.easyrgb.com/index.php?X=MATH&H=14#text14 + c = (c * (1 - k) + k); + m = (m * (1 - k) + k); + y = (y * (1 - k) + k); + + // CMY -> RGB: http://www.easyrgb.com/index.php?X=MATH&H=12#text12 + var r = (1 - c); + var g = (1 - m); + var b = (1 - y); return [r, g, b]; }, - getRgbBuffer: function cmykcs_getRgbBuffer(colorBuf, bits) { + getRgbBuffer: function DeviceCmykCS_getRgbBuffer(colorBuf, bits) { var scale = 1 / ((1 << bits) - 1); var length = colorBuf.length / 4; var rgbBuf = new Uint8Array(length * 3); @@ -403,9 +408,125 @@ var DeviceCmykCS = (function deviceCmykCS() { } return rgbBuf; + }, + isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) { + return ColorSpace.isDefaultDecode(decodeMap, this.numComps); } }; - return constructor; + return DeviceCmykCS; })(); +// +// LabCS: Based on "PDF Reference, Sixth Ed", p.250 +// +var LabCS = (function LabCSClosure() { + function LabCS(whitePoint, blackPoint, range) { + this.name = 'Lab'; + this.numComps = 3; + this.defaultColor = [0, 0, 0]; + + if (!whitePoint) + error('WhitePoint missing - required for color space Lab'); + blackPoint = blackPoint || [0, 0, 0]; + range = range || [-100, 100, -100, 100]; + + // Translate args to spec variables + this.XW = whitePoint[0]; + this.YW = whitePoint[1]; + this.ZW = whitePoint[2]; + this.amin = range[0]; + this.amax = range[1]; + this.bmin = range[2]; + this.bmax = range[3]; + + // These are here just for completeness - the spec doesn't offer any + // formulas that use BlackPoint in Lab + this.XB = blackPoint[0]; + this.YB = blackPoint[1]; + this.ZB = blackPoint[2]; + + // Validate vars as per spec + if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) + error('Invalid WhitePoint components, no fallback available'); + + if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { + warn('Invalid BlackPoint, falling back to default'); + this.XB = this.YB = this.ZB = 0; + } + + if (this.amin > this.amax || this.bmin > this.bmax) { + warn('Invalid Range, falling back to defaults'); + this.amin = -100; + this.amax = 100; + this.bmin = -100; + this.bmax = 100; + } + }; + + // Function g(x) from spec + function g(x) { + if (x >= 6 / 29) + return x * x * x; + else + return (108 / 841) * (x - 4 / 29); + } + + LabCS.prototype = { + getRgb: function LabCS_getRgb(color) { + // Ls,as,bs <---> L*,a*,b* in the spec + var Ls = color[0], as = color[1], bs = color[2]; + + // Adjust limits of 'as' and 'bs' + as = as > this.amax ? this.amax : as; + as = as < this.amin ? this.amin : as; + bs = bs > this.bmax ? this.bmax : bs; + bs = bs < this.bmin ? this.bmin : bs; + + // Computes intermediate variables X,Y,Z as per spec + var M = (Ls + 16) / 116; + var L = M + (as / 500); + var N = M - (bs / 200); + var X = this.XW * g(L); + var Y = this.YW * g(M); + var Z = this.ZW * g(N); + + // XYZ to RGB 3x3 matrix, from: + // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC18 + var XYZtoRGB = [3.240479, -1.537150, -0.498535, + -0.969256, 1.875992, 0.041556, + 0.055648, -0.204043, 1.057311]; + + return Util.apply3dTransform(XYZtoRGB, [X, Y, Z]); + }, + getRgbBuffer: function LabCS_getRgbBuffer(input, bits) { + if (bits == 8) + return input; + var scale = 255 / ((1 << bits) - 1); + var i, length = input.length / 3; + var rgbBuf = new Uint8Array(length); + + var j = 0; + for (i = 0; i < length; ++i) { + // Convert L*, a*, s* into RGB + var rgb = this.getRgb([input[i], input[i + 1], input[i + 2]]); + rgbBuf[j++] = rgb[0]; + rgbBuf[j++] = rgb[1]; + rgbBuf[j++] = rgb[2]; + } + + return rgbBuf; + }, + isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) { + // From Table 90 in Adobe's: + // "Document management - Portable document format", 1st ed, 2008 + if (decodeMap[0] === 0 && decodeMap[1] === 100 && + decodeMap[2] === this.amin && decodeMap[3] === this.amax && + decodeMap[4] === this.bmin && decodeMap[5] === this.bmax) + return true; + else + return false; + } + }; + return LabCS; +})(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/core.js b/apps/files_pdfviewer/js/pdfjs/src/core.js old mode 100755 new mode 100644 index 3549eb906b6..15cd147e2c2 --- a/apps/files_pdfviewer/js/pdfjs/src/core.js +++ b/apps/files_pdfviewer/js/pdfjs/src/core.js @@ -5,6 +5,8 @@ var globalScope = (typeof window === 'undefined') ? this : window; +var isWorker = (typeof window == 'undefined'); + var ERRORS = 0, WARNINGS = 1, TODOS = 5; var verbosity = WARNINGS; @@ -31,7 +33,9 @@ function getPdf(arg, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', params.url); xhr.mozResponseType = xhr.responseType = 'arraybuffer'; - xhr.expected = (document.URL.indexOf('file:') === 0) ? 0 : 200; + var protocol = params.url.indexOf(':') < 0 ? window.location.protocol : + params.url.substring(0, params.url.indexOf(':') + 1); + xhr.expected = (protocol === 'http:' || protocol === 'https:') ? 200 : 0; if ('progress' in params) xhr.onprogress = params.progress || undefined; @@ -39,41 +43,43 @@ function getPdf(arg, callback) { if ('error' in params) xhr.onerror = params.error || undefined; - xhr.onreadystatechange = function getPdfOnreadystatechange() { - if (xhr.readyState === 4 && xhr.status === xhr.expected) { - var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse || - xhr.responseArrayBuffer || xhr.response); - callback(data); + xhr.onreadystatechange = function getPdfOnreadystatechange(e) { + if (xhr.readyState === 4) { + if (xhr.status === xhr.expected) { + var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse || + xhr.responseArrayBuffer || xhr.response); + callback(data); + } else if (params.error) { + params.error(e); + } } }; xhr.send(null); } globalScope.PDFJS.getPdf = getPdf; +globalScope.PDFJS.pdfBug = false; -var Page = (function pagePage() { - function constructor(xref, pageNumber, pageDict, ref) { +var Page = (function PageClosure() { + function Page(xref, pageNumber, pageDict, ref) { this.pageNumber = pageNumber; this.pageDict = pageDict; - this.stats = { - create: Date.now(), - compile: 0.0, - fonts: 0.0, - images: 0.0, - render: 0.0 - }; + this.stats = new StatTimer(); + this.stats.enabled = !!globalScope.PDFJS.enableStats; this.xref = xref; this.ref = ref; + + this.displayReadyPromise = null; } - constructor.prototype = { - getPageProp: function pageGetPageProp(key) { - return this.xref.fetchIfRef(this.pageDict.get(key)); + Page.prototype = { + getPageProp: function Page_getPageProp(key) { + return this.pageDict.get(key); }, - inheritPageProp: function pageInheritPageProp(key) { + inheritPageProp: function Page_inheritPageProp(key) { var dict = this.pageDict; var obj = dict.get(key); while (obj === undefined) { - dict = this.xref.fetchIfRef(dict.get('Parent')); + dict = dict.get('Parent'); if (!dict) break; obj = dict.get(key); @@ -94,23 +100,35 @@ var Page = (function pagePage() { return shadow(this, 'mediaBox', obj); }, get view() { - var obj = this.inheritPageProp('CropBox'); + var cropBox = this.inheritPageProp('CropBox'); var view = { x: 0, y: 0, width: this.width, height: this.height }; - if (isArray(obj) && obj.length == 4) { - var tl = this.rotatePoint(obj[0], obj[1]); - var br = this.rotatePoint(obj[2], obj[3]); - view.x = Math.min(tl.x, br.x); - view.y = Math.min(tl.y, br.y); - view.width = Math.abs(tl.x - br.x); - view.height = Math.abs(tl.y - br.y); - } + if (!isArray(cropBox) || cropBox.length !== 4) + return shadow(this, 'view', view); - return shadow(this, 'cropBox', view); + var mediaBox = this.mediaBox; + var offsetX = mediaBox[0], offsetY = mediaBox[1]; + + // From the spec, 6th ed., p.963: + // "The crop, bleed, trim, and art boxes should not ordinarily + // extend beyond the boundaries of the media box. If they do, they are + // effectively reduced to their intersection with the media box." + cropBox = Util.intersect(cropBox, mediaBox); + if (!cropBox) + return shadow(this, 'view', view); + + var tl = this.rotatePoint(cropBox[0] - offsetX, cropBox[1] - offsetY); + var br = this.rotatePoint(cropBox[2] - offsetX, cropBox[3] - offsetY); + view.x = Math.min(tl.x, br.x); + view.y = Math.min(tl.y, br.y); + view.width = Math.abs(tl.x - br.x); + view.height = Math.abs(tl.y - br.y); + + return shadow(this, 'view', view); }, get annotations() { return shadow(this, 'annotations', this.inheritPageProp('Annots')); @@ -152,77 +170,80 @@ var Page = (function pagePage() { return shadow(this, 'rotate', rotate); }, - startRenderingFromIRQueue: function pageStartRenderingFromIRQueue( - IRQueue, fonts) { + startRenderingFromOperatorList: + function Page_startRenderingFromOperatorList(operatorList, fonts) { var self = this; - this.IRQueue = IRQueue; - var gfx = new CanvasGraphics(this.ctx, this.objs); + this.operatorList = operatorList; var displayContinuation = function pageDisplayContinuation() { // Always defer call to display() to work around bug in // Firefox error reporting from XHR callbacks. setTimeout(function pageSetTimeout() { - try { - self.display(gfx, self.callback); - } catch (e) { - if (self.callback) self.callback(e.toString()); - throw e; - } + self.displayReadyPromise.resolve(); }); }; this.ensureFonts(fonts, - function pageStartRenderingFromIRQueueEnsureFonts() { - displayContinuation(); - }); + function pageStartRenderingFromOperatorListEnsureFonts() { + displayContinuation(); + } + ); }, - getIRQueue: function pageGetIRQueue(handler, dependency) { - if (this.IRQueue) { + getOperatorList: function Page_getOperatorList(handler, dependency) { + if (this.operatorList) { // content was compiled - return this.IRQueue; + return this.operatorList; } + this.stats.time('Build IR Queue'); + var xref = this.xref; - var content = xref.fetchIfRef(this.content); - var resources = xref.fetchIfRef(this.resources); + var content = this.content; + var resources = this.resources; if (isArray(content)) { // fetching items var i, n = content.length; for (i = 0; i < n; ++i) content[i] = xref.fetchIfRef(content[i]); content = new StreamsSequenceStream(content); + } else if (!content) { + // replacing non-existent page content with empty one + content = new Stream(new Uint8Array(0)); } var pe = this.pe = new PartialEvaluator( xref, handler, 'p' + this.pageNumber + '_'); - var IRQueue = {}; - return (this.IRQueue = pe.getIRQueue(content, resources, IRQueue, - dependency)); + + this.operatorList = pe.getOperatorList(content, resources, dependency); + this.stats.timeEnd('Build IR Queue'); + return this.operatorList; }, - ensureFonts: function pageEnsureFonts(fonts, callback) { + ensureFonts: function Page_ensureFonts(fonts, callback) { + this.stats.time('Font Loading'); // Convert the font names to the corresponding font obj. for (var i = 0, ii = fonts.length; i < ii; i++) { fonts[i] = this.objs.objs[fonts[i]].data; } // Load all the fonts - var fontObjs = FontLoader.bind( + FontLoader.bind( fonts, function pageEnsureFontsFontObjs(fontObjs) { - this.stats.fonts = Date.now(); + this.stats.timeEnd('Font Loading'); callback.call(this); - }.bind(this), - this.objs + }.bind(this) ); }, - display: function pageDisplay(gfx, callback) { + display: function Page_display(gfx, callback) { + var stats = this.stats; + stats.time('Rendering'); var xref = this.xref; - var resources = xref.fetchIfRef(this.resources); - var mediaBox = xref.fetchIfRef(this.mediaBox); + var resources = this.resources; + var mediaBox = this.mediaBox; assertWellFormed(isDict(resources), 'invalid page resources'); gfx.xref = xref; @@ -233,20 +254,29 @@ var Page = (function pagePage() { rotate: this.rotate }); var startIdx = 0; - var length = this.IRQueue.fnArray.length; - var IRQueue = this.IRQueue; + var length = this.operatorList.fnArray.length; + var operatorList = this.operatorList; + var stepper = null; + if (PDFJS.pdfBug && StepperManager.enabled) { + stepper = StepperManager.create(this.pageNumber); + stepper.init(operatorList); + stepper.nextBreakPoint = stepper.getNextBreakPoint(); + } var self = this; function next() { - startIdx = gfx.executeIRQueue(IRQueue, startIdx, next); + startIdx = + gfx.executeOperatorList(operatorList, startIdx, next, stepper); if (startIdx == length) { - self.stats.render = Date.now(); + gfx.endDrawing(); + stats.timeEnd('Rendering'); + stats.timeEnd('Overall'); if (callback) callback(); } } next(); }, - rotatePoint: function pageRotatePoint(x, y, reverse) { + rotatePoint: function Page_rotatePoint(x, y, reverse) { var rotate = reverse ? (360 - this.rotate) : this.rotate; switch (rotate) { case 180: @@ -261,58 +291,183 @@ var Page = (function pagePage() { return {x: x, y: this.height - y}; } }, - getLinks: function pageGetLinks() { + getLinks: function Page_getLinks() { + var links = []; + var annotations = pageGetAnnotations(); + var i, n = annotations.length; + for (i = 0; i < n; ++i) { + if (annotations[i].type != 'Link') + continue; + links.push(annotations[i]); + } + return links; + }, + getAnnotations: function Page_getAnnotations() { var xref = this.xref; - var annotations = xref.fetchIfRef(this.annotations) || []; + function getInheritableProperty(annotation, name) { + var item = annotation; + while (item && !item.has(name)) { + item = item.get('Parent'); + } + if (!item) + return null; + return item.get(name); + } + function isValidUrl(url) { + if (!url) + return false; + var colon = url.indexOf(':'); + if (colon < 0) + return false; + var protocol = url.substr(0, colon); + switch (protocol) { + case 'http': + case 'https': + case 'ftp': + return true; + default: + return false; + } + } + + var annotations = this.annotations || []; var i, n = annotations.length; - var links = []; + var items = []; for (i = 0; i < n; ++i) { - var annotation = xref.fetch(annotations[i]); + var annotationRef = annotations[i]; + var annotation = xref.fetch(annotationRef); if (!isDict(annotation)) continue; var subtype = annotation.get('Subtype'); - if (!isName(subtype) || subtype.name != 'Link') + if (!isName(subtype)) continue; var rect = annotation.get('Rect'); var topLeftCorner = this.rotatePoint(rect[0], rect[1]); var bottomRightCorner = this.rotatePoint(rect[2], rect[3]); - var link = {}; - link.x = Math.min(topLeftCorner.x, bottomRightCorner.x); - link.y = Math.min(topLeftCorner.y, bottomRightCorner.y); - link.width = Math.abs(topLeftCorner.x - bottomRightCorner.x); - link.height = Math.abs(topLeftCorner.y - bottomRightCorner.y); - var a = this.xref.fetchIfRef(annotation.get('A')); - if (a) { - switch (a.get('S').name) { - case 'URI': - link.url = a.get('URI'); - break; - case 'GoTo': - link.dest = a.get('D'); + var item = {}; + item.type = subtype.name; + item.x = Math.min(topLeftCorner.x, bottomRightCorner.x); + item.y = Math.min(topLeftCorner.y, bottomRightCorner.y); + item.width = Math.abs(topLeftCorner.x - bottomRightCorner.x); + item.height = Math.abs(topLeftCorner.y - bottomRightCorner.y); + switch (subtype.name) { + case 'Link': + var a = annotation.get('A'); + if (a) { + switch (a.get('S').name) { + case 'URI': + var url = a.get('URI'); + // TODO: pdf spec mentions urls can be relative to a Base + // entry in the dictionary. + if (!isValidUrl(url)) + url = ''; + item.url = url; + break; + case 'GoTo': + item.dest = a.get('D'); + break; + default: + TODO('other link types'); + } + } else if (annotation.has('Dest')) { + // simple destination link + var dest = annotation.get('Dest'); + item.dest = isName(dest) ? dest.name : dest; + } + break; + case 'Widget': + var fieldType = getInheritableProperty(annotation, 'FT'); + if (!isName(fieldType)) break; - default: - TODO('other link types'); - } - } else if (annotation.has('Dest')) { - // simple destination link - var dest = annotation.get('Dest'); - link.dest = isName(dest) ? dest.name : dest; + item.fieldType = fieldType.name; + // Building the full field name by collecting the field and + // its ancestors 'T' properties and joining them using '.'. + var fieldName = []; + var namedItem = annotation, ref = annotationRef; + while (namedItem) { + var parent = namedItem.get('Parent'); + var parentRef = namedItem.getRaw('Parent'); + var name = namedItem.get('T'); + if (name) { + fieldName.unshift(stringToPDFString(name)); + } else { + // The field name is absent, that means more than one field + // with the same name may exist. Replacing the empty name + // with the '`' plus index in the parent's 'Kids' array. + // This is not in the PDF spec but necessary to id the + // the input controls. + var kids = parent.get('Kids'); + var j, jj; + for (j = 0, jj = kids.length; j < jj; j++) { + var kidRef = kids[j]; + if (kidRef.num == ref.num && kidRef.gen == ref.gen) + break; + } + fieldName.unshift('`' + j); + } + namedItem = parent; + ref = parentRef; + } + item.fullName = fieldName.join('.'); + var alternativeText = stringToPDFString(annotation.get('TU') || ''); + item.alternativeText = alternativeText; + var da = getInheritableProperty(annotation, 'DA') || ''; + var m = /([\d\.]+)\sTf/.exec(da); + if (m) + item.fontSize = parseFloat(m[1]); + item.textAlignment = getInheritableProperty(annotation, 'Q'); + item.flags = getInheritableProperty(annotation, 'Ff') || 0; + break; + case 'Text': + var content = annotation.get('Contents'); + var title = annotation.get('T'); + item.content = stringToPDFString(content || ''); + item.title = stringToPDFString(title || ''); + item.name = annotation.get('Name').name; + break; + default: + TODO('unimplemented annotation type: ' + subtype.name); + break; } - links.push(link); + items.push(item); } - return links; + return items; }, - startRendering: function pageStartRendering(ctx, callback) { - this.ctx = ctx; - this.callback = callback; + startRendering: function Page_startRendering(ctx, callback, textLayer) { + var stats = this.stats; + stats.time('Overall'); + // If there is no displayReadyPromise yet, then the operatorList was never + // requested before. Make the request and create the promise. + if (!this.displayReadyPromise) { + this.pdf.startRendering(this); + this.displayReadyPromise = new Promise(); + } - this.startRenderingTime = Date.now(); - this.pdf.startRendering(this); + // Once the operatorList and fonts are loaded, do the actual rendering. + this.displayReadyPromise.then( + function pageDisplayReadyPromise() { + var gfx = new CanvasGraphics(ctx, this.objs, textLayer); + try { + this.display(gfx, callback); + } catch (e) { + if (callback) + callback(e); + else + error(e); + } + }.bind(this), + function pageDisplayReadPromiseError(reason) { + if (callback) + callback(reason); + else + error(reason); + } + ); } }; - return constructor; + return Page; })(); /** @@ -321,12 +476,9 @@ var Page = (function pagePage() { * Right now there exists one PDFDocModel on the main thread + one object * for each worker. If there is no worker support enabled, there are two * `PDFDocModel` objects on the main thread created. - * TODO: Refactor the internal object structure, such that there is no - * need for the `PDFDocModel` anymore and there is only one object on the - * main thread and not one entire copy on each worker instance. */ -var PDFDocModel = (function pdfDoc() { - function constructor(arg, callback) { +var PDFDocModel = (function PDFDocModelClosure() { + function PDFDocModel(arg, callback) { if (isStream(arg)) init.call(this, arg); else if (isArrayBuffer(arg)) @@ -339,6 +491,7 @@ var PDFDocModel = (function pdfDoc() { assertWellFormed(stream.length > 0, 'stream must have data'); this.stream = stream; this.setup(); + this.acroForm = this.catalog.catDict.get('AcroForm'); } function find(stream, needle, limit, backwards) { @@ -357,7 +510,7 @@ var PDFDocModel = (function pdfDoc() { return true; /* found */ } - constructor.prototype = { + PDFDocModel.prototype = { get linearization() { var length = this.stream.length; var linearization = false; @@ -379,12 +532,17 @@ var PDFDocModel = (function pdfDoc() { if (find(stream, 'endobj', 1024)) startXRef = stream.pos + 6; } else { - // Find startxref at the end of the file. - var start = stream.end - 1024; - if (start < 0) - start = 0; - stream.pos = start; - if (find(stream, 'startxref', 1024, true)) { + // Find startxref by jumping backward from the end of the file. + var step = 1024; + var found = false, pos = stream.end; + while (!found && pos > 0) { + pos -= step - 'startxref'.length; + if (pos < 0) + pos = 0; + stream.pos = pos; + found = find(stream, 'startxref', step, true); + } + if (found) { stream.skip(9); var ch; do { @@ -413,7 +571,7 @@ var PDFDocModel = (function pdfDoc() { }, // Find the header, remove leading garbage and setup the stream // starting from the header. - checkHeader: function pdfDocCheckHeader() { + checkHeader: function PDFDocModel_checkHeader() { var stream = this.stream; stream.reset(); if (find(stream, '%PDF-', 1024)) { @@ -423,12 +581,13 @@ var PDFDocModel = (function pdfDoc() { } // May not be a PDF file, continue anyway. }, - setup: function pdfDocSetup(ownerPassword, userPassword) { + setup: function PDFDocModel_setup(ownerPassword, userPassword) { this.checkHeader(); - this.xref = new XRef(this.stream, - this.startXRef, - this.mainXRefEntriesOffset); - this.catalog = new Catalog(this.xref); + var xref = new XRef(this.stream, + this.startXRef, + this.mainXRefEntriesOffset); + this.xref = xref; + this.catalog = new Catalog(xref); }, get numPages() { var linearization = this.linearization; @@ -436,16 +595,51 @@ var PDFDocModel = (function pdfDoc() { // shadow the prototype getter return shadow(this, 'numPages', num); }, - getPage: function pdfDocGetPage(n) { + getDocumentInfo: function PDFDocModel_getDocumentInfo() { + var info; + if (this.xref.trailer.has('Info')) { + var infoDict = this.xref.trailer.get('Info'); + + info = {}; + infoDict.forEach(function(key, value) { + info[key] = typeof value !== 'string' ? value : + stringToPDFString(value); + }); + } + + return shadow(this, 'getDocumentInfo', info); + }, + getFingerprint: function PDFDocModel_getFingerprint() { + var xref = this.xref, fileID; + if (xref.trailer.has('ID')) { + fileID = ''; + var id = xref.trailer.get('ID')[0]; + id.split('').forEach(function(el) { + fileID += Number(el.charCodeAt(0)).toString(16); + }); + } else { + // If we got no fileID, then we generate one, + // from the first 100 bytes of PDF + var data = this.stream.bytes.subarray(0, 100); + var hash = calculateMD5(data, 0, data.length); + fileID = ''; + for (var i = 0, length = hash.length; i < length; i++) { + fileID += Number(hash[i]).toString(16); + } + } + + return shadow(this, 'getFingerprint', fileID); + }, + getPage: function PDFDocModel_getPage(n) { return this.catalog.getPage(n); } }; - return constructor; + return PDFDocModel; })(); -var PDFDoc = (function pdfDoc() { - function constructor(arg, callback) { +var PDFDoc = (function PDFDocClosure() { + function PDFDoc(arg, callback) { var stream = null; var data = null; @@ -461,9 +655,10 @@ var PDFDoc = (function pdfDoc() { this.data = data; this.stream = stream; - this.pdf = new PDFDocModel(stream); - - this.catalog = this.pdf.catalog; + this.pdfModel = new PDFDocModel(stream); + this.fingerprint = this.pdfModel.getFingerprint(); + this.info = this.pdfModel.getDocumentInfo(); + this.catalog = this.pdfModel.catalog; this.objs = new PDFObjects(); this.pageCache = []; @@ -478,49 +673,59 @@ var PDFDoc = (function pdfDoc() { if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = PDFJS.workerSrc; if (typeof workerSrc === 'undefined') { - throw 'No PDFJS.workerSrc specified'; + error('No PDFJS.workerSrc specified'); } - var worker; try { - worker = new Worker(workerSrc); - } catch (e) { - // Some versions of FF can't create a worker on localhost, see: - // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 - globalScope.PDFJS.disableWorker = true; - this.setupFakeWorker(); - return; - } - - var messageHandler = new MessageHandler('main', worker); - - // Tell the worker the file it was created from. - messageHandler.send('workerSrc', workerSrc); - - messageHandler.on('test', function pdfDocTest(supportTypedArray) { - if (supportTypedArray) { - this.worker = worker; - this.setupMessageHandler(messageHandler); + var worker; + if (PDFJS.isFirefoxExtension) { + // The firefox extension can't load the worker from the resource:// + // url so we have to inline the script and then use the blob loader. + var bb = new MozBlobBuilder(); + bb.append(document.querySelector('#PDFJS_SCRIPT_TAG').textContent); + var blobUrl = window.URL.createObjectURL(bb.getBlob()); + worker = new Worker(blobUrl); } else { - this.setupFakeWorker(); + // Some versions of FF can't create a worker on localhost, see: + // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 + worker = new Worker(workerSrc); } - }.bind(this)); - var testObj = new Uint8Array(1); - messageHandler.send('test', testObj); - } else { - this.setupFakeWorker(); + var messageHandler = new MessageHandler('main', worker); + + messageHandler.on('test', function pdfDocTest(supportTypedArray) { + if (supportTypedArray) { + this.worker = worker; + this.setupMessageHandler(messageHandler); + } else { + globalScope.PDFJS.disableWorker = true; + this.setupFakeWorker(); + } + }.bind(this)); + + var testObj = new Uint8Array(1); + // Some versions of Opera throw a DATA_CLONE_ERR on + // serializing the typed array. + messageHandler.send('test', testObj); + return; + } catch (e) { + warn('The worker has been disabled.'); + } } + // Either workers are disabled, not supported or have thrown an exception. + // Thus, we fallback to a faked worker. + globalScope.PDFJS.disableWorker = true; + this.setupFakeWorker(); } - constructor.prototype = { - setupFakeWorker: function() { + PDFDoc.prototype = { + setupFakeWorker: function PDFDoc_setupFakeWorker() { // If we don't use a worker, just post/sendMessage to the main thread. var fakeWorker = { - postMessage: function pdfDocPostMessage(obj) { + postMessage: function PDFDoc_postMessage(obj) { fakeWorker.onmessage({data: obj}); }, - terminate: function pdfDocTerminate() {} + terminate: function PDFDoc_terminate() {} }; var messageHandler = new MessageHandler('main', fakeWorker); @@ -532,7 +737,7 @@ var PDFDoc = (function pdfDoc() { }, - setupMessageHandler: function(messageHandler) { + setupMessageHandler: function PDFDoc_setupMessageHandler(messageHandler) { this.messageHandler = messageHandler; messageHandler.on('page', function pdfDocPage(data) { @@ -540,7 +745,8 @@ var PDFDoc = (function pdfDoc() { var page = this.pageCache[pageNum]; var depFonts = data.depFonts; - page.startRenderingFromIRQueue(data.IRQueue, depFonts); + page.stats.timeEnd('Page Request'); + page.startRenderingFromOperatorList(data.operatorList, depFonts); }, this); messageHandler.on('obj', function pdfDocObj(data) { @@ -549,8 +755,12 @@ var PDFDoc = (function pdfDoc() { switch (type) { case 'JpegStream': - var IR = data[2]; - new JpegImageLoader(id, IR, this.objs); + var imageData = data[2]; + loadJpegStream(id, imageData, this.objs); + break; + case 'Image': + var imageData = data[2]; + this.objs.resolve(id, imageData); break; case 'Font': var name = data[2]; @@ -558,46 +768,63 @@ var PDFDoc = (function pdfDoc() { var properties = data[4]; if (file) { + // Rewrap the ArrayBuffer in a stream. var fontFileDict = new Dict(); - fontFileDict.map = file.dict.map; - - var fontFile = new Stream(file.bytes, file.start, - file.end - file.start, fontFileDict); - - // Check if this is a FlateStream. Otherwise just use the created - // Stream one. This makes complex_ttf_font.pdf work. - var cmf = file.bytes[0]; - if ((cmf & 0x0f) == 0x08) { - file = new FlateStream(fontFile); - } else { - file = fontFile; - } + file = new Stream(file, 0, file.length, fontFileDict); } - // For now, resolve the font object here direclty. The real font - // object is then created in FontLoader.bind(). - this.objs.resolve(id, { - name: name, - file: file, - properties: properties - }); + // At this point, only the font object is created but the font is + // not yet attached to the DOM. This is done in `FontLoader.bind`. + var font = new Font(name, file, properties); + this.objs.resolve(id, font); break; default: - throw 'Got unkown object type ' + type; + error('Got unkown object type ' + type); } }, this); - messageHandler.on('font_ready', function pdfDocFontReady(data) { - var id = data[0]; - var font = new FontShape(data[1]); + messageHandler.on('page_error', function pdfDocError(data) { + var page = this.pageCache[data.pageNum]; + if (page.displayReadyPromise) + page.displayReadyPromise.reject(data.error); + else + error(data.error); + }, this); - // If there is no string, then there is nothing to attach to the DOM. - if (!font.str) { - this.objs.resolve(id, font); - } else { - this.objs.setData(id, font); - } - }.bind(this)); + messageHandler.on('jpeg_decode', function(data, promise) { + var imageData = data[0]; + var components = data[1]; + if (components != 3 && components != 1) + error('Only 3 component or 1 component can be returned'); + + var img = new Image(); + img.onload = (function messageHandler_onloadClosure() { + var width = img.width; + var height = img.height; + var size = width * height; + var rgbaLength = size * 4; + var buf = new Uint8Array(size * components); + var tmpCanvas = createScratchCanvas(width, height); + var tmpCtx = tmpCanvas.getContext('2d'); + tmpCtx.drawImage(img, 0, 0); + var data = tmpCtx.getImageData(0, 0, width, height).data; + + if (components == 3) { + for (var i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { + buf[j] = data[i]; + buf[j + 1] = data[i + 1]; + buf[j + 2] = data[i + 2]; + } + } else if (components == 1) { + for (var i = 0, j = 0; i < rgbaLength; i += 4, j++) { + buf[j] = data[i]; + } + } + promise.resolve({ data: buf, width: width, height: height}); + }).bind(this); + var src = 'data:image/jpeg;base64,' + window.btoa(imageData); + img.src = src; + }); setTimeout(function pdfDocFontReadySetTimeout() { messageHandler.send('doc', this.data); @@ -606,21 +833,22 @@ var PDFDoc = (function pdfDoc() { }, get numPages() { - return this.pdf.numPages; + return this.pdfModel.numPages; }, - startRendering: function pdfDocStartRendering(page) { + startRendering: function PDFDoc_startRendering(page) { // The worker might not be ready to receive the page request yet. this.workerReadyPromise.then(function pdfDocStartRenderingThen() { + page.stats.time('Page Request'); this.messageHandler.send('page_request', page.pageNumber + 1); }.bind(this)); }, - getPage: function pdfDocGetPage(n) { + getPage: function PDFDoc_getPage(n) { if (this.pageCache[n]) return this.pageCache[n]; - var page = this.pdf.getPage(n); + var page = this.pdfModel.getPage(n); // Add a reference to the objects such that Page can forward the reference // to the CanvasGraphics and so on. page.objs = this.objs; @@ -628,7 +856,7 @@ var PDFDoc = (function pdfDoc() { return (this.pageCache[n] = page); }, - destroy: function pdfDocDestroy() { + destroy: function PDFDoc_destroy() { if (this.worker) this.worker.terminate(); @@ -645,7 +873,7 @@ var PDFDoc = (function pdfDoc() { } }; - return constructor; + return PDFDoc; })(); globalScope.PDFJS.PDFDoc = PDFDoc; diff --git a/apps/files_pdfviewer/js/pdfjs/src/crypto.js b/apps/files_pdfviewer/js/pdfjs/src/crypto.js old mode 100755 new mode 100644 index 95559864483..038c0e3327f --- a/apps/files_pdfviewer/js/pdfjs/src/crypto.js +++ b/apps/files_pdfviewer/js/pdfjs/src/crypto.js @@ -3,8 +3,8 @@ 'use strict'; -var ARCFourCipher = (function arcFourCipher() { - function constructor(key) { +var ARCFourCipher = (function ARCFourCipherClosure() { + function ARCFourCipher(key) { this.a = 0; this.b = 0; var s = new Uint8Array(256); @@ -20,8 +20,8 @@ var ARCFourCipher = (function arcFourCipher() { this.s = s; } - constructor.prototype = { - encryptBlock: function arcFourCipherEncryptBlock(data) { + ARCFourCipher.prototype = { + encryptBlock: function ARCFourCipher_encryptBlock(data) { var i, n = data.length, tmp, tmp2; var a = this.a, b = this.b, s = this.s; var output = new Uint8Array(n); @@ -39,12 +39,12 @@ var ARCFourCipher = (function arcFourCipher() { return output; } }; - constructor.prototype.decryptBlock = constructor.prototype.encryptBlock; + ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock; - return constructor; + return ARCFourCipher; })(); -var calculateMD5 = (function calculateMD5() { +var calculateMD5 = (function calculateMD5Closure() { var r = new Uint8Array([ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, @@ -128,20 +128,20 @@ var calculateMD5 = (function calculateMD5() { return hash; })(); -var NullCipher = (function nullCipher() { - function constructor() { +var NullCipher = (function NullCipherClosure() { + function NullCipher() { } - constructor.prototype = { - decryptBlock: function nullCipherDecryptBlock(data) { + NullCipher.prototype = { + decryptBlock: function NullCipher_decryptBlock(data) { return data; } }; - return constructor; + return NullCipher; })(); -var AES128Cipher = (function aes128Cipher() { +var AES128Cipher = (function AES128CipherClosure() { var rcon = new Uint8Array([ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, @@ -330,7 +330,7 @@ var AES128Cipher = (function aes128Cipher() { return state; } - function constructor(key) { + function AES128Cipher(key) { this.key = expandKey128(key); this.buffer = new Uint8Array(16); this.bufferPosition = 0; @@ -370,8 +370,8 @@ var AES128Cipher = (function aes128Cipher() { return output; } - constructor.prototype = { - decryptBlock: function aes128CipherDecryptBlock(data) { + AES128Cipher.prototype = { + decryptBlock: function AES128Cipher_decryptBlock(data) { var i, sourceLength = data.length; var buffer = this.buffer, bufferLength = this.bufferPosition; // waiting for IV values -- they are at the start of the stream @@ -391,16 +391,16 @@ var AES128Cipher = (function aes128Cipher() { } }; - return constructor; + return AES128Cipher; })(); -var CipherTransform = (function cipherTransform() { - function constructor(stringCipherConstructor, streamCipherConstructor) { +var CipherTransform = (function CipherTransformClosure() { + function CipherTransform(stringCipherConstructor, streamCipherConstructor) { this.stringCipherConstructor = stringCipherConstructor; this.streamCipherConstructor = streamCipherConstructor; } - constructor.prototype = { - createStream: function cipherTransformCreateStream(stream) { + CipherTransform.prototype = { + createStream: function CipherTransform_createStream(stream) { var cipher = new this.streamCipherConstructor(); return new DecryptStream(stream, function cipherTransformDecryptStream(data) { @@ -408,17 +408,17 @@ var CipherTransform = (function cipherTransform() { } ); }, - decryptString: function cipherTransformDecryptString(s) { + decryptString: function CipherTransform_decryptString(s) { var cipher = new this.stringCipherConstructor(); var data = stringToBytes(s); data = cipher.decryptBlock(data); return bytesToString(data); } }; - return constructor; + return CipherTransform; })(); -var CipherTransformFactory = (function cipherTransformFactory() { +var CipherTransformFactory = (function CipherTransformFactoryClosure() { function prepareKeyData(fileId, password, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata) { var defaultPasswordBytes = new Uint8Array([ @@ -490,7 +490,7 @@ var CipherTransformFactory = (function cipherTransformFactory() { var identityName = new Name('Identity'); - function constructor(dict, fileId, password) { + function CipherTransformFactory(dict, fileId, password) { var filter = dict.get('Filter'); if (!isName(filter) || filter.name != 'Standard') error('unknown encryption method'); @@ -570,12 +570,11 @@ var CipherTransformFactory = (function cipherTransformFactory() { }; } error('Unknown crypto method'); - return null; } - constructor.prototype = { - createCipherTransform: function buildCipherCreateCipherTransform(num, - gen) { + CipherTransformFactory.prototype = { + createCipherTransform: + function CipherTransformFactory_createCipherTransform(num, gen) { if (this.algorithm == 4) { return new CipherTransform( buildCipherConstructor(this.cf, this.stmf, @@ -592,6 +591,6 @@ var CipherTransformFactory = (function cipherTransformFactory() { } }; - return constructor; + return CipherTransformFactory; })(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/evaluator.js b/apps/files_pdfviewer/js/pdfjs/src/evaluator.js old mode 100755 new mode 100644 index a863a531ec5..350ab20b2c5 --- a/apps/files_pdfviewer/js/pdfjs/src/evaluator.js +++ b/apps/files_pdfviewer/js/pdfjs/src/evaluator.js @@ -3,8 +3,8 @@ 'use strict'; -var PartialEvaluator = (function partialEvaluator() { - function constructor(xref, handler, uniquePrefix) { +var PartialEvaluator = (function PartialEvaluatorClosure() { + function PartialEvaluator(xref, handler, uniquePrefix) { this.state = new EvalState(); this.stateStack = []; @@ -111,14 +111,27 @@ var PartialEvaluator = (function partialEvaluator() { EX: 'endCompat' }; - constructor.prototype = { - getIRQueue: function partialEvaluatorGetIRQueue(stream, resources, - queue, dependency) { + function splitCombinedOperations(operations) { + // Two operations can be combined together, trying to find which two + // operations were concatenated. + for (var i = operations.length - 1; i > 0; i--) { + var op1 = operations.substring(0, i), op2 = operations.substring(i); + if (op1 in OP_MAP && op2 in OP_MAP) + return [op1, op2]; // operations found + } + return null; + } + + PartialEvaluator.prototype = { + getOperatorList: function PartialEvaluator_getOperatorList(stream, + resources, + dependency, + queue) { var self = this; var xref = this.xref; var handler = this.handler; - var uniquePrefix = this.uniquePrefix; + var uniquePrefix = this.uniquePrefix || ''; function insertDependency(depList) { fnArray.push('dependency'); @@ -131,18 +144,14 @@ var PartialEvaluator = (function partialEvaluator() { } } - function handleSetFont(fontName, fontRef) { + function handleSetFont(fontName, font) { var loadedName = null; var fontRes = resources.get('Font'); - // TODO: TOASK: Is it possible to get here? If so, what does - // args[0].name should be like??? assert(fontRes, 'fontRes not available'); - fontRes = xref.fetchIfRef(fontRes); - fontRef = fontRef || fontRes.get(fontName); - var font = xref.fetchIfRef(fontRef); + font = xref.fetchIfRef(font) || fontRes.get(fontName); assertWellFormed(isDict(font)); if (!font.translated) { font.translated = self.translateFont(font, xref, resources, @@ -155,6 +164,15 @@ var PartialEvaluator = (function partialEvaluator() { font.loadedName = loadedName; var translated = font.translated; + // Convert the file to an ArrayBuffer which will be turned back into + // a Stream in the main thread. + if (translated.file) + translated.file = translated.file.getBytes(); + if (translated.properties.file) { + translated.properties.file = + translated.properties.file.getBytes(); + } + handler.send('obj', [ loadedName, 'Font', @@ -168,7 +186,7 @@ var PartialEvaluator = (function partialEvaluator() { // Ensure the font is ready before the font is set // and later on used for drawing. - // TODO: This should get insert to the IRQueue only once per + // OPTIMIZE: This should get insert to the operatorList only once per // page. insertDependency([loadedName]); return loadedName; @@ -179,65 +197,60 @@ var PartialEvaluator = (function partialEvaluator() { var w = dict.get('Width', 'W'); var h = dict.get('Height', 'H'); - if (image instanceof JpegStream && image.isNative) { - var objId = 'img_' + uniquePrefix + (++self.objIdCounter); - handler.send('obj', [objId, 'JpegStream', image.getIR()]); - - // Add the dependency on the image object. - insertDependency([objId]); - - // The normal fn. - fn = 'paintJpegXObject'; - args = [objId, w, h]; - + var imageMask = dict.get('ImageMask', 'IM') || false; + if (imageMask) { + // This depends on a tmpCanvas beeing filled with the + // current fillStyle, such that processing the pixel + // data can't be done here. Instead of creating a + // complete PDFImage, only read the information needed + // for later. + + var width = dict.get('Width', 'W'); + var height = dict.get('Height', 'H'); + var bitStrideLength = (width + 7) >> 3; + var imgArray = image.getBytes(bitStrideLength * height); + var decode = dict.get('Decode', 'D'); + var inverseDecode = !!decode && decode[0] > 0; + + fn = 'paintImageMaskXObject'; + args = [imgArray, inverseDecode, width, height]; return; } - // Needs to be rendered ourself. - - // Figure out if the image has an imageMask. - var imageMask = dict.get('ImageMask', 'IM') || false; - // If there is no imageMask, create the PDFImage and a lot // of image processing can be done here. - if (!imageMask) { - var imageObj = new PDFImage(xref, resources, image, inline); - - if (imageObj.imageMask) { - throw 'Can\'t handle this in the web worker :/'; - } - - var imgData = { - width: w, - height: h, - data: new Uint8Array(w * h * 4) - }; - var pixels = imgData.data; - imageObj.fillRgbaBuffer(pixels, imageObj.decode); - - fn = 'paintImageXObject'; - args = [imgData]; + var objId = 'img_' + uniquePrefix + (++self.objIdCounter); + insertDependency([objId]); + args = [objId, w, h]; + + var softMask = dict.get('SMask', 'IM') || false; + if (!softMask && image instanceof JpegStream && + image.isNativelySupported(xref, resources)) { + // These JPEGs don't need any more processing so we can just send it. + fn = 'paintJpegXObject'; + handler.send('obj', [objId, 'JpegStream', image.getIR()]); return; } - // This depends on a tmpCanvas beeing filled with the - // current fillStyle, such that processing the pixel - // data can't be done here. Instead of creating a - // complete PDFImage, only read the information needed - // for later. - fn = 'paintImageMaskXObject'; - - var width = dict.get('Width', 'W'); - var height = dict.get('Height', 'H'); - var bitStrideLength = (width + 7) >> 3; - var imgArray = image.getBytes(bitStrideLength * height); - var decode = dict.get('Decode', 'D'); - var inverseDecode = !!decode && decode[0] > 0; - - args = [imgArray, inverseDecode, width, height]; + fn = 'paintImageXObject'; + + PDFImage.buildImage(function(imageObj) { + var drawWidth = imageObj.drawWidth; + var drawHeight = imageObj.drawHeight; + var imgData = { + width: drawWidth, + height: drawHeight, + data: new Uint8Array(drawWidth * drawHeight * 4) + }; + var pixels = imgData.data; + imageObj.fillRgbaBuffer(pixels, drawWidth, drawHeight); + handler.send('obj', [objId, 'Image', imgData]); + }, handler, xref, resources, image, inline); } - uniquePrefix = uniquePrefix || ''; + if (!queue) + queue = {}; + if (!queue.argsArray) { queue.argsArray = []; } @@ -248,45 +261,48 @@ var PartialEvaluator = (function partialEvaluator() { var fnArray = queue.fnArray, argsArray = queue.argsArray; var dependencyArray = dependency || []; - resources = xref.fetchIfRef(resources) || new Dict(); - var xobjs = xref.fetchIfRef(resources.get('XObject')) || new Dict(); - var patterns = xref.fetchIfRef(resources.get('Pattern')) || new Dict(); - var parser = new Parser(new Lexer(stream), false); + resources = resources || new Dict(); + var xobjs = resources.get('XObject') || new Dict(); + var patterns = resources.get('Pattern') || new Dict(); + var parser = new Parser(new Lexer(stream), false, xref); var res = resources; + var hasNextObj = false, nextObj; var args = [], obj; - var getObjBt = function getObjBt() { - parser = this.oldParser; - return { name: 'BT' }; - }; var TILING_PATTERN = 1, SHADING_PATTERN = 2; - while (!isEOF(obj = parser.getObj())) { + while (true) { + if (hasNextObj) { + obj = nextObj; + hasNextObj = false; + } else { + obj = parser.getObj(); + if (isEOF(obj)) + break; + } + if (isCmd(obj)) { var cmd = obj.cmd; var fn = OP_MAP[cmd]; if (!fn) { // invalid content command, trying to recover - if (cmd.substr(-2) == 'BT') { - fn = OP_MAP[cmd.substr(0, cmd.length - 2)]; - // feeding 'BT' on next interation - parser = { - getObj: getObjBt, - oldParser: parser - }; + var cmds = splitCombinedOperations(cmd); + if (cmds) { + cmd = cmds[0]; + fn = OP_MAP[cmd]; + // feeding other command on the next interation + hasNextObj = true; + nextObj = Cmd.get(cmds[1]); } } assertWellFormed(fn, 'Unknown command "' + cmd + '"'); // TODO figure out how to type-check vararg functions if ((cmd == 'SCN' || cmd == 'scn') && !args[args.length - 1].code) { - // Use the IR version for setStroke/FillColorN. - fn += '_IR'; - // compile tiling patterns var patternName = args[args.length - 1]; // SCN/scn applies patterns along with normal colors if (isName(patternName)) { - var pattern = xref.fetchIfRef(patterns.get(patternName.name)); + var pattern = patterns.get(patternName.name); if (pattern) { var dict = isStream(pattern) ? pattern.dict : pattern; var typeNum = dict.get('PatternType'); @@ -294,21 +310,20 @@ var PartialEvaluator = (function partialEvaluator() { if (typeNum == TILING_PATTERN) { // Create an IR of the pattern code. var depIdx = dependencyArray.length; - var queueObj = {}; - var codeIR = this.getIRQueue(pattern, dict.get('Resources'), - queueObj, dependencyArray); + var operatorList = this.getOperatorList(pattern, + dict.get('Resources') || resources, dependencyArray); // Add the dependencies that are required to execute the - // codeIR. + // operatorList. insertDependency(dependencyArray.slice(depIdx)); - args = TilingPattern.getIR(codeIR, dict, args); + args = TilingPattern.getIR(operatorList, dict, args); } else if (typeNum == SHADING_PATTERN) { - var shading = xref.fetchIfRef(dict.get('Shading')); + var shading = dict.get('Shading'); var matrix = dict.get('Matrix'); - var pattern = Pattern.parseShading(shading, matrix, xref, res, - null /*ctx*/); + var pattern = Pattern.parseShading(shading, matrix, xref, + res); args = pattern.getIR(); } else { error('Unkown PatternType ' + typeNum); @@ -320,7 +335,6 @@ var PartialEvaluator = (function partialEvaluator() { var name = args[0].name; var xobj = xobjs.get(name); if (xobj) { - xobj = xref.fetchIfRef(xobj); assertWellFormed(isStream(xobj), 'XObject should be a stream'); var type = xobj.dict.get('Subtype'); @@ -336,14 +350,18 @@ var PartialEvaluator = (function partialEvaluator() { fnArray.push('paintFormXObjectBegin'); argsArray.push([matrix, bbox]); - // This adds the IRQueue of the xObj to the current queue. + // This adds the operatorList of the xObj to the current queue. var depIdx = dependencyArray.length; - this.getIRQueue(xobj, xobj.dict.get('Resources'), queue, - dependencyArray); + // Pass in the current `queue` object. That means the `fnArray` + // and the `argsArray` in this scope is reused and new commands + // are added to them. + this.getOperatorList(xobj, + xobj.dict.get('Resources') || resources, + dependencyArray, queue); // Add the dependencies that are required to execute the - // codeIR. + // operatorList. insertDependency(dependencyArray.slice(depIdx)); fn = 'paintFormXObjectEnd'; @@ -367,28 +385,27 @@ var PartialEvaluator = (function partialEvaluator() { args = [ColorSpace.parseToIR(args[0], xref, resources)]; break; case 'shadingFill': - var shadingRes = xref.fetchIfRef(res.get('Shading')); + var shadingRes = res.get('Shading'); if (!shadingRes) error('No shading resource found'); - var shading = xref.fetchIfRef(shadingRes.get(args[0].name)); + var shading = shadingRes.get(args[0].name); if (!shading) error('No shading object found'); - var shadingFill = Pattern.parseShading(shading, null, xref, res, - null); + var shadingFill = Pattern.parseShading(shading, null, xref, res); var patternIR = shadingFill.getIR(); args = [patternIR]; fn = 'shadingFill'; break; case 'setGState': var dictName = args[0]; - var extGState = xref.fetchIfRef(resources.get('ExtGState')); + var extGState = resources.get('ExtGState'); if (!isDict(extGState) || !extGState.has(dictName.name)) break; - var gsState = xref.fetchIfRef(extGState.get(dictName.name)); + var gsState = extGState.get(dictName.name); // This array holds the converted/processed state data. var gsStateObj = []; @@ -453,10 +470,7 @@ var PartialEvaluator = (function partialEvaluator() { } } - return { - fnArray: fnArray, - argsArray: argsArray - }; + return queue; }, extractDataStructures: function @@ -470,7 +484,7 @@ var PartialEvaluator = (function partialEvaluator() { if (properties.composite) { // CIDSystemInfo helps to match CID to glyphs - var cidSystemInfo = xref.fetchIfRef(dict.get('CIDSystemInfo')); + var cidSystemInfo = dict.get('CIDSystemInfo'); if (isDict(cidSystemInfo)) { properties.cidSystemInfo = { registry: cidSystemInfo.get('Registry'), @@ -479,20 +493,24 @@ var PartialEvaluator = (function partialEvaluator() { }; } - var cidToGidMap = xref.fetchIfRef(dict.get('CIDToGIDMap')); + var cidToGidMap = dict.get('CIDToGIDMap'); if (isStream(cidToGidMap)) properties.cidToGidMap = this.readCidToGidMap(cidToGidMap); } + var flags = properties.flags; var differences = []; - var baseEncoding = Encodings.StandardEncoding; + var baseEncoding = !!(flags & FontFlags.Symbolic) ? + Encodings.symbolsEncoding : Encodings.StandardEncoding; var hasEncoding = dict.has('Encoding'); if (hasEncoding) { - var encoding = xref.fetchIfRef(dict.get('Encoding')); + var encoding = dict.get('Encoding'); if (isDict(encoding)) { var baseName = encoding.get('BaseEncoding'); if (baseName) baseEncoding = Encodings[baseName.name]; + else + hasEncoding = false; // base encoding was not provided // Load the differences between the base and original if (encoding.has('Differences')) { @@ -512,14 +530,14 @@ var PartialEvaluator = (function partialEvaluator() { error('Encoding is not a Name nor a Dict'); } } + properties.differences = differences; properties.baseEncoding = baseEncoding; properties.hasEncoding = hasEncoding; }, - readToUnicode: - function partialEvaluatorReadToUnicode(toUnicode, xref) { - var cmapObj = xref.fetchIfRef(toUnicode); + readToUnicode: function PartialEvaluator_readToUnicode(toUnicode, xref) { + var cmapObj = toUnicode; var charToUnicode = []; if (isName(cmapObj)) { var isIdentityMap = cmapObj.name.substr(0, 9) == 'Identity-'; @@ -532,9 +550,9 @@ var PartialEvaluator = (function partialEvaluator() { var cmap = cmapObj.getBytes(cmapObj.length); for (var i = 0, ii = cmap.length; i < ii; i++) { - var byte = cmap[i]; - if (byte == 0x20 || byte == 0x0D || byte == 0x0A || - byte == 0x3C || byte == 0x5B || byte == 0x5D) { + var octet = cmap[i]; + if (octet == 0x20 || octet == 0x0D || octet == 0x0A || + octet == 0x3C || octet == 0x5B || octet == 0x5D) { switch (token) { case 'usecmap': error('usecmap is not implemented'); @@ -554,9 +572,21 @@ var PartialEvaluator = (function partialEvaluator() { var startRange = tokens[j]; var endRange = tokens[j + 1]; var code = tokens[j + 2]; - while (startRange <= endRange) { - charToUnicode[startRange] = code++; - ++startRange; + if (code == 0xFFFF) { + // CMap is broken, assuming code == startRange + code = startRange; + } + if (isArray(code)) { + var codeindex = 0; + while (startRange <= endRange) { + charToUnicode[startRange] = code[codeindex++]; + ++startRange; + } + } else { + while (startRange <= endRange) { + charToUnicode[startRange] = code++; + ++startRange; + } } } break; @@ -579,7 +609,7 @@ var PartialEvaluator = (function partialEvaluator() { tokens.push(token); token = ''; } - switch (byte) { + switch (octet) { case 0x5B: // begin list parsing tokens.push(beginArrayToken); @@ -593,21 +623,39 @@ var PartialEvaluator = (function partialEvaluator() { tokens.push(items); break; } - } else if (byte == 0x3E) { + } else if (octet == 0x3E) { if (token.length) { - // parsing hex number - tokens.push(parseInt(token, 16)); - token = ''; + if (token.length <= 4) { + // parsing hex number + tokens.push(parseInt(token, 16)); + token = ''; + } else { + // parsing hex UTF-16BE numbers + var str = []; + for (var k = 0, kk = token.length; k < kk; k += 4) { + var b = parseInt(token.substr(k, 4), 16); + if (b <= 0x10) { + k += 4; + b = (b << 16) | parseInt(token.substr(k, 4), 16); + b -= 0x10000; + str.push(0xD800 | (b >> 10)); + str.push(0xDC00 | (b & 0x3FF)); + break; + } + str.push(b); + } + tokens.push(String.fromCharCode.apply(String, str)); + token = ''; + } } } else { - token += String.fromCharCode(byte); + token += String.fromCharCode(octet); } } } return charToUnicode; }, - readCidToGidMap: - function partialEvaluatorReadCidToGidMap(cidToGidStream) { + readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) { // Extract the encoding from the CIDToGIDMap var glyphsData = cidToGidStream.getBytes(); @@ -624,16 +672,16 @@ var PartialEvaluator = (function partialEvaluator() { return result; }, - extractWidths: function partialEvaluatorWidths(dict, + extractWidths: function PartialEvaluator_extractWidths(dict, xref, descriptor, properties) { var glyphsWidths = []; var defaultWidth = 0; if (properties.composite) { - defaultWidth = xref.fetchIfRef(dict.get('DW')) || 1000; + defaultWidth = dict.get('DW') || 1000; - var widths = xref.fetchIfRef(dict.get('W')); + var widths = dict.get('W'); if (widths) { var start = 0, end = 0; for (var i = 0, ii = widths.length; i < ii; i++) { @@ -654,7 +702,7 @@ var PartialEvaluator = (function partialEvaluator() { } } else { var firstChar = properties.firstChar; - var widths = xref.fetchIfRef(dict.get('Widths')); + var widths = dict.get('Widths'); if (widths) { var j = firstChar; for (var i = 0, ii = widths.length; i < ii; i++) @@ -676,7 +724,7 @@ var PartialEvaluator = (function partialEvaluator() { properties.widths = glyphsWidths; }, - getBaseFontMetrics: function getBaseFontMetrics(name) { + getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) { var defaultWidth = 0, widths = []; var glyphWidths = Metrics[stdFontMap[name] || name]; if (isNum(glyphWidths)) { @@ -691,8 +739,10 @@ var PartialEvaluator = (function partialEvaluator() { }; }, - translateFont: function partialEvaluatorTranslateFont(dict, xref, resources, - dependency) { + translateFont: function PartialEvaluator_translateFont(dict, + xref, + resources, + dependency) { var baseDict = dict; var type = dict.get('Subtype'); assertWellFormed(isName(type), 'invalid font Subtype'); @@ -707,10 +757,7 @@ var PartialEvaluator = (function partialEvaluator() { if (!df) return null; - if (isRef(df)) - df = xref.fetch(df); - - dict = xref.fetchIfRef(isRef(df) ? df : df[0]); + dict = isArray(df) ? xref.fetchIfRef(df[0]) : df; type = dict.get('Subtype'); assertWellFormed(isName(type), 'invalid font Subtype'); @@ -718,7 +765,7 @@ var PartialEvaluator = (function partialEvaluator() { } var maxCharIndex = composite ? 0xFFFF : 0xFF; - var descriptor = xref.fetchIfRef(dict.get('FontDescriptor')); + var descriptor = dict.get('FontDescriptor'); if (!descriptor) { if (type.name == 'Type3') { // FontDescriptor is only required for Type3 fonts when the document @@ -737,10 +784,18 @@ var PartialEvaluator = (function partialEvaluator() { baseFontName = baseFontName.name.replace(/[,_]/g, '-'); var metrics = this.getBaseFontMetrics(baseFontName); + // Simulating descriptor flags attribute + var fontNameWoStyle = baseFontName.split('-')[0]; + var flags = (serifFonts[fontNameWoStyle] || + (fontNameWoStyle.search(/serif/gi) != -1) ? FontFlags.Serif : 0) | + (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic : + FontFlags.Nonsymbolic); + var properties = { type: type.name, widths: metrics.widths, defaultWidth: metrics.defaultWidth, + flags: flags, firstChar: 0, lastChar: maxCharIndex }; @@ -752,34 +807,31 @@ var PartialEvaluator = (function partialEvaluator() { properties: properties }; } - } // According to the spec if 'FontDescriptor' is declared, 'FirstChar', - // 'LastChar' and 'Widths' should exists too, but some PDF encoders seems + // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem // to ignore this rule when a variant of a standart font is used. // TODO Fill the width array depending on which of the base font this is // a variant. - var firstChar = xref.fetchIfRef(dict.get('FirstChar')) || 0; - var lastChar = xref.fetchIfRef(dict.get('LastChar')) || maxCharIndex; - var fontName = xref.fetchIfRef(descriptor.get('FontName')); + var firstChar = dict.get('FirstChar') || 0; + var lastChar = dict.get('LastChar') || maxCharIndex; + var fontName = descriptor.get('FontName'); + // Some bad pdf's have a string as the font name. + if (isString(fontName)) + fontName = new Name(fontName); assertWellFormed(isName(fontName), 'invalid font name'); var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3'); if (fontFile) { - fontFile = xref.fetchIfRef(fontFile); if (fontFile.dict) { var subtype = fontFile.dict.get('Subtype'); if (subtype) subtype = subtype.name; var length1 = fontFile.dict.get('Length1'); - if (!isInt(length1)) - length1 = xref.fetchIfRef(length1); var length2 = fontFile.dict.get('Length2'); - if (!isInt(length2)) - length2 = xref.fetchIfRef(length2); } } @@ -808,15 +860,14 @@ var PartialEvaluator = (function partialEvaluator() { if (type.name === 'Type3') { properties.coded = true; - var charProcs = xref.fetchIfRef(dict.get('CharProcs')); - var fontResources = xref.fetchIfRef(dict.get('Resources')) || resources; + var charProcs = dict.get('CharProcs').getAll(); + var fontResources = dict.get('Resources') || resources; properties.resources = fontResources; - properties.charProcIRQueues = {}; - for (var key in charProcs.map) { - var glyphStream = xref.fetchIfRef(charProcs.map[key]); - var queueObj = {}; - properties.charProcIRQueues[key] = - this.getIRQueue(glyphStream, fontResources, queueObj, dependency); + properties.charProcOperatorList = {}; + for (var key in charProcs) { + var glyphStream = charProcs[key]; + properties.charProcOperatorList[key] = + this.getOperatorList(glyphStream, fontResources, dependency); } } @@ -829,11 +880,11 @@ var PartialEvaluator = (function partialEvaluator() { } }; - return constructor; + return PartialEvaluator; })(); -var EvalState = (function evalState() { - function constructor() { +var EvalState = (function EvalStateClosure() { + function EvalState() { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; @@ -850,8 +901,8 @@ var EvalState = (function evalState() { this.fillColorSpace = null; this.strokeColorSpace = null; } - constructor.prototype = { + EvalState.prototype = { }; - return constructor; + return EvalState; })(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/fonts.js b/apps/files_pdfviewer/js/pdfjs/src/fonts.js old mode 100755 new mode 100644 index 116bb4dfc71..7fdab8fbbf9 --- a/apps/files_pdfviewer/js/pdfjs/src/fonts.js +++ b/apps/files_pdfviewer/js/pdfjs/src/fonts.js @@ -3,8 +3,6 @@ 'use strict'; -var isWorker = (typeof window == 'undefined'); - /** * Maximum time to wait for a font to be loaded by font-face rules. */ @@ -13,6 +11,7 @@ var kMaxWaitForFontFace = 1000; // Unicode Private Use Area var kCmapGlyphOffset = 0xE000; var kSizeOfGlyphArea = 0x1900; +var kSymbolicFontGlyphOffset = 0xF000; // PDF Glyph Space Units are one Thousandth of a TextSpace Unit // except for Type 3 fonts @@ -21,269 +20,253 @@ var kPDFGlyphSpaceUnits = 1000; // Until hinting is fully supported this constant can be used var kHintingEnabled = false; +var FontFlags = { + FixedPitch: 1, + Serif: 2, + Symbolic: 4, + Script: 8, + Nonsymbolic: 32, + Italic: 64, + AllCap: 65536, + SmallCap: 131072, + ForceBold: 262144 +}; + var Encodings = { - get ExpertEncoding() { - return shadow(this, 'ExpertEncoding', ['', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', - 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', - 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', - 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', - 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', - 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', - 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', - 'threequartersemdash', 'periodsuperior', 'questionsmall', '', - 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', - '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', - 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', - 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', - 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', - 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', - 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', - 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', - 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', - 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', - 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', - 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', - 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', - 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', - 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', - 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', - 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', - 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', - 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', - 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', - 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', - 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', - 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', - 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', - 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', - 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', - 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', - 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', - 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', - 'Ydieresissmall' - ]); - }, - get MacExpertEncoding() { - return shadow(this, 'MacExpertEncoding', ['', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', - 'centoldstyle', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', - 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', - 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', - 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', - 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', - 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', - '', 'threequartersemdash', '', 'questionsmall', '', '', '', '', - 'Ethsmall', '', '', 'onequarter', 'onehalf', 'threequarters', - 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', - 'twothirds', '', '', '', '', '', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', - 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', - 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', - 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', - 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', - 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', - 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', - 'asuperior', 'centsuperior', '', '', '', '', 'Aacutesmall', - 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall', 'Atildesmall', - 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall', - 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall', - 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall', - 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall', - 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '', - 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior', - 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior', - 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior', - 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '', - 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior', - 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall', - 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '', - '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', - '', 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', - 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', - 'sixsuperior', 'sevensuperior', 'ninesuperior', 'zerosuperior', '', - 'esuperior', 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', - 'dsuperior', '', '', '', '', '', 'lsuperior', 'Ogoneksmall', - 'Brevesmall', 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', - 'commasuperior', 'periodsuperior', 'Dotaccentsmall', 'Ringsmall' - ]); - }, - get MacRomanEncoding() { - return shadow(this, 'MacRomanEncoding', ['', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', - 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', - 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', - 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', - 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', - 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'braceleft', 'bar', 'braceright', 'asciitilde', '', 'Adieresis', 'Aring', - 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', - 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', - 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', - 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', - 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', - 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', - 'germandbls', 'registered', 'copyright', 'trademark', 'acute', - 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', - 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', - 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', - 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', - 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', - 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', - 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', - 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', - 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', - 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', - 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', - 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', - 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', - 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', - 'hungarumlaut', 'ogonek', 'caron' - ]); - }, - get StandardEncoding() { - return shadow(this, 'StandardEncoding', ['', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', - 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', - 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', - 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', - 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', - 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', - 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', 'exclamdown', - 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', - 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', - 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl', - 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', - 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', - 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', - 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', - 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', - 'ordfeminine', '', '', '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', - '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', 'lslash', - 'oslash', 'oe', 'germandbls' - ]); - }, - get WinAnsiEncoding() { - return shadow(this, 'WinAnsiEncoding', ['', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', - 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', - 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', - 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', - 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', - 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', - 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'braceleft', 'bar', 'braceright', 'asciitilde', 'bullet', 'Euro', - 'bullet', 'quotesinglbase', 'florin', 'quotedblbase', 'ellipsis', - 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron', - 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', - 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', - 'endash', 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', - 'oe', 'bullet', 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', - 'sterling', 'currency', 'yen', 'brokenbar', 'section', 'dieresis', - 'copyright', 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', - 'registered', 'macron', 'degree', 'plusminus', 'twosuperior', - 'threesuperior', 'acute', 'mu', 'paragraph', 'periodcentered', - 'cedilla', 'onesuperior', 'ordmasculine', 'guillemotright', 'onequarter', - 'onehalf', 'threequarters', 'questiondown', 'Agrave', 'Aacute', - 'Acircumflex', 'Atilde', 'Adieresis', 'Aring', 'AE', 'Ccedilla', - 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute', - 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', 'Oacute', - 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', 'Ugrave', - 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', 'germandbls', - 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', 'aring', 'ae', - 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', - 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', - 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', - 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn', - 'ydieresis' - ]); - }, - get symbolsEncoding() { - return shadow(this, 'symbolsEncoding', ['', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', 'space', 'exclam', 'universal', 'numbersign', - 'existential', 'percent', 'ampersand', 'suchthat', 'parenleft', - 'parenright', 'asteriskmath', 'plus', 'comma', 'minus', 'period', - 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', - 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', - 'question', 'congruent', 'Alpha', 'Beta', 'Chi', 'Delta', 'Epsilon', - 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', 'Lambda', 'Mu', 'Nu', - 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'sigma1', - 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', 'therefore', 'bracketright', - 'perpendicular', 'underscore', 'radicalex', 'alpha', 'beta', 'chi', - 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', 'phi1', 'kappa', - 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho', 'sigma', 'tau', - 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', 'braceleft', 'bar', - 'braceright', 'similar', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal', 'fraction', - 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', 'arrowboth', - 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree', 'plusminus', - 'second', 'greaterequal', 'multiply', 'proportional', 'partialdiff', - 'bullet', 'divide', 'notequal', 'equivalence', 'approxequal', 'ellipsis', - 'arrowvertex', 'arrowhorizex', 'carriagereturn', 'aleph', 'Ifraktur', - 'Rfraktur', 'weierstrass', 'circlemultiply', 'circleplus', 'emptyset', - 'intersection', 'union', 'propersuperset', 'reflexsuperset', 'notsubset', - 'propersubset', 'reflexsubset', 'element', 'notelement', 'angle', - 'gradient', 'registerserif', 'copyrightserif', 'trademarkserif', - 'product', 'radical', 'dotmath', 'logicalnot', 'logicaland', 'logicalor', - 'arrowdblboth', 'arrowdblleft', 'arrowdblup', 'arrowdblright', - 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', 'copyrightsans', - 'trademarksans', 'summation', 'parenlefttp', 'parenleftex', - 'parenleftbt', 'bracketlefttp', 'bracketleftex', 'bracketleftbt', - 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex', '', - 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', - 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', - 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', - 'bracerightbt' - ]); - }, - get zapfDingbatsEncoding() { - return shadow(this, 'zapfDingbatsEncoding', ['', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', 'space', 'a1', 'a2', 'a202', 'a3', 'a4', - 'a5', 'a119', 'a118', 'a117', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', - 'a105', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', - 'a26', 'a27', 'a28', 'a6', 'a7', 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', - 'a32', 'a33', 'a34', 'a35', 'a36', 'a37', 'a38', 'a39', 'a40', 'a41', - 'a42', 'a43', 'a44', 'a45', 'a46', 'a47', 'a48', 'a49', 'a50', 'a51', - 'a52', 'a53', 'a54', 'a55', 'a56', 'a57', 'a58', 'a59', 'a60', 'a61', - 'a62', 'a63', 'a64', 'a65', 'a66', 'a67', 'a68', 'a69', 'a70', 'a71', - 'a72', 'a73', 'a74', 'a203', 'a75', 'a204', 'a76', 'a77', 'a78', 'a79', - 'a81', 'a82', 'a83', 'a84', 'a97', 'a98', 'a99', 'a100', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103', - 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120', - 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129', - 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138', - 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147', - 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156', - 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165', - 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173', - 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180', - 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', - 'a185', 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', - 'a191' - ]); - } + ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', + 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', + 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', + 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', + 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', + 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', + 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', + 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', + 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', + 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', + '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', + 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', + 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', + 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', + 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', + 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', + 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', + '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', + 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', + 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', + 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', + 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', + 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', + 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', + 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', + 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', + 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', + 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', + 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', + 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', + 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', + 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', + 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', + 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', + 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', + 'Ydieresissmall'], + MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle', + 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', + 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', + 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', + 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', + 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', + 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '', + 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter', + 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', + 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff', + 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', + 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall', + 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', + 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', + 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', + 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', + 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '', + 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall', + 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall', + 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall', + 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall', + 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '', + 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior', + 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior', + 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior', + 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '', + 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior', + 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall', + 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '', + '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '', + 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior', + 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', + 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior', + 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior', + '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall', + 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior', + 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'], + MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', + 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', + 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', + 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', + 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', + 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', + 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', + 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', + 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', + 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', + 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', + 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', + 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', + 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', + 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', + 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', + 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', + 'guillemotright', 'ellipsis', '', 'Agrave', 'Atilde', 'Otilde', 'OE', + 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', + 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', + 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', + 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', + 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', + 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', + 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', + 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', + 'ogonek', 'caron'], + StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', + 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', + 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', + 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', + 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', + 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown', + 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', + 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', + 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl', + 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', + 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', + 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', + 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', + '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', + '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', + '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'], + WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', + 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', + 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', + 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', + 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', + 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase', + 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron', + 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft', + 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash', + 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet', + 'zcaron', 'Ydieresis', '', 'exclamdown', 'cent', 'sterling', + 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright', + 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered', + 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute', + 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior', + 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters', + 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis', + 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', + 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', + 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', + 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', + 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', + 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', + 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', + 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', + 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn', + 'ydieresis'], + symbolsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent', + 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus', + 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', + 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', + 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi', + 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', + 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau', + 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', + 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex', + 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', + 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho', + 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', + 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal', + 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', + 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree', + 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional', + 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence', + 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn', + 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply', + 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset', + 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element', + 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif', + 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot', + 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup', + 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', + 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp', + 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex', + 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex', + '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', + 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', + 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', + 'bracerightbt'], + zapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117', + 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19', + 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7', + 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36', + 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46', + 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56', + 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66', + 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75', + 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97', + 'a98', 'a99', 'a100', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', 'a101', 'a102', 'a103', 'a104', 'a106', 'a107', 'a108', 'a112', + 'a111', 'a110', 'a109', 'a120', 'a121', 'a122', 'a123', 'a124', 'a125', + 'a126', 'a127', 'a128', 'a129', 'a130', 'a131', 'a132', 'a133', 'a134', + 'a135', 'a136', 'a137', 'a138', 'a139', 'a140', 'a141', 'a142', 'a143', + 'a144', 'a145', 'a146', 'a147', 'a148', 'a149', 'a150', 'a151', 'a152', + 'a153', 'a154', 'a155', 'a156', 'a157', 'a158', 'a159', 'a160', 'a161', + 'a163', 'a164', 'a196', 'a165', 'a192', 'a166', 'a167', 'a168', 'a169', + 'a170', 'a171', 'a172', 'a173', 'a162', 'a174', 'a175', 'a176', 'a177', + 'a178', 'a179', 'a193', 'a180', 'a199', 'a181', 'a200', 'a182', '', 'a201', + 'a183', 'a184', 'a197', 'a185', 'a194', 'a198', 'a186', 'a195', 'a187', + 'a188', 'a189', 'a190', 'a191'] }; /** @@ -341,6 +324,21 @@ var stdFontMap = { 'TimesNewRomanPSMT-Italic': 'Times-Italic' }; +/** + * Holds the map of the non-standard fonts that might be included as a standard + * fonts without glyph data. + */ +var nonStdFontMap = { + 'ComicSansMS': 'Comic Sans MS', + 'ComicSansMS-Bold': 'Comic Sans MS-Bold', + 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic', + 'ComicSansMS-Italic': 'Comic Sans MS-Italic', + 'LucidaConsole': 'Courier', + 'LucidaConsole-Bold': 'Courier-Bold', + 'LucidaConsole-BoldItalic': 'Courier-BoldOblique', + 'LucidaConsole-Italic': 'Courier-Oblique' +}; + var serifFonts = { 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true, 'Aldus': true, 'Alexandria': true, 'Algerian': true, @@ -388,13 +386,30 @@ var serifFonts = { 'Wide Latin': true, 'Windsor': true, 'XITS': true }; +var symbolsFonts = { + 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true +}; + +// Some characters, e.g. copyrightserif, mapped to the private use area and +// might not be displayed using standard fonts. Mapping/hacking well-known chars +// to the similar equivalents in the normal characters range. +function mapPrivateUseChars(code) { + switch (code) { + case 0xF8E9: // copyrightsans + case 0xF6D9: // copyrightserif + return 0x00A9; // copyright + default: + return code; + } +} + var FontLoader = { listeningForFontLoad: false, bind: function fontLoaderBind(fonts, callback) { function checkFontsLoaded() { - for (var i = 0, ii = objs.length; i < ii; i++) { - var fontObj = objs[i]; + for (var i = 0, ii = fonts.length; i < ii; i++) { + var fontObj = fonts[i]; if (fontObj.loading) { return false; } @@ -407,52 +422,45 @@ var FontLoader = { return true; } - var rules = [], names = [], objs = []; + var rules = [], names = [], fontsToLoad = []; + var fontCreateTimer = 0; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; - // If there is already a fontObj on the font, then it was loaded/attached - // to the page already and we don't have to do anything for this font - // here future. - if (font.fontObj) { + // Add the font to the DOM only once or skip if the font + // is already loaded. + if (font.attached || font.loading == false) { continue; } + font.attached = true; - var obj = new Font(font.name, font.file, font.properties); - - // Store the fontObj on the font such that `setFont` in CanvasGraphics - // can reuse it later again. - font.fontObj = obj; - - objs.push(obj); + fontsToLoad.push(font); var str = ''; - var data = obj.data; + var data = font.data; if (data) { var length = data.length; for (var j = 0; j < length; j++) str += String.fromCharCode(data[j]); - var rule = isWorker ? obj.bindWorker(str) : obj.bindDOM(str); + var rule = font.bindDOM(str); if (rule) { rules.push(rule); - names.push(obj.loadedName); + names.push(font.loadedName); } } } this.listeningForFontLoad = false; if (!isWorker && rules.length) { - FontLoader.prepareFontLoadEvent(rules, names, objs); + FontLoader.prepareFontLoadEvent(rules, names, fontsToLoad); } if (!checkFontsLoaded()) { document.documentElement.addEventListener( 'pdfjsFontLoad', checkFontsLoaded, false); } - - return objs; }, // Set things up so that at least one pdfjsFontLoad event is // dispatched when all the @font-face |rules| for |names| have been @@ -460,7 +468,7 @@ var FontLoader = { // has already started in this (outer) document, so that they should // be ordered before the load in the subdocument. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, names, - objs) { + fonts) { /** Hack begin */ // There's no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is @@ -484,6 +492,15 @@ var FontLoader = { // The postMessage() hackery was added to work around chrome bug // 82402. + // Validate the names parameter -- the values can used to construct HTML. + if (!/^\w+$/.test(names.join(''))) { + error('Invalid font name(s): ' + names.join()); + + // Normally the error-function throws. But if a malicious code + // intercepts the function call then the return is needed. + return; + } + var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + @@ -501,8 +518,8 @@ var FontLoader = { 'message', function fontLoaderMessage(e) { var fontNames = JSON.parse(e.data); - for (var i = 0, ii = objs.length; i < ii; ++i) { - var font = objs[i]; + for (var i = 0, ii = fonts.length; i < ii; ++i) { + var font = fonts[i]; font.loading = false; } var evt = document.createEvent('Events'); @@ -530,7 +547,8 @@ var FontLoader = { src += ' window.onload = function fontLoaderOnload() {\n'; src += ' parent.postMessage(JSON.stringify(fontNames), "*");\n'; src += ' }'; - src += ''; + // Hack so the end script tag isn't counted if this is inline JS. + src += ''; for (var i = 0, ii = names.length; i < ii; ++i) { src += '

    Hi

    '; } @@ -719,20 +737,20 @@ function getUnicodeRangeFor(value) { return -1; } -function adaptUnicode(unicode) { - return (unicode <= 0x1F || (unicode >= 127 && unicode < kSizeOfGlyphArea)) ? - unicode + kCmapGlyphOffset : unicode; -} - -function isAdaptedUnicode(unicode) { - return unicode >= kCmapGlyphOffset && - unicode < kCmapGlyphOffset + kSizeOfGlyphArea; +function isRTLRangeFor(value) { + var range = UnicodeRanges[13]; + if (value >= range.begin && value < range.end) + return true; + range = UnicodeRanges[11]; + if (value >= range.begin && value < range.end) + return true; + return false; } function isSpecialUnicode(unicode) { return (unicode <= 0x1F || (unicode >= 127 && unicode < kSizeOfGlyphArea)) || - unicode >= kCmapGlyphOffset && - unicode < kCmapGlyphOffset + kSizeOfGlyphArea; + (unicode >= kCmapGlyphOffset && + unicode < kCmapGlyphOffset + kSizeOfGlyphArea); } /** @@ -743,18 +761,19 @@ function isSpecialUnicode(unicode) { * var type1Font = new Font("MyFontName", binaryFile, propertiesObject); * type1Font.bind(); */ -var Font = (function Font() { - var constructor = function font_constructor(name, file, properties) { +var Font = (function FontClosure() { + function Font(name, file, properties) { this.name = name; this.coded = properties.coded; - this.charProcIRQueues = properties.charProcIRQueues; + this.charProcOperatorList = properties.charProcOperatorList; this.resources = properties.resources; this.sizes = []; var names = name.split('+'); names = names.length > 1 ? names[1] : names[0]; names = names.split(/[-,_]/g)[0]; - this.serif = serifFonts[names] || (name.search(/serif/gi) != -1); + this.isSerifFont = !!(properties.flags & FontFlags.Serif); + this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic); var type = properties.type; this.type = type; @@ -762,7 +781,7 @@ var Font = (function Font() { // If the font is to be ignored, register it like an already loaded font // to avoid the cost of waiting for it be be loaded by the platform. if (properties.ignore) { - this.loadedName = this.serif ? 'serif' : 'sans-serif'; + this.loadedName = this.isSerifFont ? 'serif' : 'sans-serif'; this.loading = false; return; } @@ -771,21 +790,30 @@ var Font = (function Font() { this.widths = properties.widths; this.defaultWidth = properties.defaultWidth; this.composite = properties.composite; - this.toUnicode = properties.toUnicode; this.hasEncoding = properties.hasEncoding; this.fontMatrix = properties.fontMatrix; - if (properties.type == 'Type3') + this.widthMultiplier = 1.0; + if (properties.type == 'Type3') { + this.encoding = properties.baseEncoding; return; + } // Trying to fix encoding using glyph CIDSystemInfo. this.loadCidToUnicode(properties); + if (properties.toUnicode) + this.toUnicode = properties.toUnicode; + else + this.rebuildToUnicode(properties); + + this.toFontChar = this.buildToFontChar(this.toUnicode); + if (!file) { // The file data is not specified. Trying to fix the font name // to be used with the canvas.font. var fontName = name.replace(/[,_]/g, '-'); - fontName = stdFontMap[fontName] || fontName; + fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName; this.bold = (fontName.search(/bold/gi) != -1); this.italic = (fontName.search(/oblique/gi) != -1) || @@ -810,7 +838,7 @@ var Font = (function Font() { var subtype = properties.subtype; var cff = (subtype == 'Type1C' || subtype == 'CIDFontType0C') ? - new Type2CFF(file, properties) : new CFF(name, file, properties); + new CFFFont(file, properties) : new Type1Font(name, file, properties); // Wrap the CFF data inside an OTF font file data = this.convert(name, cff, properties); @@ -832,9 +860,10 @@ var Font = (function Font() { this.data = data; this.fontMatrix = properties.fontMatrix; + this.widthMultiplier = !properties.fontMatrix ? 1.0 : + 1.0 / properties.fontMatrix[0]; this.encoding = properties.baseEncoding; - this.hasShortCmap = properties.hasShortCmap; - this.loadedName = getUniqueName(); + this.loadedName = properties.loadedName; this.loading = true; }; @@ -887,6 +916,13 @@ var Font = (function Font() { String.fromCharCode(value & 0xff); }; + function safeString16(value) { + // clamp value to the 16-bit int range + value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value; + return String.fromCharCode((value >> 8) & 0xff) + + String.fromCharCode(value & 0xff); + }; + function string32(value) { return String.fromCharCode((value >> 24) & 0xff) + String.fromCharCode((value >> 16) & 0xff) + @@ -961,15 +997,15 @@ var Font = (function Font() { var ranges = []; for (var n = 0; n < length; ) { var start = codes[n].unicode; - var startCode = codes[n].code; + var codeIndices = [codes[n].code]; ++n; var end = start; while (n < length && end + 1 == codes[n].unicode) { + codeIndices.push(codes[n].code); ++end; ++n; } - var endCode = codes[n - 1].code; - ranges.push([start, end, startCode, endCode]); + ranges.push([start, end, codeIndices]); } return ranges; @@ -1012,17 +1048,16 @@ var Font = (function Font() { idDeltas += string16(0); idRangeOffsets += string16(offset); - var startCode = range[2]; - var endCode = range[3]; - for (var j = startCode; j <= endCode; ++j) - glyphsIds += string16(deltas[j]); + var codes = range[2]; + for (var j = 0, jj = codes.length; j < jj; ++j) + glyphsIds += string16(deltas[codes[j]]); } } else { for (var i = 0; i < segCount - 1; i++) { var range = ranges[i]; var start = range[0]; var end = range[1]; - var startCode = range[2]; + var startCode = range[2][0]; startCount += string16(start); endCount += string16(end); @@ -1226,13 +1261,13 @@ var Font = (function Font() { return nameTable; } - constructor.prototype = { + Font.prototype = { name: null, font: null, mimetype: null, encoding: null, - checkAndRepair: function font_checkAndRepair(name, font, properties) { + checkAndRepair: function Font_checkAndRepair(name, font, properties) { function readTableEntry(file) { var tag = file.getBytes(4); tag = String.fromCharCode(tag[0]) + @@ -1299,7 +1334,7 @@ var Font = (function Font() { properties.baseEncoding = encoding; } - function replaceCMapTable(cmap, font, properties) { + function readCMapTable(cmap, font) { var start = (font.start ? font.start : 0) + cmap.offset; font.pos = start; @@ -1316,7 +1351,7 @@ var Font = (function Font() { } // Check that table are sorted by platformID then encodingID, - records.sort(function fontReplaceCMapTableSort(a, b) { + records.sort(function fontReadCMapTableSort(a, b) { return ((a.platformID << 16) + a.encodingID) - ((b.platformID << 16) + b.encodingID); }); @@ -1371,16 +1406,15 @@ var Font = (function Font() { for (var j = 0; j < 256; j++) { var index = font.getByte(); if (index) { - var unicode = adaptUnicode(j); - glyphs.push({ unicode: unicode, code: j }); + glyphs.push({ unicode: j, code: j }); ids.push(index); } } - - properties.hasShortCmap = true; - - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids, + hasShortCmap: true + }; } else if (format == 4) { // re-creating the table in format 4 since the encoding // might be changed @@ -1432,17 +1466,18 @@ var Font = (function Font() { var glyphCode = offsetIndex < 0 ? j : offsets[offsetIndex + j - start]; glyphCode = (glyphCode + delta) & 0xFFFF; - if (glyphCode == 0 || isAdaptedUnicode(j)) + if (glyphCode == 0) continue; - var unicode = adaptUnicode(j); - glyphs.push({ unicode: unicode, code: j }); + glyphs.push({ unicode: j, code: j }); ids.push(glyphCode); } } - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids + }; } else if (format == 6) { // Format 6 is a 2-bytes dense mapping, which means the font data // lives glue together even if they are pretty far in the unicode @@ -1457,19 +1492,18 @@ var Font = (function Font() { for (var j = 0; j < entryCount; j++) { var glyphCode = int16(font.getBytes(2)); var code = firstCode + j; - if (isAdaptedUnicode(glyphCode)) - continue; - var unicode = adaptUnicode(code); - glyphs.push({ unicode: unicode, code: code }); + glyphs.push({ unicode: code, code: code }); ids.push(glyphCode); } - createGlyphNameMap(glyphs, ids, properties); - return cmap.data = createCMapTable(glyphs, ids); + return { + glyphs: glyphs, + ids: ids + }; } } - return cmap.data; + error('Unsupported cmap table format'); }; function sanitizeMetrics(font, header, metrics, numGlyphs) { @@ -1505,6 +1539,61 @@ var Font = (function Font() { } }; + function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart) { + if (sourceEnd - sourceStart <= 12) { + // glyph with data less than 12 is invalid one + return 0; + } + var glyf = source.subarray(sourceStart, sourceEnd); + var contoursCount = (glyf[0] << 8) | glyf[1]; + if (contoursCount & 0x8000) { + // complex glyph, writing as is + dest.set(glyf, destStart); + return glyf.length; + } + + var j = 10, flagsCount = 0; + for (var i = 0; i < contoursCount; i++) { + var endPoint = (glyf[j] << 8) | glyf[j + 1]; + flagsCount = endPoint + 1; + j += 2; + } + // skipping instructions + var instructionsLength = (glyf[j] << 8) | glyf[j + 1]; + j += 2 + instructionsLength; + // validating flags + var coordinatesLength = 0; + for (var i = 0; i < flagsCount; i++) { + var flag = glyf[j++]; + if (flag & 0xC0) { + // reserved flags must be zero, rejecting + return 0; + } + var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) + + ((flag & 4) ? 1 : (flag & 32) ? 0 : 2); + coordinatesLength += xyLength; + if (flag & 8) { + var repeat = glyf[j++]; + i += repeat; + coordinatesLength += repeat * xyLength; + } + } + var glyphDataLength = j + coordinatesLength; + if (glyphDataLength > glyf.length) { + // not enough data for coordinates + return 0; + } + if (glyf.length - glyphDataLength > 3) { + // truncating and aligning to 4 bytes the long glyph data + glyphDataLength = (glyphDataLength + 3) & ~3; + dest.set(glyf.subarray(0, glyphDataLength), destStart); + return glyphDataLength; + } + // glyph data is fine + dest.set(glyf, destStart); + return glyf.length; + } + function sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong) { var itemSize, itemDecode, itemEncode; @@ -1531,20 +1620,64 @@ var Font = (function Font() { }; } var locaData = loca.data; + // removing the invalid glyphs + var oldGlyfData = glyf.data; + var oldGlyfDataLength = oldGlyfData.length; + var newGlyfData = new Uint8Array(oldGlyfDataLength); var startOffset = itemDecode(locaData, 0); - var firstOffset = itemDecode(locaData, itemSize); - if (firstOffset - startOffset < 12 || startOffset > 0) { - // removing first glyph - glyf.data = glyf.data.subarray(firstOffset); - glyf.length -= firstOffset; - - itemEncode(locaData, 0, 0); - var i, pos = itemSize; - for (i = 1; i <= numGlyphs; ++i) { - itemEncode(locaData, pos, - itemDecode(locaData, pos) - firstOffset); - pos += itemSize; + var writeOffset = 0; + itemEncode(locaData, 0, writeOffset); + for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) { + var endOffset = itemDecode(locaData, j); + if (endOffset > oldGlyfDataLength) { + // glyph end offset points outside glyf data, rejecting the glyph + itemEncode(locaData, j, writeOffset); + startOffset = endOffset; + continue; } + + var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset, + newGlyfData, writeOffset); + writeOffset += newLength; + itemEncode(locaData, j, writeOffset); + startOffset = endOffset; + } + + if (writeOffset == 0) { + // glyf table cannot be empty -- redoing the glyf and loca tables + // to have single glyph with one point + var simpleGlyph = new Uint8Array( + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]); + for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) + itemEncode(locaData, j, simpleGlyph.length); + glyf.data = simpleGlyph; + return; + } + + glyf.data = newGlyfData.subarray(0, writeOffset); + } + + function findEmptyGlyphs(locaTable, isGlyphLocationsLong, emptyGlyphIds) { + var itemSize, itemDecode; + if (isGlyphLocationsLong) { + itemSize = 4; + itemDecode = function fontItemDecodeLong(data, offset) { + return (data[offset] << 24) | (data[offset + 1] << 16) | + (data[offset + 2] << 8) | data[offset + 3]; + }; + } else { + itemSize = 2; + itemDecode = function fontItemDecode(data, offset) { + return (data[offset] << 9) | (data[offset + 1] << 1); + }; + } + var data = locaTable.data, length = data.length; + var lastOffset = itemDecode(data, 0); + for (var i = itemSize, j = 0; i < length; i += itemSize, j++) { + var offset = itemDecode(data, i); + if (offset == lastOffset) + emptyGlyphIds[j] = true; + lastOffset = offset; } } @@ -1674,11 +1807,15 @@ var Font = (function Font() { sanitizeMetrics(font, hhea, hmtx, numGlyphs); sanitizeMetrics(font, vhea, vmtx, numGlyphs); + var isGlyphLocationsLong = int16([head.data[50], head.data[51]]); if (head && loca && glyf) { - var isGlyphLocationsLong = int16([head.data[50], head.data[51]]); sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong); } + var emptyGlyphIds = []; + if (glyf) + findEmptyGlyphs(loca, isGlyphLocationsLong, emptyGlyphIds); + // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth // Sometimes it's 0. That needs to be fixed if (hhea.data[10] == 0 && hhea.data[11] == 0) { @@ -1691,8 +1828,9 @@ var Font = (function Font() { readGlyphNameMap(post, properties); } - // Replace the old CMAP table with a shiny new one + var glyphs, ids; if (properties.type == 'CIDFontType2') { + // Replace the old CMAP table with a shiny new one // Type2 composite fonts map characters directly to glyphs so the cmap // table must be replaced. // canvas fillText will reencode some characters even if the font has a @@ -1708,19 +1846,236 @@ var Font = (function Font() { tables.push(cmap); } - var glyphs = []; - for (i = 1; i < numGlyphs; i++) { - if (isAdaptedUnicode(i)) - continue; + var cidToGidMap = properties.cidToGidMap || []; + var gidToCidMap = [0]; + if (cidToGidMap.length > 0) { + for (var j = cidToGidMap.length - 1; j >= 0; j--) { + var gid = cidToGidMap[j]; + if (gid) + gidToCidMap[gid] = j; + } + // filling the gaps using CID above the CIDs currently used in font + var nextCid = cidToGidMap.length; + for (var i = 1; i < numGlyphs; i++) { + if (!gidToCidMap[i]) + gidToCidMap[i] = nextCid++; + } + } - glyphs.push({ unicode: adaptUnicode(i) }); + glyphs = []; + ids = []; + + var usedUnicodes = []; + var unassignedUnicodeItems = []; + for (var i = 1; i < numGlyphs; i++) { + var cid = gidToCidMap[i] || i; + var unicode = this.toFontChar[cid]; + if (!unicode || typeof unicode !== 'number' || + isSpecialUnicode(unicode) || unicode in usedUnicodes) { + unassignedUnicodeItems.push(i); + continue; + } + usedUnicodes[unicode] = true; + glyphs.push({ unicode: unicode, code: cid }); + ids.push(i); + } + // trying to fit as many unassigned symbols as we can + // in the range allocated for the user defined symbols + var unusedUnicode = kCmapGlyphOffset; + for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) { + var i = unassignedUnicodeItems[j]; + var cid = gidToCidMap[i] || i; + while (unusedUnicode in usedUnicodes) + unusedUnicode++; + if (unusedUnicode >= kCmapGlyphOffset + kSizeOfGlyphArea) + break; + var unicode = unusedUnicode++; + this.toFontChar[cid] = unicode; + usedUnicodes[unicode] = true; + glyphs.push({ unicode: unicode, code: cid }); + ids.push(i); } - cmap.data = createCMapTable(glyphs); } else { - replaceCMapTable(cmap, font, properties); + var cmapTable = readCMapTable(cmap, font); + + glyphs = cmapTable.glyphs; + ids = cmapTable.ids; + + var hasShortCmap = !!cmapTable.hasShortCmap; + var toFontChar = this.toFontChar; + + if (hasShortCmap && ids.length == numGlyphs) { + // Fixes the short cmap tables -- some generators use incorrect + // glyph id. + for (var i = 0, ii = ids.length; i < ii; i++) + ids[i] = i; + } + + var unusedUnicode = kCmapGlyphOffset; + var glyphNames = properties.glyphNames || []; + var encoding = properties.baseEncoding; + var differences = properties.differences; + if (toFontChar && toFontChar.length > 0) { + // checking if cmap is just identity map + var isIdentity = true; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + if (glyphs[i].unicode != i + 1) { + isIdentity = false; + break; + } + } + // if it is, replacing with meaningful toUnicode values + if (isIdentity && !this.isSymbolicFont) { + var usedUnicodes = [], unassignedUnicodeItems = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var unicode = toFontChar[i + 1]; + if (!unicode || typeof unicode !== 'number' || + unicode in usedUnicodes) { + unassignedUnicodeItems.push(i); + continue; + } + glyphs[i].unicode = unicode; + usedUnicodes[unicode] = true; + } + for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) { + var i = unassignedUnicodeItems[j]; + while (unusedUnicode in usedUnicodes) + unusedUnicode++; + var cid = i + 1; + // override only if unicode mapping is not specified + if (!(cid in toFontChar)) + toFontChar[cid] = unusedUnicode; + glyphs[i].unicode = unusedUnicode++; + } + this.useToFontChar = true; + } + } + + // remove glyph references outside range of avaialable glyphs or empty + var glyphsRemoved = 0; + for (var i = ids.length - 1; i >= 0; i--) { + if (ids[i] < numGlyphs && + (!emptyGlyphIds[ids[i]] || this.isSymbolicFont)) + continue; + ids.splice(i, 1); + glyphs.splice(i, 1); + glyphsRemoved++; + } + + // checking if it's a "true" symbolic font + if (this.isSymbolicFont) { + var minUnicode = 0xFFFF, maxUnicode = 0; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var unicode = glyphs[i].unicode; + minUnicode = Math.min(minUnicode, unicode); + maxUnicode = Math.max(maxUnicode, unicode); + } + // high byte must be the same for min and max unicodes + if ((maxUnicode & 0xFF00) != (minUnicode & 0xFF00)) + this.isSymbolicFont = false; + } + + // heuristics: if removed more than 2 glyphs encoding WinAnsiEncoding + // does not set properly + if (glyphsRemoved > 2) { + warn('Switching TrueType encoding to MacRomanEncoding for ' + + this.name + ' font'); + encoding = Encodings.MacRomanEncoding; + } + + if (hasShortCmap && this.hasEncoding && !this.isSymbolicFont) { + // Re-encode short map encoding to unicode -- that simplifies the + // resolution of MacRoman encoded glyphs logic for TrueType fonts: + // copying all characters to private use area, all mapping all known + // glyphs to the unicodes. The glyphs and ids arrays will grow. + var usedUnicodes = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode; + var gid = ids[i]; + glyphs[i].unicode += kCmapGlyphOffset; + toFontChar[code] = glyphs[i].unicode; + + var glyphName = glyphNames[gid] || encoding[code]; + if (glyphName in GlyphsUnicode) { + var unicode = GlyphsUnicode[glyphName]; + if (unicode in usedUnicodes) + continue; + + usedUnicodes[unicode] = true; + glyphs.push({ + unicode: unicode, + code: glyphs[i].code + }); + ids.push(gid); + toFontChar[code] = unicode; + } + } + this.useToFontChar = true; + } else if (!this.isSymbolicFont && (this.hasEncoding || + properties.glyphNames || differences.length > 0)) { + // Re-encode cmap encoding to unicode, based on the 'post' table data + // diffrence array or base encoding + var reverseMap = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) + reverseMap[glyphs[i].unicode] = i; + + var newGlyphUnicodes = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode; + var changeCode = false; + var gid = ids[i]; + + var glyphName = glyphNames[gid]; + if (!glyphName) { + glyphName = differences[code] || encoding[code]; + changeCode = true; + } + if (glyphName in GlyphsUnicode) { + var unicode = GlyphsUnicode[glyphName]; + if (!unicode || reverseMap[unicode] === i) + continue; // unknown glyph name or in its own place + + newGlyphUnicodes[i] = unicode; + if (changeCode) + toFontChar[code] = unicode; + delete reverseMap[code]; + } + } + for (var index in newGlyphUnicodes) { + var unicode = newGlyphUnicodes[index]; + if (reverseMap[unicode]) { + // avoiding assigning to the same unicode + glyphs[index].unicode = unusedUnicode++; + continue; + } + glyphs[index].unicode = unicode; + reverseMap[unicode] = index; + } + this.useToFontChar = true; + } + + // Moving all symbolic font glyphs into 0xF000 - 0xF0FF range. + if (this.isSymbolicFont) { + for (var i = 0, ii = glyphs.length; i < ii; i++) { + var code = glyphs[i].unicode & 0xFF; + var fontCharCode = kSymbolicFontGlyphOffset | code; + glyphs[i].unicode = toFontChar[code] = fontCharCode; + } + this.useToFontChar = true; + } + + createGlyphNameMap(glyphs, ids, properties); this.glyphNameMap = properties.glyphNameMap; } + // Converting glyphs and ids into font's cmap table + cmap.data = createCMapTable(glyphs, ids); + var unicodeIsEnabled = []; + for (var i = 0, ii = glyphs.length; i < ii; i++) { + unicodeIsEnabled[glyphs[i].unicode] = true; + } + this.unicodeIsEnabled = unicodeIsEnabled; + // Rewrite the 'post' table if needed if (requiredTables.indexOf('post') != -1) { tables.push({ @@ -1767,7 +2122,7 @@ var Font = (function Font() { return stringToArray(ttf.file); }, - convert: function font_convert(fontName, font, properties) { + convert: function Font_convert(fontName, font, properties) { function isFixedPitch(glyphs) { for (var i = 0, ii = glyphs.length - 1; i < ii; i++) { if (glyphs[i] != glyphs[i + 1]) @@ -1808,6 +2163,14 @@ var Font = (function Font() { } properties.baseEncoding = encoding; } + if (properties.subtype == 'CIDFontType0C') { + var toFontChar = []; + for (var i = 0; i < charstrings.length; ++i) { + var charstring = charstrings[i]; + toFontChar[charstring.code] = charstring.unicode; + } + this.toFontChar = toFontChar; + } var fields = { // PostScript Font Program @@ -1832,9 +2195,9 @@ var Font = (function Font() { '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date '\x00\x00' + // xMin - string16(properties.descent) + // yMin + safeString16(properties.descent) + // yMin '\x0F\xFF' + // xMax - string16(properties.ascent) + // yMax + safeString16(properties.ascent) + // yMax string16(properties.italicAngle ? 2 : 0) + // macStyle '\x00\x11' + // lowestRecPPEM '\x00\x00' + // fontDirectionHint @@ -1846,15 +2209,15 @@ var Font = (function Font() { 'hhea': (function fontFieldsHhea() { return stringToArray( '\x00\x01\x00\x00' + // Version number - string16(properties.ascent) + // Typographic Ascent - string16(properties.descent) + // Typographic Descent + safeString16(properties.ascent) + // Typographic Ascent + safeString16(properties.descent) + // Typographic Descent '\x00\x00' + // Line Gap '\xFF\xFF' + // advanceWidthMax '\x00\x00' + // minLeftSidebearing '\x00\x00' + // minRightSidebearing '\x00\x00' + // xMaxExtent - string16(properties.capHeight) + // caretSlopeRise - string16(Math.tan(properties.italicAngle) * + safeString16(properties.capHeight) + // caretSlopeRise + safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + // caretSlopeRun '\x00\x00' + // caretOffset '\x00\x00' + // -reserved- @@ -1868,8 +2231,11 @@ var Font = (function Font() { // Horizontal metrics 'hmtx': (function fontFieldsHmtx() { var hmtx = '\x00\x00\x00\x00'; // Fake .notdef - for (var i = 0, ii = charstrings.length; i < ii; i++) - hmtx += string16(charstrings[i].width) + string16(0); + for (var i = 0, ii = charstrings.length; i < ii; i++) { + var charstring = charstrings[i]; + var width = 'width' in charstring ? charstring.width : 0; + hmtx += string16(width) + string16(0); + } return stringToArray(hmtx); })(), @@ -1898,17 +2264,48 @@ var Font = (function Font() { return stringToArray(otf.file); }, - loadCidToUnicode: function font_loadCidToUnicode(properties) { - if (properties.cidToGidMap) { - this.cidToUnicode = properties.cidToGidMap; - return; + buildToFontChar: function Font_buildToFontChar(toUnicode) { + var result = []; + var unusedUnicode = kCmapGlyphOffset; + for (var i = 0, ii = toUnicode.length; i < ii; i++) { + var unicode = toUnicode[i]; + var fontCharCode = typeof unicode === 'object' ? unusedUnicode++ : + unicode; + if (typeof unicode !== 'undefined') + result[i] = fontCharCode; + } + return result; + }, + + rebuildToUnicode: function Font_rebuildToUnicode(properties) { + var firstChar = properties.firstChar, lastChar = properties.lastChar; + var map = []; + if (properties.composite) { + var isIdentityMap = this.cidToUnicode.length == 0; + for (var i = firstChar, ii = lastChar; i <= ii; i++) { + // TODO missing map the character according font's CMap + var cid = i; + map[i] = isIdentityMap ? cid : this.cidToUnicode[cid]; + } + } else { + for (var i = firstChar, ii = lastChar; i <= ii; i++) { + var glyph = properties.differences[i]; + if (!glyph) + glyph = properties.baseEncoding[i]; + if (!!glyph && (glyph in GlyphsUnicode)) + map[i] = GlyphsUnicode[glyph]; + } } + this.toUnicode = map; + }, + loadCidToUnicode: function Font_loadCidToUnicode(properties) { if (!properties.cidSystemInfo) return; - var cidToUnicodeMap = []; + var cidToUnicodeMap = [], unicodeToCIDMap = []; this.cidToUnicode = cidToUnicodeMap; + this.unicodeToCID = unicodeToCIDMap; var cidSystemInfo = properties.cidSystemInfo; var cidToUnicode; @@ -1920,43 +2317,38 @@ var Font = (function Font() { if (!cidToUnicode) return; // identity encoding - var glyph = 1, i, j, k, ii; + var cid = 1, i, j, k, ii; for (i = 0, ii = cidToUnicode.length; i < ii; ++i) { var unicode = cidToUnicode[i]; if (isArray(unicode)) { var length = unicode.length; - for (j = 0; j < length; j++) - cidToUnicodeMap[unicode[j]] = glyph; - glyph++; + for (j = 0; j < length; j++) { + cidToUnicodeMap[cid] = unicode[j]; + unicodeToCIDMap[unicode[j]] = cid; + } + cid++; } else if (typeof unicode === 'object') { var fillLength = unicode.f; if (fillLength) { k = unicode.c; for (j = 0; j < fillLength; ++j) { - cidToUnicodeMap[k] = glyph++; + cidToUnicodeMap[cid] = k; + unicodeToCIDMap[k] = cid; + cid++; k++; } } else - glyph += unicode.s; + cid += unicode.s; } else if (unicode) { - cidToUnicodeMap[unicode] = glyph++; + cidToUnicodeMap[cid] = unicode; + unicodeToCIDMap[unicode] = cid; + cid++; } else - glyph++; + cid++; } }, - bindWorker: function font_bindWorker(data) { - postMessage({ - action: 'font', - data: { - raw: data, - fontName: this.loadedName, - mimetype: this.mimetype - } - }); - }, - - bindDOM: function font_bindDom(data) { + bindDOM: function Font_bindDOM(data) { var fontName = this.loadedName; // Add the font-face rule to the document @@ -1964,89 +2356,137 @@ var Font = (function Font() { window.btoa(data) + ');'); var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}'; - document.documentElement.firstChild.appendChild( - document.createElement('style')); + var styleElement = document.createElement('style'); + document.documentElement.getElementsByTagName('head')[0].appendChild( + styleElement); - var styleSheet = document.styleSheets[document.styleSheets.length - 1]; + var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); + if (PDFJS.pdfBug && FontInspector.enabled) + FontInspector.fontAdded(this, url); + return rule; }, - charToGlyph: function fonts_charToGlyph(charcode) { - var unicode, width, codeIRQueue; + get spaceWidth() { + // trying to estimate space character width + var possibleSpaceReplacements = ['space', 'minus', 'one', 'i']; + var width; + for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) { + var glyphName = possibleSpaceReplacements[i]; + // if possible, getting width by glyph name + if (glyphName in this.widths) { + width = this.widths[glyphName]; + break; + } + var glyphUnicode = GlyphsUnicode[glyphName]; + // finding the charcode via unicodeToCID map + var charcode = 0; + if (this.composite) + charcode = this.unicodeToCID[glyphUnicode]; + // ... via toUnicode map + if (!charcode && 'toUnicode' in this) + charcode = this.toUnicode.indexOf(glyphUnicode); + // setting it to unicode if negative or undefined + if (!(charcode > 0)) + charcode = glyphUnicode; + // trying to get width via charcode + width = this.widths[charcode]; + if (width) + break; // the non-zero width found + } + width = (width || this.defaultWidth) * this.widthMultiplier; + return shadow(this, 'spaceWidth', width); + }, + + charToGlyph: function Font_charToGlyph(charcode) { + var fontCharCode, width, operatorList, disabled; var width = this.widths[charcode]; switch (this.type) { case 'CIDFontType0': if (this.noUnicodeAdaptation) { - width = this.widths[this.cidToUnicode[charcode]]; - unicode = charcode; + width = this.widths[this.unicodeToCID[charcode] || charcode]; + fontCharCode = mapPrivateUseChars(charcode); break; } - unicode = adaptUnicode(this.cidToUnicode[charcode] || charcode); + fontCharCode = this.toFontChar[charcode] || charcode; break; case 'CIDFontType2': if (this.noUnicodeAdaptation) { - width = this.widths[this.cidToUnicode[charcode]]; - unicode = charcode; + width = this.widths[this.unicodeToCID[charcode] || charcode]; + fontCharCode = mapPrivateUseChars(charcode); break; } - unicode = adaptUnicode(this.cidToUnicode[charcode] || charcode); + fontCharCode = this.toFontChar[charcode] || charcode; break; case 'Type1': var glyphName = this.differences[charcode] || this.encoding[charcode]; + if (!isNum(width)) + width = this.widths[glyphName]; if (this.noUnicodeAdaptation) { - if (!isNum(width)) - width = this.widths[glyphName]; - unicode = GlyphsUnicode[glyphName] || charcode; + fontCharCode = mapPrivateUseChars(GlyphsUnicode[glyphName] || + charcode); break; } - unicode = this.glyphNameMap[glyphName] || - adaptUnicode(GlyphsUnicode[glyphName] || charcode); + fontCharCode = this.glyphNameMap[glyphName] || + GlyphsUnicode[glyphName] || charcode; break; case 'Type3': var glyphName = this.differences[charcode] || this.encoding[charcode]; - codeIRQueue = this.charProcIRQueues[glyphName]; - unicode = charcode; + operatorList = this.charProcOperatorList[glyphName]; + fontCharCode = charcode; break; case 'TrueType': + if (this.useToFontChar) { + fontCharCode = this.toFontChar[charcode] || charcode; + break; + } var glyphName = this.differences[charcode] || this.encoding[charcode]; if (!glyphName) glyphName = Encodings.StandardEncoding[charcode]; if (!isNum(width)) width = this.widths[glyphName]; if (this.noUnicodeAdaptation) { - unicode = GlyphsUnicode[glyphName] || charcode; + fontCharCode = GlyphsUnicode[glyphName] || charcode; break; } - if (!this.hasEncoding) { - unicode = adaptUnicode(charcode); + if (!this.hasEncoding || this.isSymbolicFont) { + fontCharCode = this.useToFontChar ? this.toFontChar[charcode] : + charcode; break; } - if (this.hasShortCmap) { - var j = Encodings.MacRomanEncoding.indexOf(glyphName); - unicode = j >= 0 && !isSpecialUnicode(j) ? j : - this.glyphNameMap[glyphName]; - } else { - unicode = glyphName in GlyphsUnicode ? - adaptUnicode(GlyphsUnicode[glyphName]) : - this.glyphNameMap[glyphName]; - } + + // MacRoman encoding address by re-encoding the cmap table + fontCharCode = glyphName in this.glyphNameMap ? + this.glyphNameMap[glyphName] : GlyphsUnicode[glyphName]; break; default: warn('Unsupported font type: ' + this.type); break; } + + var unicodeChars = !('toUnicode' in this) ? charcode : + this.toUnicode[charcode] || charcode; + if (typeof unicodeChars === 'number') + unicodeChars = String.fromCharCode(unicodeChars); + + width = (isNum(width) ? width : this.defaultWidth) * this.widthMultiplier; + disabled = this.unicodeIsEnabled ? + !this.unicodeIsEnabled[fontCharCode] : false; + return { - unicode: unicode, - width: isNum(width) ? width : this.defaultWidth, - codeIRQueue: codeIRQueue + fontChar: String.fromCharCode(fontCharCode), + unicode: unicodeChars, + width: width, + disabled: disabled, + operatorList: operatorList }; }, - charsToGlyphs: function fonts_chars2Glyphs(chars) { + charsToGlyphs: function Font_charsToGlyphs(chars) { var charsCache = this.charsCache; var glyphs; @@ -2094,7 +2534,7 @@ var Font = (function Font() { } }; - return constructor; + return Font; })(); /* @@ -2381,7 +2821,13 @@ var Type1Parser = function type1Parser() { while (str[index++] != ']') count++; - var array = str.substr(start, count).split(' '); + str = str.substr(start, count); + + str = str.trim(); + // Remove adjacent spaces + str = str.replace(/\s+/g, ' '); + + var array = str.split(' '); for (var i = 0, ii = array.length; i < ii; i++) array[i] = parseFloat(array[i] || 0); return array; @@ -2404,7 +2850,7 @@ var Type1Parser = function type1Parser() { return c == ' ' || c == '\n' || c == '\x0d'; } - this.extractFontProgram = function t1_extractFontProgram(stream) { + this.extractFontProgram = function Type1Parser_extractFontProgram(stream) { var eexec = decrypt(stream, kEexecEncryptionKey, 4); var eexecStr = ''; for (var i = 0, ii = eexec.length; i < ii; i++) @@ -2415,7 +2861,7 @@ var Type1Parser = function type1Parser() { subrs: [], charstrings: [], properties: { - 'private': { + 'privateData': { 'lenIV': 4 } } @@ -2444,7 +2890,7 @@ var Type1Parser = function type1Parser() { (token == 'RD' || token == '-|')) { i++; var data = eexec.slice(i, i + length); - var lenIV = program.properties.private['lenIV']; + var lenIV = program.properties.privateData['lenIV']; var encoded = decrypt(data, kCharStringsEncryptionKey, lenIV); var str = decodeCharString(encoded); @@ -2484,7 +2930,7 @@ var Type1Parser = function type1Parser() { var length = parseInt(getToken(), 10); getToken(); // read in 'RD' var data = eexec.slice(i + 1, i + 1 + length); - var lenIV = program.properties.private['lenIV']; + var lenIV = program.properties.privateData['lenIV']; var encoded = decrypt(data, kCharStringsEncryptionKey, lenIV); var str = decodeCharString(encoded); i = i + 1 + length; @@ -2500,12 +2946,12 @@ var Type1Parser = function type1Parser() { case '/FamilyOtherBlues': case '/StemSnapH': case '/StemSnapV': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumberArray(eexecStr, i + 1); break; case '/StdHW': case '/StdVW': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumberArray(eexecStr, i + 2)[0]; break; case '/BlueShift': @@ -2514,7 +2960,7 @@ var Type1Parser = function type1Parser() { case '/BlueScale': case '/LanguageGroup': case '/ExpansionFactor': - program.properties.private[token.substring(1)] = + program.properties.privateData[token.substring(1)] = readNumber(eexecStr, i + 1); break; } @@ -2529,7 +2975,8 @@ var Type1Parser = function type1Parser() { return program; }; - this.extractFontHeader = function t1_extractFontHeader(stream, properties) { + this.extractFontHeader = function Type1Parser_extractFontHeader(stream, + properties) { var headerString = ''; for (var i = 0, ii = stream.length; i < ii; i++) headerString += String.fromCharCode(stream[i]); @@ -2538,14 +2985,14 @@ var Type1Parser = function type1Parser() { var count = headerString.length; for (var i = 0; i < count; i++) { var getToken = function getToken() { - var char = headerString[i]; - while (i < count && (isSeparator(char) || char == '/')) - char = headerString[++i]; + var character = headerString[i]; + while (i < count && (isSeparator(character) || character == '/')) + character = headerString[++i]; var token = ''; - while (i < count && !(isSeparator(char) || char == '/')) { - token += char; - char = headerString[++i]; + while (i < count && !(isSeparator(character) || character == '/')) { + token += character; + character = headerString[++i]; } return token; @@ -2605,7 +3052,7 @@ var Type1Parser = function type1Parser() { * The CFF class takes a Type1 file and wrap it into a * 'Compact Font Format' which itself embed Type2 charstrings. */ -var CFFStrings = [ +var CFFStandardStrings = [ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', @@ -2675,7 +3122,8 @@ var CFFStrings = [ var type1Parser = new Type1Parser(); -var CFF = function cffCFF(name, file, properties) { +// Type1Font is also a CIDFontType0. +var Type1Font = function Type1Font(name, file, properties) { // Get the data block containing glyphs and subrs informations var headerBlock = file.getBytes(properties.length1); type1Parser.extractFontHeader(headerBlock, properties); @@ -2695,8 +3143,9 @@ var CFF = function cffCFF(name, file, properties) { subrs, properties); }; -CFF.prototype = { - createCFFIndexHeader: function cff_createCFFIndexHeader(objects, isByte) { +Type1Font.prototype = { + createCFFIndexHeader: function Type1Font_createCFFIndexHeader(objects, + isByte) { // First 2 bytes contains the number of objects contained into this index var count = objects.length; @@ -2732,7 +3181,7 @@ CFF.prototype = { return data; }, - encodeNumber: function cff_encodeNumber(value) { + encodeNumber: function Type1Font_encodeNumber(value) { // some of the fonts has ouf-of-range values // they are just arithmetic overflows // make sanitizer happy @@ -2750,25 +3199,16 @@ CFF.prototype = { } }, - getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs, + getOrderedCharStrings: function Type1Font_getOrderedCharStrings(glyphs, properties) { var charstrings = []; - var reverseMapping = {}; - var encoding = properties.baseEncoding; var i, length, glyphName; - for (i = 0, length = encoding.length; i < length; ++i) { - glyphName = encoding[i]; - if (!glyphName || isSpecialUnicode(i)) - continue; - reverseMapping[glyphName] = i; - } - reverseMapping['.notdef'] = 0; var unusedUnicode = kCmapGlyphOffset; for (i = 0, length = glyphs.length; i < length; i++) { var item = glyphs[i]; var glyphName = item.glyph; - var unicode = glyphName in reverseMapping ? - reverseMapping[glyphName] : unusedUnicode++; + var unicode = glyphName in GlyphsUnicode ? + GlyphsUnicode[glyphName] : unusedUnicode++; charstrings.push({ glyph: glyphName, unicode: unicode, @@ -2785,7 +3225,8 @@ CFF.prototype = { return charstrings; }, - getType2Charstrings: function cff_getType2Charstrings(type1Charstrings) { + getType2Charstrings: function Type1Font_getType2Charstrings( + type1Charstrings) { var type2Charstrings = []; var count = type1Charstrings.length; for (var i = 0; i < count; i++) { @@ -2796,7 +3237,7 @@ CFF.prototype = { return type2Charstrings; }, - getType2Subrs: function cff_getType2Subrs(type1Subrs) { + getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) { var bias = 0; var count = type1Subrs.length; if (count < 1240) @@ -2848,7 +3289,7 @@ CFF.prototype = { 'hvcurveto': 31 }, - flattenCharstring: function flattenCharstring(charstring, map) { + flattenCharstring: function Type1Font_flattenCharstring(charstring, map) { // charstring changes size - can't cache .length in loop for (var i = 0; i < charstring.length; i++) { var command = charstring[i]; @@ -2875,7 +3316,7 @@ CFF.prototype = { return charstring; }, - wrap: function wrap(name, glyphs, charstrings, subrs, properties) { + wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) { var fields = { // major version, minor version, header size, offset size 'header': '\x01\x00\x04\x04', @@ -2919,7 +3360,7 @@ CFF.prototype = { dict += self.encodeNumber(offset) + '\x11'; // Charstrings offset = offset + fields.charstrings.length; - dict += self.encodeNumber(fields.private.length); + dict += self.encodeNumber(fields.privateData.length); dict += self.encodeNumber(offset) + '\x12'; // Private return header + String.fromCharCode(dict.length + 1) + dict; @@ -2944,7 +3385,7 @@ CFF.prototype = { var count = glyphs.length; for (var i = 0; i < count; i++) { - var index = CFFStrings.indexOf(charstrings[i].glyph); + var index = CFFStandardStrings.indexOf(charstrings[i].glyph); // Some characters like asterikmath && circlecopyrt are // missing from the original strings, for the moment let's // map them to .notdef and see later if it cause any @@ -2960,7 +3401,7 @@ CFF.prototype = { 'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), true), - 'private': (function cffWrapPrivate(self) { + 'privateData': (function cffWrapPrivate(self) { var data = '\x8b\x14' + // defaultWidth '\x8b\x15'; // nominalWidth @@ -2978,9 +3419,9 @@ CFF.prototype = { ExpansionFactor: '\x0c\x18' }; for (var field in fieldMap) { - if (!properties.private.hasOwnProperty(field)) + if (!properties.privateData.hasOwnProperty(field)) continue; - var value = properties.private[field]; + var value = properties.privateData[field]; if (isArray(value)) { data += self.encodeNumber(value[0]); @@ -3013,106 +3454,31 @@ CFF.prototype = { } }; -var Type2CFF = (function type2CFF() { - // TODO: replace parsing code with the Type2Parser in font_utils.js - function constructor(file, properties) { - var bytes = file.getBytes(); - this.bytes = bytes; +var CFFFont = (function CFFFontClosure() { + function CFFFont(file, properties) { this.properties = properties; - this.data = this.parse(); + var parser = new CFFParser(file, properties); + var cff = parser.parse(); + var compiler = new CFFCompiler(cff); + this.readExtra(cff); + try { + this.data = compiler.compile(); + } catch (e) { + warn('Failed to compile font ' + properties.loadedName); + // There may have just been an issue with the compiler, set the data + // anyway and hope the font loaded. + this.data = file; + } } - constructor.prototype = { - parse: function cff_parse() { - var header = this.parseHeader(); - var properties = this.properties; - var nameIndex = this.parseIndex(header.endPos); - - var dictIndex = this.parseIndex(nameIndex.endPos); - if (dictIndex.length != 1) - error('CFF contains more than 1 font'); - - var stringIndex = this.parseIndex(dictIndex.endPos); - var gsubrIndex = this.parseIndex(stringIndex.endPos); - - var strings = this.getStrings(stringIndex); - - var baseDict = this.parseDict(dictIndex.get(0).data); - var topDict = this.getTopDict(baseDict, strings); - - var bytes = this.bytes; - - var privateDict = {}; - var privateInfo = topDict.Private; - if (privateInfo) { - var privOffset = privateInfo[1], privLength = privateInfo[0]; - var privBytes = bytes.subarray(privOffset, privOffset + privLength); - baseDict = this.parseDict(privBytes); - privateDict = this.getPrivDict(baseDict, strings); - } else { - privateDict.defaultWidthX = properties.defaultWidth; - } - - var charStrings = this.parseIndex(topDict.CharStrings); - var charset = this.parseCharsets(topDict.charset, - charStrings.length, strings); - var encoding = this.parseEncoding(topDict.Encoding, properties, - strings, charset); - - var charset, encoding; - var isCIDFont = properties.subtype == 'CIDFontType0C'; - if (isCIDFont) { - charset = []; - charset.length = charStrings.length; - encoding = this.parseCidMap(topDict.charset, - charStrings.length); - } else { - charset = this.parseCharsets(topDict.charset, - charStrings.length, strings); - encoding = this.parseEncoding(topDict.Encoding, properties, - strings, charset); - } - - // The font sanitizer does not support CFF encoding with a - // supplement, since the encoding is not really use to map - // between gid to glyph, let's overwrite what is declared in - // the top dictionary to let the sanitizer think the font use - // StandardEncoding, that's a lie but that's ok. - if (encoding.hasSupplement) - bytes[topDict.Encoding] &= 0x7F; - - // The CFF specification state that the 'dotsection' command - // (12, 0) is deprecated and treated as a no-op, but all Type2 - // charstrings processors should support them. Unfortunately - // the font sanitizer don't. As a workaround the sequence (12, 0) - // is replaced by a useless (0, hmoveto). - var count = charStrings.length; - for (var i = 0; i < count; i++) { - var charstring = charStrings.get(i); - - var start = charstring.start; - var data = charstring.data; - var length = data.length; - for (var j = 0; j <= length; j) { - var value = data[j++]; - if (value == 12 && data[j++] == 0) { - bytes[start + j - 2] = 139; - bytes[start + j - 1] = 22; - } else if (value === 28) { - j += 2; - } else if (value >= 247 && value <= 254) { - j++; - } else if (value == 255) { - j += 4; - } - } - } - + CFFFont.prototype = { + readExtra: function CFFFont_readExtra(cff) { // charstrings contains info about glyphs (one element per glyph // containing mappings for {unicode, width}) - var charstrings = this.getCharStrings(charset, encoding.encoding, - privateDict, this.properties); + var charset = cff.charset.charset; + var encoding = cff.encoding ? cff.encoding.encoding : null; + var charstrings = this.getCharStrings(charset, encoding); // create the mapping between charstring and glyph id var glyphIds = []; @@ -3121,301 +3487,127 @@ var Type2CFF = (function type2CFF() { this.charstrings = charstrings; this.glyphIds = glyphIds; - - var data = []; - for (var i = 0, ii = bytes.length; i < ii; ++i) - data.push(bytes[i]); - return data; }, - - getCharStrings: function cff_charstrings(charsets, encoding, - privateDict, properties) { + getCharStrings: function CFFFont_getCharStrings(charsets, encoding) { var charstrings = []; var unicodeUsed = []; var unassignedUnicodeItems = []; + var inverseEncoding = []; + // CID fonts don't have an encoding. + if (encoding !== null) + for (var charcode in encoding) + inverseEncoding[encoding[charcode]] = charcode | 0; + else + inverseEncoding = charsets; for (var i = 0, ii = charsets.length; i < ii; i++) { var glyph = charsets[i]; - var encodingFound = false; - for (var charcode in encoding) { - if (encoding[charcode] == i) { - var code = charcode | 0; - charstrings.push({ - unicode: adaptUnicode(code), - code: code, - gid: i, - glyph: glyph - }); - unicodeUsed[code] = true; - encodingFound = true; - break; - } - } - if (!encodingFound) { + if (glyph == '.notdef') + continue; + + var code = inverseEncoding[i]; + if (!code || isSpecialUnicode(code)) { unassignedUnicodeItems.push(i); + continue; } + charstrings.push({ + unicode: code, + code: code, + gid: i, + glyph: glyph + }); + unicodeUsed[code] = true; } - var nextUnusedUnicode = 0x21; + var nextUnusedUnicode = kCmapGlyphOffset; for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; ++j) { var i = unassignedUnicodeItems[j]; // giving unicode value anyway - while (unicodeUsed[nextUnusedUnicode]) + while (nextUnusedUnicode in unicodeUsed) nextUnusedUnicode++; - var code = nextUnusedUnicode++; + var unicode = nextUnusedUnicode++; charstrings.push({ - unicode: adaptUnicode(code), - code: code, + unicode: unicode, + code: inverseEncoding[i] || 0, gid: i, glyph: charsets[i] }); } // sort the array by the unicode value (again) - charstrings.sort(function type2CFFGetCharStringsSort(a, b) { + charstrings.sort(function getCharStringsSort(a, b) { return a.unicode - b.unicode; }); return charstrings; - }, + } + }; - parseEncoding: function cff_parseencoding(pos, properties, strings, - charset) { - var encoding = {}; - var bytes = this.bytes; - var result = { - encoding: encoding, - hasSupplement: false - }; + return CFFFont; +})(); - function readSupplement() { - var supplementsCount = bytes[pos++]; - for (var i = 0; i < supplementsCount; i++) { - var code = bytes[pos++]; - var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff); - encoding[code] = properties.differences.indexOf(strings[sid]); - } - } +var CFFParser = (function CFFParserClosure() { + function CFFParser(file, properties) { + this.bytes = file.getBytes(); + this.properties = properties; + } + CFFParser.prototype = { + parse: function CFFParser_parse() { + var properties = this.properties; + var cff = new CFF(); + this.cff = cff; - if (pos == 0 || pos == 1) { - var gid = 1; - var baseEncoding = pos ? Encodings.ExpertEncoding : - Encodings.StandardEncoding; - for (var i = 0, ii = charset.length; i < ii; i++) { - var index = baseEncoding.indexOf(charset[i]); - if (index != -1) - encoding[index] = gid++; + // The first five sections must be in order, all the others are reached + // via offsets contained in one of the below. + var header = this.parseHeader(); + var nameIndex = this.parseIndex(header.endPos); + var topDictIndex = this.parseIndex(nameIndex.endPos); + var stringIndex = this.parseIndex(topDictIndex.endPos); + var globalSubrIndex = this.parseIndex(stringIndex.endPos); + + var topDictParsed = this.parseDict(topDictIndex.obj.get(0)); + var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings); + + cff.header = header.obj; + cff.names = this.parseNameIndex(nameIndex.obj); + cff.strings = this.parseStringIndex(stringIndex.obj); + cff.topDict = topDict; + cff.globalSubrIndex = globalSubrIndex.obj; + + this.parsePrivateDict(cff.topDict); + + cff.isCIDFont = topDict.hasName('ROS'); + + var charStringOffset = topDict.getByName('CharStrings'); + cff.charStrings = this.parseCharStrings(charStringOffset); + + var charset, encoding; + if (cff.isCIDFont) { + var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj; + for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) { + var dictRaw = fdArrayIndex.get(i); + var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw), + cff.strings); + this.parsePrivateDict(fontDict); + cff.fdArray.push(fontDict); } + // cid fonts don't have an encoding + encoding = null; + charset = this.parseCharsets(topDict.getByName('charset'), + cff.charStrings.count, cff.strings, true); + cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'), + cff.charStrings.count); } else { - var format = bytes[pos++]; - switch (format & 0x7f) { - case 0: - var glyphsCount = bytes[pos++]; - for (var i = 1; i <= glyphsCount; i++) - encoding[bytes[pos++]] = i; - break; - - case 1: - var rangesCount = bytes[pos++]; - var gid = 1; - for (var i = 0; i < rangesCount; i++) { - var start = bytes[pos++]; - var left = bytes[pos++]; - for (var j = start; j <= start + left; j++) - encoding[j] = gid++; - } - break; - - default: - error('Unknow encoding format: ' + format + ' in CFF'); - break; - } - if (format & 0x80) { - readSupplement(); - result.hasSupplement = true; - } - } - return result; - }, - - parseCharsets: function cff_parsecharsets(pos, length, strings) { - if (pos == 0) { - return ISOAdobeCharset.slice(); - } else if (pos == 1) { - return ExpertCharset.slice(); - } else if (pos == 2) { - return ExpertSubsetCharset.slice(); + charset = this.parseCharsets(topDict.getByName('charset'), + cff.charStrings.count, cff.strings, false); + encoding = this.parseEncoding(topDict.getByName('Encoding'), + properties, + cff.strings, charset.charset); } + cff.charset = charset; + cff.encoding = encoding; - var bytes = this.bytes; - var format = bytes[pos++]; - var charset = ['.notdef']; - - // subtract 1 for the .notdef glyph - length -= 1; - - switch (format) { - case 0: - for (var i = 0; i < length; i++) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - charset.push(strings[sid]); - } - break; - case 1: - while (charset.length <= length) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - var count = bytes[pos++]; - for (var i = 0; i <= count; i++) - charset.push(strings[sid++]); - } - break; - case 2: - while (charset.length <= length) { - var sid = (bytes[pos++] << 8) | bytes[pos++]; - var count = (bytes[pos++] << 8) | bytes[pos++]; - for (var i = 0; i <= count; i++) - charset.push(strings[sid++]); - } - break; - default: - error('Unknown charset format'); - } - return charset; + return cff; }, - - parseCidMap: function cff_parsecharsets(pos, length) { - var bytes = this.bytes; - var format = bytes[pos++]; - - var encoding = {}; - var map = {encoding: encoding}; - - encoding[0] = 0; - - var gid = 1; - switch (format) { - case 0: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - encoding[cid] = gid++; - } - break; - case 1: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - var count = bytes[pos++]; - for (var i = 0; i <= count; i++) - encoding[cid++] = gid++; - } - break; - case 2: - while (gid < length) { - var cid = (bytes[pos++] << 8) | bytes[pos++]; - var count = (bytes[pos++] << 8) | bytes[pos++]; - for (var i = 0; i <= count; i++) - encoding[cid++] = gid++; - } - break; - default: - error('Unknown charset format'); - } - return map; - }, - - getPrivDict: function cff_getprivdict(baseDict, strings) { - var dict = {}; - - // default values - dict['defaultWidthX'] = 0; - dict['nominalWidthX'] = 0; - - for (var i = 0, ii = baseDict.length; i < ii; ++i) { - var pair = baseDict[i]; - var key = pair[0]; - var value = pair[1]; - switch (key) { - case 20: - dict['defaultWidthX'] = value[0]; - case 21: - dict['nominalWidthX'] = value[0]; - default: - TODO('interpret top dict key: ' + key); - } - } - return dict; - }, - getTopDict: function cff_gettopdict(baseDict, strings) { - var dict = {}; - - // default values - dict['Encoding'] = 0; - dict['charset'] = 0; - - for (var i = 0, ii = baseDict.length; i < ii; ++i) { - var pair = baseDict[i]; - var key = pair[0]; - var value = pair[1]; - switch (key) { - case 1: - dict['Notice'] = strings[value[0]]; - break; - case 4: - dict['Weight'] = strings[value[0]]; - break; - case 3094: - dict['BaseFontName'] = strings[value[0]]; - break; - case 5: - dict['FontBBox'] = value; - break; - case 13: - dict['UniqueID'] = value[0]; - break; - case 15: - dict['charset'] = value[0]; - break; - case 16: - dict['Encoding'] = value[0]; - break; - case 17: - dict['CharStrings'] = value[0]; - break; - case 18: - dict['Private'] = value; - break; - case 3102: - case 3103: - case 3104: - case 3105: - case 3106: - case 3107: - case 3108: - case 3109: - case 3110: - dict['cidOperatorPresent'] = true; - break; - default: - TODO('interpret top dict key'); - } - } - return dict; - }, - getStrings: function cff_getStrings(stringIndex) { - function bytesToString(bytesArray) { - var str = ''; - for (var i = 0, ii = bytesArray.length; i < ii; i++) - str += String.fromCharCode(bytesArray[i]); - return str; - } - - var stringArray = []; - for (var i = 0, ii = CFFStrings.length; i < ii; i++) - stringArray.push(CFFStrings[i]); - - for (var i = 0, ii = stringIndex.length; i < ii; i++) - stringArray.push(bytesToString(stringIndex.get(i).data)); - - return stringArray; - }, - parseHeader: function cff_parseHeader() { + parseHeader: function CFFParser_parseHeader() { var bytes = this.bytes; var offset = 0; @@ -3423,17 +3615,18 @@ var Type2CFF = (function type2CFF() { ++offset; if (offset != 0) { - warning('cff data is shifted'); + warn('cff data is shifted'); bytes = bytes.subarray(offset); this.bytes = bytes; } - - return { - endPos: bytes[2], - offsetSize: bytes[3] - }; + var major = bytes[0]; + var minor = bytes[1]; + var hdrSize = bytes[2]; + var offSize = bytes[3]; + var header = new CFFHeader(major, minor, hdrSize, offSize); + return {obj: header, endPos: hdrSize}; }, - parseDict: function cff_parseDict(dict) { + parseDict: function CFFParser_parseDict(dict) { var pos = 0; function parseOperand() { @@ -3450,11 +3643,11 @@ var Type2CFF = (function type2CFF() { value = (value << 8) | dict[pos++]; value = (value << 8) | dict[pos++]; return value; - } else if (value <= 246) { + } else if (value >= 32 && value <= 246) { return value - 139; - } else if (value <= 250) { + } else if (value >= 247 && value <= 250) { return ((value - 247) * 256) + dict[pos++] + 108; - } else if (value <= 254) { + } else if (value >= 251 && value <= 254) { return -((value - 251) * 256) - dict[pos++] - 108; } else { error('255 is not a valid DICT command'); @@ -3492,27 +3685,8 @@ var Type2CFF = (function type2CFF() { while (pos < end) { var b = dict[pos]; if (b <= 21) { - if (b === 12) { - ++pos; - var op = dict[pos]; - if ((op > 14 && op < 17) || - (op > 23 && op < 30) || op > 38) { - warn('Invalid CFF dictionary key: ' + op); - // trying to replace it with initialRandomSeed - // to pass sanitizer - dict[pos] = 19; - } - var b = (b << 8) | op; - } - if (!operands.length && b == 8 && - dict[pos + 1] == 9) { - // no operands for FamilyBlues, removing the key - // and next one is FamilyOtherBlues - skipping them - // also replacing FamilyBlues to pass sanitizer - dict[pos] = 139; - pos += 2; - continue; - } + if (b === 12) + b = (b << 8) | dict[++pos]; entries.push([b, operands]); operands = []; ++pos; @@ -3522,10 +3696,12 @@ var Type2CFF = (function type2CFF() { } return entries; }, - parseIndex: function cff_parseIndex(pos) { + parseIndex: function CFFParser_parseIndex(pos) { + var cffIndex = new CFFIndex(); var bytes = this.bytes; - var count = bytes[pos++] << 8 | bytes[pos++]; + var count = (bytes[pos++] << 8) | bytes[pos++]; var offsets = []; + var start = pos; var end = pos; if (count != 0) { @@ -3543,26 +3719,947 @@ var Type2CFF = (function type2CFF() { } end = offsets[count]; } + for (var i = 0, ii = offsets.length - 1; i < ii; ++i) { + var offsetStart = offsets[i]; + var offsetEnd = offsets[i + 1]; + cffIndex.add(bytes.subarray(offsetStart, offsetEnd)); + } + return {obj: cffIndex, endPos: end}; + }, + parseNameIndex: function CFFParser_parseNameIndex(index) { + var names = []; + for (var i = 0, ii = index.count; i < ii; ++i) { + var name = index.get(i); + // OTS doesn't allow names to be over 127 characters. + var length = Math.min(name.length, 127); + var data = []; + // OTS also only permits certain characters in the name. + for (var j = 0; j < length; ++j) { + var c = name[j]; + if (j === 0 && c === 0) { + data[j] = c; + continue; + } + if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ || + c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ || + c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ || + c === 47 /* / */ || c === 37 /* % */) { + data[j] = 95; + continue; + } + data[j] = c; + } + names.push(String.fromCharCode.apply(null, data)); + } + return names; + }, + parseStringIndex: function CFFParser_parseStringIndex(index) { + var strings = new CFFStrings(); + for (var i = 0, ii = index.count; i < ii; ++i) { + var data = index.get(i); + strings.add(String.fromCharCode.apply(null, data)); + } + return strings; + }, + createDict: function CFFParser_createDict(type, dict, strings) { + var cffDict = new type(strings); + var types = cffDict.types; + + for (var i = 0, ii = dict.length; i < ii; ++i) { + var pair = dict[i]; + var key = pair[0]; + var value = pair[1]; + cffDict.setByKey(key, value); + } + return cffDict; + }, + parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) { + var charStrings = this.parseIndex(charStringOffset).obj; + // The CFF specification state that the 'dotsection' command + // (12, 0) is deprecated and treated as a no-op, but all Type2 + // charstrings processors should support them. Unfortunately + // the font sanitizer don't. As a workaround the sequence (12, 0) + // is replaced by a useless (0, hmoveto). + var count = charStrings.count; + for (var i = 0; i < count; i++) { + var charstring = charStrings.get(i); + + var data = charstring; + var length = data.length; + for (var j = 0; j <= length; j) { + var value = data[j++]; + if (value == 12 && data[j++] == 0) { + data[j - 2] = 139; + data[j - 1] = 22; + } else if (value === 28) { + j += 2; + } else if (value >= 247 && value <= 254) { + j++; + } else if (value == 255) { + j += 4; + } + } + } + return charStrings; + }, + parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) { + // no private dict, do nothing + if (!parentDict.hasName('Private')) + return; + var privateOffset = parentDict.getByName('Private'); + // make sure the params are formatted correctly + if (!isArray(privateOffset) || privateOffset.length !== 2) { + parentDict.removeByName('Private'); + return; + } + var size = privateOffset[0]; + var offset = privateOffset[1]; + // remove empty dicts or ones that refer to invalid location + if (size === 0 || offset >= this.bytes.length) { + parentDict.removeByName('Private'); + return; + } + + var privateDictEnd = offset + size; + var dictData = this.bytes.subarray(offset, privateDictEnd); + var dict = this.parseDict(dictData); + var privateDict = this.createDict(CFFPrivateDict, dict, + parentDict.strings); + parentDict.privateDict = privateDict; + + // Parse the Subrs index also since it's relative to the private dict. + if (!privateDict.getByName('Subrs')) + return; + var subrsOffset = privateDict.getByName('Subrs'); + var relativeOffset = offset + subrsOffset; + // Validate the offset. + if (subrsOffset === 0 || relativeOffset >= this.bytes.length) { + privateDict.removeByName('Subrs'); + return; + } + var subrsIndex = this.parseIndex(relativeOffset); + privateDict.subrsIndex = subrsIndex.obj; + }, + parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) { + if (pos == 0) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, + ISOAdobeCharset); + } else if (pos == 1) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, + ExpertCharset); + } else if (pos == 2) { + return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, + ExpertSubsetCharset); + } + + var bytes = this.bytes; + var start = pos; + var format = bytes[pos++]; + var charset = ['.notdef']; + // subtract 1 for the .notdef glyph + length -= 1; + + switch (format) { + case 0: + for (var i = 0; i < length; i++) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + charset.push(cid ? id : strings.get(id)); + } + break; + case 1: + while (charset.length <= length) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + var count = bytes[pos++]; + for (var i = 0; i <= count; i++) + charset.push(cid ? id++ : strings.get(id++)); + } + break; + case 2: + while (charset.length <= length) { + var id = (bytes[pos++] << 8) | bytes[pos++]; + var count = (bytes[pos++] << 8) | bytes[pos++]; + for (var i = 0; i <= count; i++) + charset.push(cid ? id++ : strings.get(id++)); + } + break; + default: + error('Unknown charset format'); + } + // Raw won't be needed if we actually compile the charset. + var end = pos; + var raw = bytes.subarray(start, end); + + return new CFFCharset(false, format, charset, raw); + }, + parseEncoding: function CFFParser_parseEncoding(pos, + properties, + strings, + charset) { + var encoding = {}; + var bytes = this.bytes; + var predefined = false; + var hasSupplement = false; + var format; + var raw = null; + + function readSupplement() { + var supplementsCount = bytes[pos++]; + for (var i = 0; i < supplementsCount; i++) { + var code = bytes[pos++]; + var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff); + encoding[code] = properties.differences.indexOf(strings.get(sid)); + } + } + + if (pos == 0 || pos == 1) { + predefined = true; + format = pos; + var gid = 1; + var baseEncoding = pos ? Encodings.ExpertEncoding : + Encodings.StandardEncoding; + for (var i = 0, ii = charset.length; i < ii; i++) { + var index = baseEncoding.indexOf(charset[i]); + if (index != -1) + encoding[index] = gid++; + } + } else { + var dataStart = pos; + var format = bytes[pos++]; + switch (format & 0x7f) { + case 0: + var glyphsCount = bytes[pos++]; + for (var i = 1; i <= glyphsCount; i++) + encoding[bytes[pos++]] = i; + break; + + case 1: + var rangesCount = bytes[pos++]; + var gid = 1; + for (var i = 0; i < rangesCount; i++) { + var start = bytes[pos++]; + var left = bytes[pos++]; + for (var j = start; j <= start + left; j++) + encoding[j] = gid++; + } + break; + + default: + error('Unknow encoding format: ' + format + ' in CFF'); + break; + } + var dataEnd = pos; + if (format & 0x80) { + // The font sanitizer does not support CFF encoding with a + // supplement, since the encoding is not really used to map + // between gid to glyph, let's overwrite what is declared in + // the top dictionary to let the sanitizer think the font use + // StandardEncoding, that's a lie but that's ok. + bytes[dataStart] &= 0x7f; + readSupplement(); + hasSupplement = true; + } + raw = bytes.subarray(dataStart, dataEnd); + } + format = format & 0x7f; + return new CFFEncoding(predefined, format, encoding, raw); + }, + parseFDSelect: function CFFParser_parseFDSelect(pos, length) { + var start = pos; + var bytes = this.bytes; + var format = bytes[pos++]; + var fdSelect = []; + switch (format) { + case 0: + for (var i = 0; i < length; ++i) { + var id = bytes[pos++]; + fdSelect.push(id); + } + break; + case 3: + var rangesCount = (bytes[pos++] << 8) | bytes[pos++]; + for (var i = 0; i < rangesCount; ++i) { + var first = (bytes[pos++] << 8) | bytes[pos++]; + var fdIndex = bytes[pos++]; + var next = (bytes[pos] << 8) | bytes[pos + 1]; + for (var j = first; j < next; ++j) + fdSelect.push(fdIndex); + } + // Advance past the sentinel(next). + pos += 2; + break; + default: + error('Unknown fdselect format ' + format); + break; + } + var end = pos; + return new CFFFDSelect(fdSelect, bytes.subarray(start, end)); + } + }; + return CFFParser; +})(); + +// Compact Font Format +var CFF = (function CFFClosure() { + function CFF() { + this.header = null; + this.names = []; + this.topDict = null; + this.strings = new CFFStrings(); + this.globalSubrIndex = null; + + // The following could really be per font, but since we only have one font + // store them here. + this.encoding = null; + this.charset = null; + this.charStrings = null; + this.fdArray = []; + this.fdSelect = null; + + this.isCIDFont = false; + } + return CFF; +})(); + +var CFFHeader = (function CFFHeaderClosure() { + function CFFHeader(major, minor, hdrSize, offSize) { + this.major = major; + this.minor = minor; + this.hdrSize = hdrSize; + this.offSize = offSize; + } + return CFFHeader; +})(); + +var CFFStrings = (function CFFStringsClosure() { + function CFFStrings() { + this.strings = []; + } + CFFStrings.prototype = { + get: function CFFStrings_get(index) { + if (index >= 0 && index <= 390) + return CFFStandardStrings[index]; + if (index - 391 <= this.strings.length) + return this.strings[index - 391]; + return CFFStandardStrings[0]; + }, + add: function CFFStrings_add(value) { + this.strings.push(value); + }, + get count() { + return this.strings.length; + } + }; + return CFFStrings; +})(); + +var CFFIndex = (function CFFIndexClosure() { + function CFFIndex() { + this.objects = []; + this.length = 0; + } + CFFIndex.prototype = { + add: function CFFIndex_add(data) { + this.length += data.length; + this.objects.push(data); + }, + get: function CFFIndex_get(index) { + return this.objects[index]; + }, + get count() { + return this.objects.length; + } + }; + return CFFIndex; +})(); + +var CFFDict = (function CFFDictClosure() { + function CFFDict(tables, strings) { + this.keyToNameMap = tables.keyToNameMap; + this.nameToKeyMap = tables.nameToKeyMap; + this.defaults = tables.defaults; + this.types = tables.types; + this.opcodes = tables.opcodes; + this.order = tables.order; + this.strings = strings; + this.values = {}; + } + CFFDict.prototype = { + // value should always be an array + setByKey: function CFFDict_setByKey(key, value) { + if (!(key in this.keyToNameMap)) + return false; + // ignore empty values + if (value.length === 0) + return true; + var type = this.types[key]; + // remove the array wrapping these types of values + if (type === 'num' || type === 'sid' || type === 'offset') + value = value[0]; + this.values[key] = value; + return true; + }, + hasName: function CFFDict_hasName(name) { + return this.nameToKeyMap[name] in this.values; + }, + getByName: function CFFDict_getByName(name) { + if (!(name in this.nameToKeyMap)) + error('Invalid dictionary name "' + name + '"'); + var key = this.nameToKeyMap[name]; + if (!(key in this.values)) + return this.defaults[key]; + return this.values[key]; + }, + removeByName: function CFFDict_removeByName(name) { + delete this.values[this.nameToKeyMap[name]]; + } + }; + CFFDict.createTables = function CFFDict_createTables(layout) { + var tables = { + keyToNameMap: {}, + nameToKeyMap: {}, + defaults: {}, + types: {}, + opcodes: {}, + order: [] + }; + for (var i = 0, ii = layout.length; i < ii; ++i) { + var entry = layout[i]; + var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0]; + tables.keyToNameMap[key] = entry[1]; + tables.nameToKeyMap[entry[1]] = key; + tables.types[key] = entry[2]; + tables.defaults[key] = entry[3]; + tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]]; + tables.order.push(key); + } + return tables; + }; + return CFFDict; +})(); + +var CFFTopDict = (function CFFTopDictClosure() { + var layout = [ + [[12, 30], 'ROS', ['sid', 'sid', 'num'], null], + [[12, 20], 'SyntheticBase', 'num', null], + [0, 'version', 'sid', null], + [1, 'Notice', 'sid', null], + [[12, 0], 'Copyright', 'sid', null], + [2, 'FullName', 'sid', null], + [3, 'FamilyName', 'sid', null], + [4, 'Weight', 'sid', null], + [[12, 1], 'isFixedPitch', 'num', 0], + [[12, 2], 'ItalicAngle', 'num', 0], + [[12, 3], 'UnderlinePosition', 'num', -100], + [[12, 4], 'UnderlineThickness', 'num', 50], + [[12, 5], 'PaintType', 'num', 0], + [[12, 6], 'CharstringType', 'num', 2], + [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'], + [.001, 0, 0, .001, 0, 0]], + [13, 'UniqueID', 'num', null], + [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]], + [[12, 8], 'StrokeWidth', 'num', 0], + [14, 'XUID', 'array', null], + [15, 'charset', 'offset', 0], + [16, 'Encoding', 'offset', 0], + [17, 'CharStrings', 'offset', 0], + [18, 'Private', ['offset', 'offset'], null], + [[12, 21], 'PostScript', 'sid', null], + [[12, 22], 'BaseFontName', 'sid', null], + [[12, 23], 'BaseFontBlend', 'delta', null], + [[12, 31], 'CIDFontVersion', 'num', 0], + [[12, 32], 'CIDFontRevision', 'num', 0], + [[12, 33], 'CIDFontType', 'num', 0], + [[12, 34], 'CIDCount', 'num', 8720], + [[12, 35], 'UIDBase', 'num', null], + [[12, 36], 'FDArray', 'offset', null], + [[12, 37], 'FDSelect', 'offset', null], + [[12, 38], 'FontName', 'sid', null]]; + var tables = null; + function CFFTopDict(strings) { + if (tables === null) + tables = CFFDict.createTables(layout); + CFFDict.call(this, tables, strings); + this.privateDict = null; + } + CFFTopDict.prototype = Object.create(CFFDict.prototype); + return CFFTopDict; +})(); + +var CFFPrivateDict = (function CFFPrivateDictClosure() { + var layout = [ + [6, 'BlueValues', 'delta', null], + [7, 'OtherBlues', 'delta', null], + [8, 'FamilyBlues', 'delta', null], + [9, 'FamilyOtherBlues', 'delta', null], + [[12, 9], 'BlueScale', 'num', 0.039625], + [[12, 10], 'BlueShift', 'num', 7], + [[12, 11], 'BlueFuzz', 'num', 1], + [10, 'StdHW', 'num', null], + [11, 'StdVW', 'num', null], + [[12, 12], 'StemSnapH', 'delta', null], + [[12, 13], 'StemSnapV', 'delta', null], + [[12, 14], 'ForceBold', 'num', 0], + [[12, 17], 'LanguageGroup', 'num', 0], + [[12, 18], 'ExpansionFactor', 'num', 0.06], + [[12, 19], 'initialRandomSeed', 'num', 0], + [19, 'Subrs', 'offset', null], + [20, 'defaultWidthX', 'num', 0], + [21, 'nominalWidthX', 'num', 0] + ]; + var tables = null; + function CFFPrivateDict(strings) { + if (tables === null) + tables = CFFDict.createTables(layout); + CFFDict.call(this, tables, strings); + this.subrsIndex = null; + } + CFFPrivateDict.prototype = Object.create(CFFDict.prototype); + return CFFPrivateDict; +})(); + +var CFFCharsetPredefinedTypes = { + ISO_ADOBE: 0, + EXPERT: 1, + EXPERT_SUBSET: 2 +}; +var CFFCharsetEmbeddedTypes = { + FORMAT0: 0, + FORMAT1: 1, + FORMAT2: 2 +}; +var CFFCharset = (function CFFCharsetClosure() { + function CFFCharset(predefined, format, charset, raw) { + this.predefined = predefined; + this.format = format; + this.charset = charset; + this.raw = raw; + } + return CFFCharset; +})(); + +var CFFEncodingPredefinedTypes = { + STANDARD: 0, + EXPERT: 1 +}; +var CFFCharsetEmbeddedTypes = { + FORMAT0: 0, + FORMAT1: 1 +}; +var CFFEncoding = (function CFFEncodingClosure() { + function CFFEncoding(predefined, format, encoding, raw) { + this.predefined = predefined; + this.format = format; + this.encoding = encoding; + this.raw = raw; + } + return CFFEncoding; +})(); + +var CFFFDSelect = (function CFFFDSelectClosure() { + function CFFFDSelect(fdSelect, raw) { + this.fdSelect = fdSelect; + this.raw = raw; + } + return CFFFDSelect; +})(); + +// Helper class to keep track of where an offset is within the data and helps +// filling in that offset once it's known. +var CFFOffsetTracker = (function CFFOffsetTrackerClosure() { + function CFFOffsetTracker() { + this.offsets = {}; + } + CFFOffsetTracker.prototype = { + isTracking: function CFFOffsetTracker_isTracking(key) { + return key in this.offsets; + }, + track: function CFFOffsetTracker_track(key, location) { + if (key in this.offsets) + error('Already tracking location of ' + key); + this.offsets[key] = location; + }, + offset: function CFFOffsetTracker_offset(value) { + for (var key in this.offsets) { + this.offsets[key] += value; + } + }, + setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, + values, + output) { + if (!(key in this.offsets)) + error('Not tracking location of ' + key); + var data = output.data; + var dataOffset = this.offsets[key]; + var size = 5; + for (var i = 0, ii = values.length; i < ii; ++i) { + var offset0 = i * size + dataOffset; + var offset1 = offset0 + 1; + var offset2 = offset0 + 2; + var offset3 = offset0 + 3; + var offset4 = offset0 + 4; + // It's easy to screw up offsets so perform this sanity check. + if (data[offset0] !== 0x1d || data[offset1] !== 0 || + data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) + error('writing to an offset that is not empty'); + var value = values[i]; + data[offset0] = 0x1d; + data[offset1] = (value >> 24) & 0xFF; + data[offset2] = (value >> 16) & 0xFF; + data[offset3] = (value >> 8) & 0xFF; + data[offset4] = value & 0xFF; + } + } + }; + return CFFOffsetTracker; +})(); + +// Takes a CFF and converts it to the binary representation. +var CFFCompiler = (function CFFCompilerClosure() { + function stringToArray(str) { + var array = []; + for (var i = 0, ii = str.length; i < ii; ++i) + array[i] = str.charCodeAt(i); + + return array; + }; + function CFFCompiler(cff) { + this.cff = cff; + } + CFFCompiler.prototype = { + compile: function CFFCompiler_compile() { + var cff = this.cff; + var output = { + data: [], + length: 0, + add: function CFFCompiler_add(data) { + this.data = this.data.concat(data); + this.length = this.data.length; + } + }; + + // Compile the five entries that must be in order. + var header = this.compileHeader(cff.header); + output.add(header); + + var nameIndex = this.compileNameIndex(cff.names); + output.add(nameIndex); + + var compiled = this.compileTopDicts([cff.topDict], output.length); + output.add(compiled.output); + var topDictTracker = compiled.trackers[0]; + + var stringIndex = this.compileStringIndex(cff.strings.strings); + output.add(stringIndex); + + var globalSubrIndex = this.compileIndex(cff.globalSubrIndex); + output.add(globalSubrIndex); + + // Now start on the other entries that have no specfic order. + if (cff.encoding && cff.topDict.hasName('Encoding')) { + if (cff.encoding.predefined) { + topDictTracker.setEntryLocation('Encoding', [cff.encoding.format], + output); + } else { + var encoding = this.compileEncoding(cff.encoding); + topDictTracker.setEntryLocation('Encoding', [output.length], output); + output.add(encoding); + } + } + + if (cff.charset && cff.topDict.hasName('charset')) { + if (cff.charset.predefined) { + topDictTracker.setEntryLocation('charset', [cff.charset.format], + output); + } else { + var charset = this.compileCharset(cff.charset); + topDictTracker.setEntryLocation('charset', [output.length], output); + output.add(charset); + } + } + + var charStrings = this.compileCharStrings(cff.charStrings); + topDictTracker.setEntryLocation('CharStrings', [output.length], output); + output.add(charStrings); + + if (cff.isCIDFont) { + // For some reason FDSelect must be in front of FDArray on windows. OSX + // and linux don't seem to care. + topDictTracker.setEntryLocation('FDSelect', [output.length], output); + var fdSelect = this.compileFDSelect(cff.fdSelect.raw); + output.add(fdSelect); + + var compiled = this.compileTopDicts(cff.fdArray, output.length); + topDictTracker.setEntryLocation('FDArray', [output.length], output); + output.add(compiled.output); + var fontDictTrackers = compiled.trackers; + + this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output); + } + + this.compilePrivateDicts([cff.topDict], [topDictTracker], output); + + return output.data; + }, + encodeNumber: function CFFCompiler_encodeNumber(value) { + if (parseFloat(value) == parseInt(value) && !isNaN(value)) // isInt + return this.encodeInteger(value); + else + return this.encodeFloat(value); + }, + encodeFloat: function CFFCompiler_encodeFloat(value) { + value = value.toString(); + // Strip off the any leading zeros. + if (value.substr(0, 2) === '0.') + value = value.substr(1); + else if (value.substr(0, 3) === '-0.') + value = '-' + value.substr(2); + var nibbles = []; + for (var i = 0, ii = value.length; i < ii; ++i) { + var a = value.charAt(i), b = value.charAt(i + 1); + var nibble; + if (a === 'e' && b === '-') { + nibble = 0xc; + ++i; + } else if (a === '.') { + nibble = 0xa; + } else if (a === 'E') { + nibble = 0xb; + } else if (a === '-') { + nibble = 0xe; + } else { + nibble = a; + } + nibbles.push(nibble); + } + nibbles.push(0xf); + if (nibbles.length % 2) + nibbles.push(0xf); + var out = [30]; + for (var i = 0, ii = nibbles.length; i < ii; i += 2) + out.push(nibbles[i] << 4 | nibbles[i + 1]); + return out; + }, + encodeInteger: function CFFCompiler_encodeInteger(value) { + var code; + if (value >= -107 && value <= 107) { + code = [value + 139]; + } else if (value >= 108 && value <= 1131) { + value = [value - 108]; + code = [(value >> 8) + 247, value & 0xFF]; + } else if (value >= -1131 && value <= -108) { + value = -value - 108; + code = [(value >> 8) + 251, value & 0xFF]; + } else if (value >= -32768 && value <= 32767) { + code = [0x1c, (value >> 8) & 0xFF, value & 0xFF]; + } else { + code = [0x1d, + (value >> 24) & 0xFF, + (value >> 16) & 0xFF, + (value >> 8) & 0xFF, + value & 0xFF]; + } + return code; + }, + compileHeader: function CFFCompiler_compileHeader(header) { + return [ + header.major, + header.minor, + header.hdrSize, + header.offSize + ]; + }, + compileNameIndex: function CFFCompiler_compileNameIndex(names) { + var nameIndex = new CFFIndex(); + for (var i = 0, ii = names.length; i < ii; ++i) + nameIndex.add(stringToArray(names[i])); + return this.compileIndex(nameIndex); + }, + compileTopDicts: function CFFCompiler_compileTopDicts(dicts, length) { + var fontDictTrackers = []; + var fdArrayIndex = new CFFIndex(); + for (var i = 0, ii = dicts.length; i < ii; ++i) { + var fontDict = dicts[i]; + var fontDictTracker = new CFFOffsetTracker(); + var fontDictData = this.compileDict(fontDict, fontDictTracker); + fontDictTrackers.push(fontDictTracker); + fdArrayIndex.add(fontDictData); + fontDictTracker.offset(length); + } + fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers); return { - get: function index_get(index) { - if (index >= count) - return null; - - var start = offsets[index]; - var end = offsets[index + 1]; - return { - start: start, - end: end, - data: bytes.subarray(start, end) - }; - }, - length: count, - endPos: end + trackers: fontDictTrackers, + output: fdArrayIndex }; + }, + compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts, + trackers, + output) { + for (var i = 0, ii = dicts.length; i < ii; ++i) { + var fontDict = dicts[i]; + if (!fontDict.privateDict || !fontDict.hasName('Private')) + continue; + var privateDict = fontDict.privateDict; + var privateDictTracker = new CFFOffsetTracker(); + var privateDictData = this.compileDict(privateDict, privateDictTracker); + + privateDictTracker.offset(output.length); + trackers[i].setEntryLocation('Private', + [privateDictData.length, output.length], + output); + output.add(privateDictData); + + if (privateDict.subrsIndex && privateDict.hasName('Subrs')) { + var subrs = this.compileIndex(privateDict.subrsIndex); + privateDictTracker.setEntryLocation('Subrs', [privateDictData.length], + output); + output.add(subrs); + } + } + }, + compileDict: function CFFCompiler_compileDict(dict, offsetTracker) { + var out = []; + // The dictionary keys must be in a certain order. + var order = dict.order; + for (var i = 0; i < order.length; ++i) { + var key = order[i]; + if (!(key in dict.values)) + continue; + var values = dict.values[key]; + var types = dict.types[key]; + if (!isArray(types)) types = [types]; + if (!isArray(values)) values = [values]; + + // Remove any empty dict values. + if (values.length === 0) + continue; + + for (var j = 0, jj = types.length; j < jj; ++j) { + var type = types[j]; + var value = values[j]; + switch (type) { + case 'num': + case 'sid': + out = out.concat(this.encodeNumber(value)); + break; + case 'offset': + // For offsets we just insert a 32bit integer so we don't have to + // deal with figuring out the length of the offset when it gets + // replaced later on by the compiler. + var name = dict.keyToNameMap[key]; + // Some offsets have the offset and the length, so just record the + // position of the first one. + if (!offsetTracker.isTracking(name)) + offsetTracker.track(name, out.length); + out = out.concat([0x1d, 0, 0, 0, 0]); + break; + case 'array': + case 'delta': + out = out.concat(this.encodeNumber(value)); + for (var k = 1, kk = values.length; k < kk; ++k) + out = out.concat(this.encodeNumber(values[k])); + break; + default: + error('Unknown data type of ' + type); + break; + } + } + out = out.concat(dict.opcodes[key]); + } + return out; + }, + compileStringIndex: function CFFCompiler_compileStringIndex(strings) { + var stringIndex = new CFFIndex(); + for (var i = 0, ii = strings.length; i < ii; ++i) + stringIndex.add(stringToArray(strings[i])); + return this.compileIndex(stringIndex); + }, + compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() { + var globalSubrIndex = this.cff.globalSubrIndex; + this.out.writeByteArray(this.compileIndex(globalSubrIndex)); + }, + compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) { + return this.compileIndex(charStrings); + }, + compileCharset: function CFFCompiler_compileCharset(charset) { + return this.compileTypedArray(charset.raw); + }, + compileEncoding: function CFFCompiler_compileEncoding(encoding) { + return this.compileTypedArray(encoding.raw); + }, + compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) { + return this.compileTypedArray(fdSelect); + }, + compileTypedArray: function CFFCompiler_compileTypedArray(data) { + var out = []; + for (var i = 0, ii = data.length; i < ii; ++i) + out[i] = data[i]; + return out; + }, + compileIndex: function CFFCompiler_compileIndex(index, trackers) { + trackers = trackers || []; + var objects = index.objects; + // First 2 bytes contains the number of objects contained into this index + var count = objects.length; + + // If there is no object, just create an index. This technically + // should just be [0, 0] but OTS has an issue with that. + if (count == 0) + return [0, 0, 0]; + + var data = [(count >> 8) & 0xFF, count & 0xff]; + + var lastOffset = 1; + for (var i = 0; i < count; ++i) + lastOffset += objects[i].length; + + var offsetSize; + if (lastOffset < 0x100) + offsetSize = 1; + else if (lastOffset < 0x10000) + offsetSize = 2; + else if (lastOffset < 0x1000000) + offsetSize = 3; + else + offsetSize = 4; + + // Next byte contains the offset size use to reference object in the file + data.push(offsetSize); + + // Add another offset after this one because we need a new offset + var relativeOffset = 1; + for (var i = 0; i < count + 1; i++) { + if (offsetSize === 1) { + data.push(relativeOffset & 0xFF); + } else if (offsetSize === 2) { + data.push((relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } else if (offsetSize === 3) { + data.push((relativeOffset >> 16) & 0xFF, + (relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } else { + data.push((relativeOffset >>> 24) & 0xFF, + (relativeOffset >> 16) & 0xFF, + (relativeOffset >> 8) & 0xFF, + relativeOffset & 0xFF); + } + + if (objects[i]) + relativeOffset += objects[i].length; + } + var offset = data.length; + + for (var i = 0; i < count; i++) { + // Notify the tracker where the object will be offset in the data. + if (trackers[i]) + trackers[i].offset(data.length); + for (var j = 0, jj = objects[i].length; j < jj; j++) + data.push(objects[i][j]); + } + return data; } }; - - return constructor; + return CFFCompiler; })(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/function.js b/apps/files_pdfviewer/js/pdfjs/src/function.js old mode 100755 new mode 100644 index ef24736c135..2e7ad45e6ea --- a/apps/files_pdfviewer/js/pdfjs/src/function.js +++ b/apps/files_pdfviewer/js/pdfjs/src/function.js @@ -3,14 +3,14 @@ 'use strict'; -var PDFFunction = (function pdfFunction() { +var PDFFunction = (function PDFFunctionClosure() { var CONSTRUCT_SAMPLED = 0; var CONSTRUCT_INTERPOLATED = 2; var CONSTRUCT_STICHED = 3; var CONSTRUCT_POSTSCRIPT = 4; return { - getSampleArray: function pdfFunctionGetSampleArray(size, outputSize, bps, + getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps, str) { var length = 1; for (var i = 0, ii = size.length; i < ii; i++) @@ -38,7 +38,7 @@ var PDFFunction = (function pdfFunction() { return array; }, - getIR: function pdfFunctionGetIR(xref, fn) { + getIR: function PDFFunction_getIR(xref, fn) { var dict = fn.dict; if (!dict) dict = fn; @@ -57,7 +57,7 @@ var PDFFunction = (function pdfFunction() { return typeFn.call(this, fn, dict, xref); }, - fromIR: function pdfFunctionFromIR(IR) { + fromIR: function PDFFunction_fromIR(IR) { var type = IR[0]; switch (type) { case CONSTRUCT_SAMPLED: @@ -72,16 +72,16 @@ var PDFFunction = (function pdfFunction() { } }, - parse: function pdfFunctionParse(xref, fn) { + parse: function PDFFunction_parse(xref, fn) { var IR = this.getIR(xref, fn); return this.fromIR(IR); }, - constructSampled: function pdfFunctionConstructSampled(str, dict) { + constructSampled: function PDFFunction_constructSampled(str, dict) { function toMultiArray(arr) { var inputLength = arr.length; var outputLength = arr.length / 2; - var out = new Array(outputLength); + var out = []; var index = 0; for (var i = 0; i < inputLength; i += 2) { out[index] = [arr[i], arr[i + 1]]; @@ -125,114 +125,104 @@ var PDFFunction = (function pdfFunction() { else decode = toMultiArray(decode); - // Precalc the multipliers - var inputMul = new Float64Array(inputSize); - for (var i = 0; i < inputSize; ++i) { - inputMul[i] = (encode[i][1] - encode[i][0]) / - (domain[i][1] - domain[i][0]); - } - - var idxMul = new Int32Array(inputSize); - idxMul[0] = outputSize; - for (i = 1; i < inputSize; ++i) { - idxMul[i] = idxMul[i - 1] * size[i - 1]; - } - - var nSamples = outputSize; - for (i = 0; i < inputSize; ++i) - nSamples *= size[i]; - var samples = this.getSampleArray(size, outputSize, bps, str); return [ CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size, - outputSize, bps, range, inputMul, idxMul, nSamples + outputSize, Math.pow(2, bps) - 1, range ]; }, - constructSampledFromIR: function pdfFunctionConstructSampledFromIR(IR) { - var inputSize = IR[1]; - var domain = IR[2]; - var encode = IR[3]; - var decode = IR[4]; - var samples = IR[5]; - var size = IR[6]; - var outputSize = IR[7]; - var bps = IR[8]; - var range = IR[9]; - var inputMul = IR[10]; - var idxMul = IR[11]; - var nSamples = IR[12]; + constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) { + // See chapter 3, page 109 of the PDF reference + function interpolate(x, xmin, xmax, ymin, ymax) { + return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin))); + } return function constructSampledFromIRResult(args) { - if (inputSize != args.length) + // See chapter 3, page 110 of the PDF reference. + var m = IR[1]; + var domain = IR[2]; + var encode = IR[3]; + var decode = IR[4]; + var samples = IR[5]; + var size = IR[6]; + var n = IR[7]; + var mask = IR[8]; + var range = IR[9]; + + if (m != args.length) error('Incorrect number of arguments: ' + inputSize + ' != ' + args.length); - // Most of the below is a port of Poppler's implementation. - // TODO: There's a few other ways to do multilinear interpolation such - // as piecewise, which is much faster but an approximation. - var out = new Float64Array(outputSize); - var x; - var e = new Array(inputSize); - var efrac0 = new Float64Array(inputSize); - var efrac1 = new Float64Array(inputSize); - var sBuf = new Float64Array(1 << inputSize); - var i, j, k, idx, t; - - // map input values into sample array - for (i = 0; i < inputSize; ++i) { - x = (args[i] - domain[i][0]) * inputMul[i] + encode[i][0]; - if (x < 0) { - x = 0; - } else if (x > size[i] - 1) { - x = size[i] - 1; - } - e[i] = [Math.floor(x), 0]; - if ((e[i][1] = e[i][0] + 1) >= size[i]) { - // this happens if in[i] = domain[i][1] - e[i][1] = e[i][0]; - } - efrac1[i] = x - e[i][0]; - efrac0[i] = 1 - efrac1[i]; - } - // for each output, do m-linear interpolation - for (i = 0; i < outputSize; ++i) { - - // pull 2^m values out of the sample array - for (j = 0; j < (1 << inputSize); ++j) { - idx = i; - for (k = 0, t = j; k < inputSize; ++k, t >>= 1) { - idx += idxMul[k] * (e[k][t & 1]); - } - if (idx >= 0 && idx < nSamples) { - sBuf[j] = samples[idx]; + var x = args; + + // Building the cube vertices: its part and sample index + // http://rjwagner49.com/Mathematics/Interpolation.pdf + var cubeVertices = 1 << m; + var cubeN = new Float64Array(cubeVertices); + var cubeVertex = new Uint32Array(cubeVertices); + for (var j = 0; j < cubeVertices; j++) + cubeN[j] = 1; + + var k = n, pos = 1; + // Map x_i to y_j for 0 <= i < m using the sampled function. + for (var i = 0; i < m; ++i) { + // x_i' = min(max(x_i, Domain_2i), Domain_2i+1) + var domain_2i = domain[i][0]; + var domain_2i_1 = domain[i][1]; + var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1); + + // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1, + // Encode_2i, Encode_2i+1) + var e = interpolate(xi, domain_2i, domain_2i_1, + encode[i][0], encode[i][1]); + + // e_i' = min(max(e_i, 0), Size_i - 1) + var size_i = size[i]; + e = Math.min(Math.max(e, 0), size_i - 1); + + // Adjusting the cube: N and vertex sample index + var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1; + var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0); + var n1 = e - e0; // (e - e0) / (e1 - e0); + var offset0 = e0 * k; + var offset1 = offset0 + k; // e1 * k + for (var j = 0; j < cubeVertices; j++) { + if (j & pos) { + cubeN[j] *= n1; + cubeVertex[j] += offset1; } else { - sBuf[j] = 0; // TODO Investigate if this is what Adobe does + cubeN[j] *= n0; + cubeVertex[j] += offset0; } } - // do m sets of interpolations - for (j = 0, t = (1 << inputSize); j < inputSize; ++j, t >>= 1) { - for (k = 0; k < t; k += 2) { - sBuf[k >> 1] = efrac0[j] * sBuf[k] + efrac1[j] * sBuf[k + 1]; - } - } + k *= size_i; + pos <<= 1; + } - // map output value to range - out[i] = (sBuf[0] * (decode[i][1] - decode[i][0]) + decode[i][0]); - if (out[i] < range[i][0]) { - out[i] = range[i][0]; - } else if (out[i] > range[i][1]) { - out[i] = range[i][1]; - } + var y = new Float64Array(n); + for (var j = 0; j < n; ++j) { + // Sum all cube vertices' samples portions + var rj = 0; + for (var i = 0; i < cubeVertices; i++) + rj += samples[cubeVertex[i] + j] * cubeN[i]; + + // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1, + // Decode_2j, Decode_2j+1) + rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]); + + // y_j = min(max(r_j, range_2j), range_2j+1) + y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]); } - return out; + + return y; } }, - constructInterpolated: - function pdfFunctionConstructInterpolated(str, dict) { + constructInterpolated: function PDFFunction_constructInterpolated(str, + dict) { var c0 = dict.get('C0') || [0]; var c1 = dict.get('C1') || [1]; var n = dict.get('N'); @@ -249,7 +239,7 @@ var PDFFunction = (function pdfFunction() { }, constructInterpolatedFromIR: - function pdfFunctionconstructInterpolatedFromIR(IR) { + function PDFFunction_constructInterpolatedFromIR(IR) { var c0 = IR[1]; var diff = IR[2]; var n = IR[3]; @@ -268,9 +258,8 @@ var PDFFunction = (function pdfFunction() { } }, - constructStiched: function pdfFunctionConstructStiched(fn, dict, xref) { + constructStiched: function PDFFunction_constructStiched(fn, dict, xref) { var domain = dict.get('Domain'); - var range = dict.get('Range'); if (!domain) error('No domain'); @@ -290,7 +279,7 @@ var PDFFunction = (function pdfFunction() { return [CONSTRUCT_STICHED, domain, bounds, encode, fns]; }, - constructStichedFromIR: function pdfFunctionConstructStichedFromIR(IR) { + constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) { var domain = IR[1]; var bounds = IR[2]; var encode = IR[3]; @@ -336,16 +325,550 @@ var PDFFunction = (function pdfFunction() { }; }, - constructPostScript: function pdfFunctionConstructPostScript() { - return [CONSTRUCT_POSTSCRIPT]; + constructPostScript: function PDFFunction_constructPostScript(fn, dict, + xref) { + var domain = dict.get('Domain'); + var range = dict.get('Range'); + + if (!domain) + error('No domain.'); + + if (!range) + error('No range.'); + + var lexer = new PostScriptLexer(fn); + var parser = new PostScriptParser(lexer); + var code = parser.parse(); + + return [CONSTRUCT_POSTSCRIPT, domain, range, code]; }, - constructPostScriptFromIR: function pdfFunctionConstructPostScriptFromIR() { - TODO('unhandled type of function'); - return function constructPostScriptFromIRResult() { - return [255, 105, 180]; + constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR( + IR) { + var domain = IR[1]; + var range = IR[2]; + var code = IR[3]; + var numOutputs = range.length / 2; + var evaluator = new PostScriptEvaluator(code); + // Cache the values for a big speed up, the cache size is limited though + // since the number of possible values can be huge from a PS function. + var cache = new FunctionCache(); + return function constructPostScriptFromIRResult(args) { + var initialStack = []; + for (var i = 0, ii = (domain.length / 2); i < ii; ++i) { + initialStack.push(args[i]); + } + + var key = initialStack.join('_'); + if (cache.has(key)) + return cache.get(key); + + var stack = evaluator.execute(initialStack); + var transformed = []; + for (i = numOutputs - 1; i >= 0; --i) { + var out = stack.pop(); + var rangeIndex = 2 * i; + if (out < range[rangeIndex]) + out = range[rangeIndex]; + else if (out > range[rangeIndex + 1]) + out = range[rangeIndex + 1]; + transformed[i] = out; + } + cache.set(key, transformed); + return transformed; }; } }; })(); +var FunctionCache = (function FunctionCacheClosure() { + // Of 10 PDF's with type4 functions the maxium number of distinct values seen + // was 256. This still may need some tweaking in the future though. + var MAX_CACHE_SIZE = 1024; + function FunctionCache() { + this.cache = {}; + this.total = 0; + } + FunctionCache.prototype = { + has: function FunctionCache_has(key) { + return key in this.cache; + }, + get: function FunctionCache_get(key) { + return this.cache[key]; + }, + set: function FunctionCache_set(key, value) { + if (this.total < MAX_CACHE_SIZE) { + this.cache[key] = value; + this.total++; + } + } + }; + return FunctionCache; +})(); + +var PostScriptStack = (function PostScriptStackClosure() { + var MAX_STACK_SIZE = 100; + function PostScriptStack(initialStack) { + this.stack = initialStack || []; + } + + PostScriptStack.prototype = { + push: function PostScriptStack_push(value) { + if (this.stack.length >= MAX_STACK_SIZE) + error('PostScript function stack overflow.'); + this.stack.push(value); + }, + pop: function PostScriptStack_pop() { + if (this.stack.length <= 0) + error('PostScript function stack underflow.'); + return this.stack.pop(); + }, + copy: function PostScriptStack_copy(n) { + if (this.stack.length + n >= MAX_STACK_SIZE) + error('PostScript function stack overflow.'); + var stack = this.stack; + for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) + stack.push(stack[i]); + }, + index: function PostScriptStack_index(n) { + this.push(this.stack[this.stack.length - n - 1]); + }, + // rotate the last n stack elements p times + roll: function PostScriptStack_roll(n, p) { + var stack = this.stack; + var l = stack.length - n; + var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t; + for (i = l, j = r; i < j; i++, j--) { + t = stack[i]; stack[i] = stack[j]; stack[j] = t; + } + for (i = l, j = c - 1; i < j; i++, j--) { + t = stack[i]; stack[i] = stack[j]; stack[j] = t; + } + for (i = c, j = r; i < j; i++, j--) { + t = stack[i]; stack[i] = stack[j]; stack[j] = t; + } + } + }; + return PostScriptStack; +})(); +var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { + function PostScriptEvaluator(operators, operands) { + this.operators = operators; + this.operands = operands; + } + PostScriptEvaluator.prototype = { + execute: function PostScriptEvaluator_execute(initialStack) { + var stack = new PostScriptStack(initialStack); + var counter = 0; + var operators = this.operators; + var length = operators.length; + var operator, a, b; + while (counter < length) { + operator = operators[counter++]; + if (typeof operator == 'number') { + // Operator is really an operand and should be pushed to the stack. + stack.push(operator); + continue; + } + switch (operator) { + // non standard ps operators + case 'jz': // jump if false + b = stack.pop(); + a = stack.pop(); + if (!a) + counter = b; + break; + case 'j': // jump + a = stack.pop(); + counter = a; + break; + + // all ps operators in alphabetical order (excluding if/ifelse) + case 'abs': + a = stack.pop(); + stack.push(Math.abs(a)); + break; + case 'add': + b = stack.pop(); + a = stack.pop(); + stack.push(a + b); + break; + case 'and': + b = stack.pop(); + a = stack.pop(); + if (isBool(a) && isBool(b)) + stack.push(a && b); + else + stack.push(a & b); + break; + case 'atan': + a = stack.pop(); + stack.push(Math.atan(a)); + break; + case 'bitshift': + b = stack.pop(); + a = stack.pop(); + if (a > 0) + stack.push(a << b); + else + stack.push(a >> b); + break; + case 'ceiling': + a = stack.pop(); + stack.push(Math.ceil(a)); + break; + case 'copy': + a = stack.pop(); + stack.copy(a); + break; + case 'cos': + a = stack.pop(); + stack.push(Math.cos(a)); + break; + case 'cvi': + a = stack.pop() | 0; + stack.push(a); + break; + case 'cvr': + // noop + break; + case 'div': + b = stack.pop(); + a = stack.pop(); + stack.push(a / b); + break; + case 'dup': + stack.copy(1); + break; + case 'eq': + b = stack.pop(); + a = stack.pop(); + stack.push(a == b); + break; + case 'exch': + stack.roll(2, 1); + break; + case 'exp': + b = stack.pop(); + a = stack.pop(); + stack.push(Math.pow(a, b)); + break; + case 'false': + stack.push(false); + break; + case 'floor': + a = stack.pop(); + stack.push(Math.floor(a)); + break; + case 'ge': + b = stack.pop(); + a = stack.pop(); + stack.push(a >= b); + break; + case 'gt': + b = stack.pop(); + a = stack.pop(); + stack.push(a > b); + break; + case 'idiv': + b = stack.pop(); + a = stack.pop(); + stack.push((a / b) | 0); + break; + case 'index': + a = stack.pop(); + stack.index(a); + break; + case 'le': + b = stack.pop(); + a = stack.pop(); + stack.push(a <= b); + break; + case 'ln': + a = stack.pop(); + stack.push(Math.log(a)); + break; + case 'log': + a = stack.pop(); + stack.push(Math.log(a) / Math.LN10); + break; + case 'lt': + b = stack.pop(); + a = stack.pop(); + stack.push(a < b); + break; + case 'mod': + b = stack.pop(); + a = stack.pop(); + stack.push(a % b); + break; + case 'mul': + b = stack.pop(); + a = stack.pop(); + stack.push(a * b); + break; + case 'ne': + b = stack.pop(); + a = stack.pop(); + stack.push(a != b); + break; + case 'neg': + a = stack.pop(); + stack.push(-b); + break; + case 'not': + a = stack.pop(); + if (isBool(a) && isBool(b)) + stack.push(a && b); + else + stack.push(a & b); + break; + case 'or': + b = stack.pop(); + a = stack.pop(); + if (isBool(a) && isBool(b)) + stack.push(a || b); + else + stack.push(a | b); + break; + case 'pop': + stack.pop(); + break; + case 'roll': + b = stack.pop(); + a = stack.pop(); + stack.roll(a, b); + break; + case 'round': + a = stack.pop(); + stack.push(Math.round(a)); + break; + case 'sin': + a = stack.pop(); + stack.push(Math.sin(a)); + break; + case 'sqrt': + a = stack.pop(); + stack.push(Math.sqrt(a)); + break; + case 'sub': + b = stack.pop(); + a = stack.pop(); + stack.push(a - b); + break; + case 'true': + stack.push(true); + break; + case 'truncate': + a = stack.pop(); + a = a < 0 ? Math.ceil(a) : Math.floor(a); + stack.push(a); + break; + case 'xor': + b = stack.pop(); + a = stack.pop(); + if (isBool(a) && isBool(b)) + stack.push(a != b); + else + stack.push(a ^ b); + break; + default: + error('Unknown operator ' + operator); + break; + } + } + return stack.stack; + } + }; + return PostScriptEvaluator; +})(); + +var PostScriptParser = (function PostScriptParserClosure() { + function PostScriptParser(lexer) { + this.lexer = lexer; + this.operators = []; + this.token; + this.prev; + } + PostScriptParser.prototype = { + nextToken: function PostScriptParser_nextToken() { + this.prev = this.token; + this.token = this.lexer.getToken(); + }, + accept: function PostScriptParser_accept(type) { + if (this.token.type == type) { + this.nextToken(); + return true; + } + return false; + }, + expect: function PostScriptParser_expect(type) { + if (this.accept(type)) + return true; + error('Unexpected symbol: found ' + this.token.type + ' expected ' + + type + '.'); + }, + parse: function PostScriptParser_parse() { + this.nextToken(); + this.expect(PostScriptTokenTypes.LBRACE); + this.parseBlock(); + this.expect(PostScriptTokenTypes.RBRACE); + return this.operators; + }, + parseBlock: function PostScriptParser_parseBlock() { + while (true) { + if (this.accept(PostScriptTokenTypes.NUMBER)) { + this.operators.push(this.prev.value); + } else if (this.accept(PostScriptTokenTypes.OPERATOR)) { + this.operators.push(this.prev.value); + } else if (this.accept(PostScriptTokenTypes.LBRACE)) { + this.parseCondition(); + } else { + return; + } + } + }, + parseCondition: function PostScriptParser_parseCondition() { + // Add two place holders that will be updated later + var conditionLocation = this.operators.length; + this.operators.push(null, null); + + this.parseBlock(); + this.expect(PostScriptTokenTypes.RBRACE); + if (this.accept(PostScriptTokenTypes.IF)) { + // The true block is right after the 'if' so it just falls through on + // true else it jumps and skips the true block. + this.operators[conditionLocation] = this.operators.length; + this.operators[conditionLocation + 1] = 'jz'; + } else if (this.accept(PostScriptTokenTypes.LBRACE)) { + var jumpLocation = this.operators.length; + this.operators.push(null, null); + var endOfTrue = this.operators.length; + this.parseBlock(); + this.expect(PostScriptTokenTypes.RBRACE); + this.expect(PostScriptTokenTypes.IFELSE); + // The jump is added at the end of the true block to skip the false + // block. + this.operators[jumpLocation] = this.operators.length; + this.operators[jumpLocation + 1] = 'j'; + + this.operators[conditionLocation] = endOfTrue; + this.operators[conditionLocation + 1] = 'jz'; + } else { + error('PS Function: error parsing conditional.'); + } + } + }; + return PostScriptParser; +})(); + +var PostScriptTokenTypes = { + LBRACE: 0, + RBRACE: 1, + NUMBER: 2, + OPERATOR: 3, + IF: 4, + IFELSE: 5 +}; + +var PostScriptToken = (function PostScriptTokenClosure() { + function PostScriptToken(type, value) { + this.type = type; + this.value = value; + } + + var opCache = {}; + + PostScriptToken.getOperator = function PostScriptToken_getOperator(op) { + var opValue = opCache[op]; + if (opValue) + return opValue; + + return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op); + }; + + PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE, + '{'); + PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE, + '}'); + PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF'); + PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE, + 'IFELSE'); + return PostScriptToken; +})(); + +var PostScriptLexer = (function PostScriptLexerClosure() { + function PostScriptLexer(stream) { + this.stream = stream; + } + PostScriptLexer.prototype = { + getToken: function PostScriptLexer_getToken() { + var s = ''; + var ch; + var comment = false; + var stream = this.stream; + + // skip comments + while (true) { + if (!(ch = stream.getChar())) + return EOF; + + if (comment) { + if (ch == '\x0a' || ch == '\x0d') + comment = false; + } else if (ch == '%') { + comment = true; + } else if (!Lexer.isSpace(ch)) { + break; + } + } + switch (ch) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case '+': case '-': case '.': + return new PostScriptToken(PostScriptTokenTypes.NUMBER, + this.getNumber(ch)); + case '{': + return PostScriptToken.LBRACE; + case '}': + return PostScriptToken.RBRACE; + } + // operator + var str = ch.toLowerCase(); + while (true) { + ch = stream.lookChar().toLowerCase(); + if (ch >= 'a' && ch <= 'z') + str += ch; + else + break; + stream.skip(); + } + switch (str) { + case 'if': + return PostScriptToken.IF; + case 'ifelse': + return PostScriptToken.IFELSE; + default: + return PostScriptToken.getOperator(str); + } + }, + getNumber: function PostScriptLexer_getNumber(ch) { + var str = ch; + var stream = this.stream; + while (true) { + ch = stream.lookChar(); + if ((ch >= '0' && ch <= '9') || ch == '-' || ch == '.') + str += ch; + else + break; + stream.skip(); + } + var value = parseFloat(str); + if (isNaN(value)) + error('Invalid floating point number: ' + value); + return value; + } + }; + return PostScriptLexer; +})(); + diff --git a/apps/files_pdfviewer/js/pdfjs/src/glyphlist.js b/apps/files_pdfviewer/js/pdfjs/src/glyphlist.js old mode 100755 new mode 100644 index 5691f85461e..694134840e6 --- a/apps/files_pdfviewer/js/pdfjs/src/glyphlist.js +++ b/apps/files_pdfviewer/js/pdfjs/src/glyphlist.js @@ -1508,27 +1508,7 @@ var GlyphsUnicode = { dalet: 0x05D3, daletdagesh: 0xFB33, daletdageshhebrew: 0xFB33, - dalethatafpatah: 0x05D305B2, - dalethatafpatahhebrew: 0x05D305B2, - dalethatafsegol: 0x05D305B1, - dalethatafsegolhebrew: 0x05D305B1, dalethebrew: 0x05D3, - dalethiriq: 0x05D305B4, - dalethiriqhebrew: 0x05D305B4, - daletholam: 0x05D305B9, - daletholamhebrew: 0x05D305B9, - daletpatah: 0x05D305B7, - daletpatahhebrew: 0x05D305B7, - daletqamats: 0x05D305B8, - daletqamatshebrew: 0x05D305B8, - daletqubuts: 0x05D305BB, - daletqubutshebrew: 0x05D305BB, - daletsegol: 0x05D305B6, - daletsegolhebrew: 0x05D305B6, - daletsheva: 0x05D305B0, - daletshevahebrew: 0x05D305B0, - dalettsere: 0x05D305B5, - dalettserehebrew: 0x05D305B5, dalfinalarabic: 0xFEAA, dammaarabic: 0x064F, dammalowarabic: 0x064F, @@ -1845,10 +1825,6 @@ var GlyphsUnicode = { finalkafdagesh: 0xFB3A, finalkafdageshhebrew: 0xFB3A, finalkafhebrew: 0x05DA, - finalkafqamats: 0x05DA05B8, - finalkafqamatshebrew: 0x05DA05B8, - finalkafsheva: 0x05DA05B0, - finalkafshevahebrew: 0x05DA05B0, finalmem: 0x05DD, finalmemhebrew: 0x05DD, finalnun: 0x05DF, @@ -2037,14 +2013,7 @@ var GlyphsUnicode = { hakatakanahalfwidth: 0xFF8A, halantgurmukhi: 0x0A4D, hamzaarabic: 0x0621, - hamzadammaarabic: 0x0621064F, - hamzadammatanarabic: 0x0621064C, - hamzafathaarabic: 0x0621064E, - hamzafathatanarabic: 0x0621064B, hamzalowarabic: 0x0621, - hamzalowkasraarabic: 0x06210650, - hamzalowkasratanarabic: 0x0621064D, - hamzasukunarabic: 0x06210652, hangulfiller: 0x3164, hardsigncyrillic: 0x044A, harpoonleftbarbup: 0x21BC, @@ -2476,10 +2445,6 @@ var GlyphsUnicode = { lameddagesh: 0xFB3C, lameddageshhebrew: 0xFB3C, lamedhebrew: 0x05DC, - lamedholam: 0x05DC05B9, - lamedholamdagesh: '05DC 05B9 05BC', - lamedholamdageshhebrew: '05DC 05B9 05BC', - lamedholamhebrew: 0x05DC05B9, lamfinalarabic: 0xFEDE, lamhahinitialarabic: 0xFCCA, laminitialarabic: 0xFEDF, @@ -2489,8 +2454,6 @@ var GlyphsUnicode = { lammedialarabic: 0xFEE0, lammeemhahinitialarabic: 0xFD88, lammeeminitialarabic: 0xFCCC, - lammeemjeeminitialarabic: 'FEDF FEE4 FEA0', - lammeemkhahinitialarabic: 'FEDF FEE4 FEA8', largecircle: 0x25EF, lbar: 0x019A, lbelt: 0x026C, @@ -2787,7 +2750,6 @@ var GlyphsUnicode = { noonfinalarabic: 0xFEE6, noonghunnaarabic: 0x06BA, noonghunnafinalarabic: 0xFB9F, - noonhehinitialarabic: 0xFEE7FEEC, nooninitialarabic: 0xFEE7, noonjeeminitialarabic: 0xFCD2, noonjeemisolatedarabic: 0xFC4B, @@ -3159,27 +3121,7 @@ var GlyphsUnicode = { qof: 0x05E7, qofdagesh: 0xFB47, qofdageshhebrew: 0xFB47, - qofhatafpatah: 0x05E705B2, - qofhatafpatahhebrew: 0x05E705B2, - qofhatafsegol: 0x05E705B1, - qofhatafsegolhebrew: 0x05E705B1, qofhebrew: 0x05E7, - qofhiriq: 0x05E705B4, - qofhiriqhebrew: 0x05E705B4, - qofholam: 0x05E705B9, - qofholamhebrew: 0x05E705B9, - qofpatah: 0x05E705B7, - qofpatahhebrew: 0x05E705B7, - qofqamats: 0x05E705B8, - qofqamatshebrew: 0x05E705B8, - qofqubuts: 0x05E705BB, - qofqubutshebrew: 0x05E705BB, - qofsegol: 0x05E705B6, - qofsegolhebrew: 0x05E705B6, - qofsheva: 0x05E705B0, - qofshevahebrew: 0x05E705B0, - qoftsere: 0x05E705B5, - qoftserehebrew: 0x05E705B5, qparen: 0x24AC, quarternote: 0x2669, qubuts: 0x05BB, @@ -3253,32 +3195,11 @@ var GlyphsUnicode = { reharmenian: 0x0580, rehfinalarabic: 0xFEAE, rehiragana: 0x308C, - rehyehaleflamarabic: '0631 FEF3 FE8E 0644', rekatakana: 0x30EC, rekatakanahalfwidth: 0xFF9A, resh: 0x05E8, reshdageshhebrew: 0xFB48, - reshhatafpatah: 0x05E805B2, - reshhatafpatahhebrew: 0x05E805B2, - reshhatafsegol: 0x05E805B1, - reshhatafsegolhebrew: 0x05E805B1, reshhebrew: 0x05E8, - reshhiriq: 0x05E805B4, - reshhiriqhebrew: 0x05E805B4, - reshholam: 0x05E805B9, - reshholamhebrew: 0x05E805B9, - reshpatah: 0x05E805B7, - reshpatahhebrew: 0x05E805B7, - reshqamats: 0x05E805B8, - reshqamatshebrew: 0x05E805B8, - reshqubuts: 0x05E805BB, - reshqubutshebrew: 0x05E805BB, - reshsegol: 0x05E805B6, - reshsegolhebrew: 0x05E805B6, - reshsheva: 0x05E805B0, - reshshevahebrew: 0x05E805B0, - reshtsere: 0x05E805B5, - reshtserehebrew: 0x05E805B5, reversedtilde: 0x223D, reviahebrew: 0x0597, reviamugrashhebrew: 0x0597, @@ -3477,7 +3398,6 @@ var GlyphsUnicode = { shaddadammaarabic: 0xFC61, shaddadammatanarabic: 0xFC5E, shaddafathaarabic: 0xFC60, - shaddafathatanarabic: 0x0651064B, shaddakasraarabic: 0xFC62, shaddakasratanarabic: 0xFC5F, shade: 0x2592, @@ -3674,7 +3594,6 @@ var GlyphsUnicode = { tchehfinalarabic: 0xFB7B, tchehinitialarabic: 0xFB7C, tchehmedialarabic: 0xFB7D, - tchehmeeminitialarabic: 0xFB7CFEE4, tcircle: 0x24E3, tcircumflexbelow: 0x1E71, tcommaaccent: 0x0163, @@ -4287,6 +4206,7 @@ var GlyphsUnicode = { zretroflexhook: 0x0290, zstroke: 0x01B6, zuhiragana: 0x305A, - zukatakana: 0x30BA + zukatakana: 0x30BA, + '.notdef': 0x0000 }; diff --git a/apps/files_pdfviewer/js/pdfjs/src/image.js b/apps/files_pdfviewer/js/pdfjs/src/image.js old mode 100755 new mode 100644 index 17ef7b06d82..035e2f754be --- a/apps/files_pdfviewer/js/pdfjs/src/image.js +++ b/apps/files_pdfviewer/js/pdfjs/src/image.js @@ -3,8 +3,37 @@ 'use strict'; -var PDFImage = (function pdfImage() { - function constructor(xref, res, image, inline) { +var PDFImage = (function PDFImageClosure() { + /** + * Decode the image in the main thread if it supported. Resovles the promise + * when the image data is ready. + */ + function handleImageData(handler, xref, res, image, promise) { + if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) { + // For natively supported jpegs send them to the main thread for decoding. + var dict = image.dict; + var colorSpace = dict.get('ColorSpace', 'CS'); + colorSpace = ColorSpace.parse(colorSpace, xref, res); + var numComps = colorSpace.numComps; + handler.send('jpeg_decode', [image.getIR(), numComps], function(message) { + var data = message.data; + var stream = new Stream(data, 0, data.length, image.dict); + promise.resolve(stream); + }); + } else { + promise.resolve(image); + } + } + /** + * Decode and clamp a value. The formula is different from the spec because we + * don't decode to float range [0,1], we decode it in the [0,max] range. + */ + function decodeAndClamp(value, addend, coefficient, max) { + value = addend + value * coefficient; + // Clamp the value to the range + return value < 0 ? 0 : value > max ? max : value; + } + function PDFImage(xref, res, image, inline, smask) { this.image = image; if (image.getParams) { // JPX/JPEG2000 streams directly contain bits per component @@ -49,34 +78,143 @@ var PDFImage = (function pdfImage() { } this.decode = dict.get('Decode', 'D'); + this.needsDecode = false; + if (this.decode && this.colorSpace && + !this.colorSpace.isDefaultDecode(this.decode)) { + this.needsDecode = true; + // Do some preprocessing to avoid more math. + var max = (1 << bitsPerComponent) - 1; + this.decodeCoefficients = []; + this.decodeAddends = []; + for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) { + var dmin = this.decode[i]; + var dmax = this.decode[i + 1]; + this.decodeCoefficients[j] = dmax - dmin; + this.decodeAddends[j] = max * dmin; + } + } - var mask = xref.fetchIfRef(dict.get('Mask')); - var smask = xref.fetchIfRef(dict.get('SMask')); + var mask = dict.get('Mask'); if (mask) { TODO('masked images'); } else if (smask) { - this.smask = new PDFImage(xref, res, smask); + this.smask = new PDFImage(xref, res, smask, false); } } + /** + * Handles processing of image data and calls the callback with an argument + * of a PDFImage when the image is ready to be used. + */ + PDFImage.buildImage = function PDFImage_buildImage(callback, handler, xref, + res, image, inline) { + var imageDataPromise = new Promise(); + var smaskPromise = new Promise(); + // The image data and smask data may not be ready yet, wait till both are + // resolved. + Promise.all([imageDataPromise, smaskPromise]).then(function(results) { + var imageData = results[0], smaskData = results[1]; + var image = new PDFImage(xref, res, imageData, inline, smaskData); + callback(image); + }); + + handleImageData(handler, xref, res, image, imageDataPromise); + + var smask = image.dict.get('SMask'); + if (smask) + handleImageData(handler, xref, res, smask, smaskPromise); + else + smaskPromise.resolve(null); + }; + + /** + * Resize an image using the nearest neighbor algorithm. Currently only + * supports one and three component images. + * @param {TypedArray} pixels The original image with one component. + * @param {Number} bpc Number of bits per component. + * @param {Number} components Number of color components, 1 or 3 is supported. + * @param {Number} w1 Original width. + * @param {Number} h1 Original height. + * @param {Number} w2 New width. + * @param {Number} h2 New height. + * @return {TypedArray} Resized image data. + */ + PDFImage.resize = function PDFImage_resize(pixels, bpc, components, + w1, h1, w2, h2) { + var length = w2 * h2 * components; + var temp = bpc <= 8 ? new Uint8Array(length) : + bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length); + var xRatio = w1 / w2; + var yRatio = h1 / h2; + var px, py, newIndex, oldIndex; + for (var i = 0; i < h2; i++) { + for (var j = 0; j < w2; j++) { + px = Math.floor(j * xRatio); + py = Math.floor(i * yRatio); + newIndex = (i * w2) + j; + oldIndex = ((py * w1) + px); + if (components === 1) { + temp[newIndex] = pixels[oldIndex]; + } else if (components === 3) { + newIndex *= 3; + oldIndex *= 3; + temp[newIndex] = pixels[oldIndex]; + temp[newIndex + 1] = pixels[oldIndex + 1]; + temp[newIndex + 2] = pixels[oldIndex + 2]; + } + } + } + return temp; + }; - constructor.prototype = { - getComponents: function getComponents(buffer, decodeMap) { + PDFImage.prototype = { + get drawWidth() { + if (!this.smask) + return this.width; + return Math.max(this.width, this.smask.width); + }, + get drawHeight() { + if (!this.smask) + return this.height; + return Math.max(this.height, this.smask.height); + }, + getComponents: function PDFImage_getComponents(buffer) { var bpc = this.bpc; - if (bpc == 8) + var needsDecode = this.needsDecode; + var decodeMap = this.decode; + + // This image doesn't require any extra work. + if (bpc == 8 && !needsDecode) return buffer; + var bufferLength = buffer.length; var width = this.width; var height = this.height; var numComps = this.numComps; - var length = width * height; + var length = width * height * numComps; var bufferPos = 0; var output = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length); var rowComps = width * numComps; + var decodeAddends, decodeCoefficients; + if (needsDecode) { + decodeAddends = this.decodeAddends; + decodeCoefficients = this.decodeCoefficients; + } + var max = (1 << bpc) - 1; - if (bpc == 1) { + if (bpc == 8) { + // Optimization for reading 8 bpc images that have a decode. + for (var i = 0, ii = length; i < ii; ++i) { + var compIndex = i % numComps; + var value = buffer[i]; + value = decodeAndClamp(value, decodeAddends[compIndex], + decodeCoefficients[compIndex], max); + output[i] = value; + } + } else if (bpc == 1) { + // Optimization for reading 1 bpc images. var valueZero = 0, valueOne = 1; if (decodeMap) { valueZero = decodeMap[0] ? 1 : 0; @@ -101,8 +239,7 @@ var PDFImage = (function pdfImage() { output[i] = !(buf & mask) ? valueZero : valueOne; } } else { - if (decodeMap != null) - TODO('interpolate component values'); + // The general case that handles all other bpc values. var bits = 0, buf = 0; for (var i = 0, ii = length; i < ii; ++i) { if (i % rowComps == 0) { @@ -116,51 +253,44 @@ var PDFImage = (function pdfImage() { } var remainingBits = bits - bpc; - output[i] = buf >> remainingBits; + var value = buf >> remainingBits; + if (needsDecode) { + var compIndex = i % numComps; + value = decodeAndClamp(value, decodeAddends[compIndex], + decodeCoefficients[compIndex], max); + } + output[i] = value; buf = buf & ((1 << remainingBits) - 1); bits = remainingBits; } } return output; }, - getOpacity: function getOpacity() { + getOpacity: function PDFImage_getOpacity(width, height) { var smask = this.smask; - var width = this.width; - var height = this.height; - var buf = new Uint8Array(width * height); + var originalWidth = this.width; + var originalHeight = this.height; + var buf; if (smask) { - if (smask.image.getImage) { - // smask is a DOM image - var tempCanvas = new ScratchCanvas(width, height); - var tempCtx = tempCanvas.getContext('2d'); - var domImage = smask.image.getImage(); - tempCtx.drawImage(domImage, 0, 0, domImage.width, domImage.height, - 0, 0, width, height); - var data = tempCtx.getImageData(0, 0, width, height).data; - for (var i = 0, j = 0, ii = width * height; i < ii; ++i, j += 4) - buf[i] = data[j]; // getting first component value - return buf; - } var sw = smask.width; var sh = smask.height; - if (sw != this.width || sh != this.height) - error('smask dimensions do not match image dimensions: ' + sw + - ' != ' + this.width + ', ' + sh + ' != ' + this.height); - + buf = new Uint8Array(sw * sh); smask.fillGrayBuffer(buf); - return buf; + if (sw != width || sh != height) + buf = PDFImage.resize(buf, smask.bps, 1, sw, sh, width, height); } else { + buf = new Uint8Array(width * height); for (var i = 0, ii = width * height; i < ii; ++i) buf[i] = 255; } return buf; }, - applyStencilMask: function applyStencilMask(buffer, inverseDecode) { + applyStencilMask: function PDFImage_applyStencilMask(buffer, + inverseDecode) { var width = this.width, height = this.height; var bitStrideLength = (width + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(bitStrideLength * height); + var imgArray = this.getImageBytes(bitStrideLength * height); var imgArrayPos = 0; var i, j, mask, buf; // removing making non-masked pixels transparent @@ -180,21 +310,23 @@ var PDFImage = (function pdfImage() { } } }, - fillRgbaBuffer: function fillRgbaBuffer(buffer, decodeMap) { + fillRgbaBuffer: function PDFImage_fillRgbaBuffer(buffer, width, height) { var numComps = this.numComps; - var width = this.width; - var height = this.height; + var originalWidth = this.width; + var originalHeight = this.height; var bpc = this.bpc; // rows start at byte boundary; - var rowBytes = (width * numComps * bpc + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(height * rowBytes); + var rowBytes = (originalWidth * numComps * bpc + 7) >> 3; + var imgArray = this.getImageBytes(originalHeight * rowBytes); var comps = this.colorSpace.getRgbBuffer( - this.getComponents(imgArray, decodeMap), bpc); + this.getComponents(imgArray), bpc); + if (originalWidth != width || originalHeight != height) + comps = PDFImage.resize(comps, this.bpc, 3, originalWidth, + originalHeight, width, height); var compsPos = 0; - var opacity = this.getOpacity(); + var opacity = this.getOpacity(width, height); var opacityPos = 0; var length = width * height * 4; @@ -205,7 +337,7 @@ var PDFImage = (function pdfImage() { buffer[i + 3] = opacity[opacityPos++]; } }, - fillGrayBuffer: function fillGrayBuffer(buffer) { + fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) { var numComps = this.numComps; if (numComps != 1) error('Reading gray scale from a color image: ' + numComps); @@ -216,42 +348,28 @@ var PDFImage = (function pdfImage() { // rows start at byte boundary; var rowBytes = (width * numComps * bpc + 7) >> 3; - this.image.reset(); - var imgArray = this.image.getBytes(height * rowBytes); + var imgArray = this.getImageBytes(height * rowBytes); var comps = this.getComponents(imgArray); var length = width * height; - + // we aren't using a colorspace so we need to scale the value + var scale = 255 / ((1 << bpc) - 1); for (var i = 0; i < length; ++i) - buffer[i] = comps[i]; + buffer[i] = (scale * comps[i]) | 0; + }, + getImageBytes: function PDFImage_getImageBytes(length) { + this.image.reset(); + return this.image.getBytes(length); } }; - return constructor; + return PDFImage; })(); -var JpegImageLoader = (function jpegImage() { - function JpegImageLoader(objId, imageData, objs) { - var src = 'data:image/jpeg;base64,' + window.btoa(imageData); - - var img = new Image(); - img.onload = (function jpegImageLoaderOnload() { - this.loaded = true; - - objs.resolve(objId, this); - - if (this.onLoad) - this.onLoad(); - }).bind(this); - img.src = src; - this.domImage = img; - } - - JpegImageLoader.prototype = { - getImage: function jpegImageLoaderGetImage() { - return this.domImage; - } - }; - - return JpegImageLoader; -})(); +function loadJpegStream(id, imageData, objs) { + var img = new Image(); + img.onload = (function loadJpegStream_onloadClosure() { + objs.resolve(id, img); + }); + img.src = 'data:image/jpeg;base64,' + window.btoa(imageData); +} diff --git a/apps/files_pdfviewer/js/pdfjs/src/jpx.js b/apps/files_pdfviewer/js/pdfjs/src/jpx.js new file mode 100644 index 00000000000..63193753d2a --- /dev/null +++ b/apps/files_pdfviewer/js/pdfjs/src/jpx.js @@ -0,0 +1,1862 @@ +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +'use strict'; + +var JpxImage = (function JpxImageClosure() { + // Table E.1 + var SubbandsGainLog2 = { + 'LL': 0, + 'LH': 1, + 'HL': 1, + 'HH': 2 + }; + function JpxImage() { + this.failOnCorruptedImage = false; + } + JpxImage.prototype = { + load: function JpxImage_load(url) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = (function() { + // TODO catch parse error + var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function JpxImage_parse(data) { + function ReadUint(data, offset, bytes) { + var n = 0; + for (var i = 0; i < bytes; i++) + n = n * 256 + (data[offset + i] & 0xFF); + return n; + } + var position = 0, length = data.length; + while (position < length) { + var headerSize = 8; + var lbox = ReadUint(data, position, 4); + var tbox = ReadUint(data, position + 4, 4); + position += headerSize; + if (lbox == 1) { + lbox = ReadUint(data, position, 8); + position += 8; + headerSize += 8; + } + if (lbox == 0) + lbox = length - position + headerSize; + if (lbox < headerSize) + error('JPX error: Invalid box field size'); + var dataLength = lbox - headerSize; + var jumpDataLength = true; + switch (tbox) { + case 0x6A501A1A: // 'jP\032\032' + // TODO + break; + case 0x6A703268: // 'jp2h' + jumpDataLength = false; // parsing child boxes + break; + case 0x636F6C72: // 'colr' + // TODO + break; + case 0x6A703263: // 'jp2c' + this.parseCodestream(data, position, position + dataLength); + break; + } + if (jumpDataLength) + position += dataLength; + } + }, + parseCodestream: function JpxImage_parseCodestream(data, start, end) { + var context = {}; + try { + var position = start; + while (position < end) { + var code = readUint16(data, position); + position += 2; + + var length = 0, j; + switch (code) { + case 0xFF4F: // Start of codestream (SOC) + context.mainHeader = true; + break; + case 0xFFD9: // End of codestream (EOC) + break; + case 0xFF51: // Image and tile size (SIZ) + length = readUint16(data, position); + var siz = {}; + siz.Xsiz = readUint32(data, position + 4); + siz.Ysiz = readUint32(data, position + 8); + siz.XOsiz = readUint32(data, position + 12); + siz.YOsiz = readUint32(data, position + 16); + siz.XTsiz = readUint32(data, position + 20); + siz.YTsiz = readUint32(data, position + 24); + siz.XTOsiz = readUint32(data, position + 28); + siz.YTOsiz = readUint32(data, position + 32); + var componentsCount = readUint16(data, position + 36); + siz.Csiz = componentsCount; + var components = []; + j = position + 38; + for (var i = 0; i < componentsCount; i++) { + var component = { + precision: (data[j] & 0x7F) + 1, + isSigned: !!(data[j] & 0x80), + XRsiz: data[j + 1], + YRsiz: data[j + 1] + }; + calculateComponentDimensions(component, siz); + components.push(component); + } + context.SIZ = siz; + context.components = components; + calculateTileGrids(context, components); + context.QCC = []; + context.COC = []; + break; + case 0xFF5C: // Quantization default (QCD) + length = readUint16(data, position); + var qcd = {}; + j = position + 2; + var sqcd = data[j++]; + var spqcdSize, scalarExpounded; + switch (sqcd & 0x1F) { + case 0: + spqcdSize = 8; + scalarExpounded = true; + break; + case 1: + spqcdSize = 16; + scalarExpounded = false; + break; + case 2: + spqcdSize = 16; + scalarExpounded = true; + break; + default: + throw 'Invalid SQcd value ' + sqcd; + } + qcd.noQuantization = spqcdSize == 8; + qcd.scalarExpounded = scalarExpounded; + qcd.guardBits = sqcd >> 5; + var spqcds = []; + while (j < length + position) { + var spqcd = {}; + if (spqcdSize == 8) { + spqcd.epsilon = data[j++] >> 3; + spqcd.mu = 0; + } else { + spqcd.epsilon = data[j] >> 3; + spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1]; + j += 2; + } + spqcds.push(spqcd); + } + qcd.SPqcds = spqcds; + if (context.mainHeader) + context.QCD = qcd; + else { + context.currentTile.QCD = qcd; + context.currentTile.QCC = []; + } + break; + case 0xFF5D: // Quantization component (QCC) + length = readUint16(data, position); + var qcc = {}; + j = position + 2; + var cqcc; + if (context.SIZ.Csiz < 257) + cqcc = data[j++]; + else { + cqcc = readUint16(data, j); + j += 2; + } + var sqcd = data[j++]; + var spqcdSize, scalarExpounded; + switch (sqcd & 0x1F) { + case 0: + spqcdSize = 8; + scalarExpounded = true; + break; + case 1: + spqcdSize = 16; + scalarExpounded = false; + break; + case 2: + spqcdSize = 16; + scalarExpounded = true; + break; + default: + throw 'Invalid SQcd value ' + sqcd; + } + qcc.noQuantization = spqcdSize == 8; + qcc.scalarExpounded = scalarExpounded; + qcc.guardBits = sqcd >> 5; + var spqcds = []; + while (j < length + position) { + var spqcd = {}; + if (spqcdSize == 8) { + spqcd.epsilon = data[j++] >> 3; + spqcd.mu = 0; + } else { + spqcd.epsilon = data[j] >> 3; + spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1]; + j += 2; + } + spqcds.push(spqcd); + } + qcc.SPqcds = spqcds; + if (context.mainHeader) + context.QCC[cqcc] = qcc; + else + context.currentTile.QCC[cqcc] = qcc; + break; + case 0xFF52: // Coding style default (COD) + length = readUint16(data, position); + var cod = {}; + j = position + 2; + var scod = data[j++]; + cod.entropyCoderWithCustomPrecincts = !!(scod & 1); + cod.sopMarkerUsed = !!(scod & 2); + cod.ephMarkerUsed = !!(scod & 4); + var codingStyle = {}; + cod.progressionOrder = data[j++]; + cod.layersCount = readUint16(data, j); + j += 2; + cod.multipleComponentTransform = data[j++]; + + cod.decompositionLevelsCount = data[j++]; + cod.xcb = (data[j++] & 0xF) + 2; + cod.ycb = (data[j++] & 0xF) + 2; + var blockStyle = data[j++]; + cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1); + cod.resetContextProbabilities = !!(blockStyle & 2); + cod.terminationOnEachCodingPass = !!(blockStyle & 4); + cod.verticalyStripe = !!(blockStyle & 8); + cod.predictableTermination = !!(blockStyle & 16); + cod.segmentationSymbolUsed = !!(blockStyle & 32); + cod.transformation = data[j++]; + if (cod.entropyCoderWithCustomPrecincts) { + var precinctsSizes = {}; + while (j < length + position) { + var precinctsSize = data[j]; + precinctsSizes.push({ + PPx: precinctsSize & 0xF, + PPy: precinctsSize >> 4 + }); + } + cod.precinctsSizes = precinctsSizes; + } + + if (cod.sopMarkerUsed || cod.ephMarkerUsed || + cod.selectiveArithmeticCodingBypass || + cod.resetContextProbabilities || + cod.terminationOnEachCodingPass || + cod.verticalyStripe || cod.predictableTermination || + cod.segmentationSymbolUsed) + throw 'Unsupported COD options: ' + uneval(cod); + + if (context.mainHeader) + context.COD = cod; + else { + context.currentTile.COD = cod; + context.currentTile.COC = []; + } + break; + case 0xFF90: // Start of tile-part (SOT) + length = readUint16(data, position); + var tile = {}; + tile.index = readUint16(data, position + 2); + tile.length = readUint32(data, position + 4); + tile.dataEnd = tile.length + position - 2; + tile.partIndex = data[position + 8]; + tile.partsCount = data[position + 9]; + + context.mainHeader = false; + if (tile.partIndex == 0) { + // reset component specific settings + tile.COD = context.COD; + tile.COC = context.COC.slice(0); // clone of the global COC + tile.QCD = context.QCD; + tile.QCC = context.QCC.slice(0); // clone of the global COC + } + context.currentTile = tile; + break; + case 0xFF93: // Start of data (SOD) + var tile = context.currentTile; + if (tile.partIndex == 0) { + initializeTile(context, tile.index); + buildPackets(context); + } + + // moving to the end of the data + length = tile.dataEnd - position; + + parseTilePackets(context, data, position, length); + break; + case 0xFF64: // Comment (COM) + length = readUint16(data, position); + // skipping content + break; + default: + throw 'Unknown codestream code: ' + code.toString(16); + } + position += length; + } + } catch (e) { + if (this.failOnCorruptedImage) + error('JPX error: ' + e); + else + warn('JPX error: ' + e + '. Trying to recover'); + } + this.tiles = transformComponents(context); + this.width = context.SIZ.Xsiz - context.SIZ.XOsiz; + this.height = context.SIZ.Ysiz - context.SIZ.YOsiz; + this.componentsCount = context.SIZ.Csiz; + } + }; + function readUint32(data, offset) { + return (data[offset] << 24) | (data[offset + 1] << 16) | + (data[offset + 2] << 8) | data[offset + 3]; + } + function readUint16(data, offset) { + return (data[offset] << 8) | data[offset + 1]; + } + function log2(x) { + var n = 1, i = 0; + while (x > n) { + n <<= 1; + i++; + } + return i; + } + function calculateComponentDimensions(component, siz) { + // Section B.2 Component mapping + component.x0 = Math.ceil(siz.XOsiz / component.XRsiz); + component.x1 = Math.ceil(siz.Xsiz / component.XRsiz); + component.y0 = Math.ceil(siz.YOsiz / component.YRsiz); + component.y1 = Math.ceil(siz.Ysiz / component.YRsiz); + component.width = component.x1 - component.x0; + component.height = component.y1 - component.y0; + } + function calculateTileGrids(context, components) { + var siz = context.SIZ; + // Section B.3 Division into tile and tile-components + var tiles = []; + var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz); + var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz); + for (var q = 0; q < numYtiles; q++) { + for (var p = 0; p < numXtiles; p++) { + var tile = {}; + tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz); + tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz); + tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz); + tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz); + tile.width = tile.tx1 - tile.tx0; + tile.height = tile.ty1 - tile.ty0; + tile.components = []; + tiles.push(tile); + } + } + context.tiles = tiles; + + var componentsCount = siz.Csiz; + for (var i = 0, ii = componentsCount; i < ii; i++) { + var component = components[i]; + var tileComponents = []; + for (var j = 0, jj = tiles.length; j < jj; j++) { + var tileComponent = {}, tile = tiles[j]; + tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz); + tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz); + tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz); + tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz); + tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0; + tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0; + tile.components[i] = tileComponent; + } + } + } + function getBlocksDimensions(context, component, r) { + var codOrCoc = component.codingStyleParameters; + var result = {}; + if (!codOrCoc.entropyCoderWithCustomPrecincts) { + result.PPx = 15; + result.PPy = 15; + } else { + result.PPx = codOrCoc.precinctsSizes[r].PPx; + result.PPy = codOrCoc.precinctsSizes[r].PPy; + } + // calculate codeblock size as described in section B.7 + result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : + Math.min(codOrCoc.xcb, result.PPx); + result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : + Math.min(codOrCoc.ycb, result.PPy); + return result; + } + function buildPrecincts(context, resolution, dimensions) { + // Section B.6 Division resolution to precincts + var precinctWidth = 1 << dimensions.PPx; + var precinctHeight = 1 << dimensions.PPy; + var numprecinctswide = resolution.trx1 > resolution.trx0 ? + Math.ceil(resolution.trx1 / precinctWidth) - + Math.floor(resolution.trx0 / precinctWidth) : 0; + var numprecinctshigh = resolution.try1 > resolution.try0 ? + Math.ceil(resolution.try1 / precinctHeight) - + Math.floor(resolution.try0 / precinctHeight) : 0; + var numprecincts = numprecinctswide * numprecinctshigh; + var precinctXOffset = Math.floor(resolution.trx0 / precinctWidth) * + precinctWidth; + var precinctYOffset = Math.floor(resolution.try0 / precinctHeight) * + precinctHeight; + resolution.precinctParameters = { + precinctXOffset: precinctXOffset, + precinctYOffset: precinctYOffset, + precinctWidth: precinctWidth, + precinctHeight: precinctHeight, + numprecinctswide: numprecinctswide, + numprecinctshigh: numprecinctshigh, + numprecincts: numprecincts + }; + } + function buildCodeblocks(context, subband, dimensions) { + // Section B.7 Division sub-band into code-blocks + var xcb_ = dimensions.xcb_; + var ycb_ = dimensions.ycb_; + var codeblockWidth = 1 << xcb_; + var codeblockHeight = 1 << ycb_; + var cbx0 = Math.floor(subband.tbx0 / codeblockWidth); + var cby0 = Math.floor(subband.tby0 / codeblockHeight); + var cbx1 = Math.ceil(subband.tbx1 / codeblockWidth); + var cby1 = Math.ceil(subband.tby1 / codeblockHeight); + var precinctParameters = subband.resolution.precinctParameters; + var codeblocks = []; + var precincts = []; + for (var j = cby0; j < cby1; j++) { + for (var i = cbx0; i < cbx1; i++) { + var codeblock = { + cbx: i, + cby: j, + tbx0: codeblockWidth * i, + tby0: codeblockHeight * j, + tbx1: codeblockWidth * (i + 1), + tby1: codeblockHeight * (j + 1) + }; + // calculate precinct number + var pi = Math.floor((codeblock.tbx0 - + precinctParameters.precinctXOffset) / + precinctParameters.precinctWidth); + var pj = Math.floor((codeblock.tby0 - + precinctParameters.precinctYOffset) / + precinctParameters.precinctHeight); + var precinctNumber = pj + + pi * precinctParameters.numprecinctswide; + codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0); + codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0); + codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1); + codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1); + codeblock.precinctNumber = precinctNumber; + codeblock.subbandType = subband.type; + var coefficientsLength = (codeblock.tbx1_ - codeblock.tbx0_) * + (codeblock.tby1_ - codeblock.tby0_); + codeblock.Lblock = 3; + codeblocks.push(codeblock); + // building precinct for the sub-band + var precinct; + if (precinctNumber in precincts) { + precinct = precincts[precinctNumber]; + precinct.cbxMin = Math.min(precinct.cbxMin, i); + precinct.cbyMin = Math.min(precinct.cbyMin, j); + precinct.cbxMax = Math.max(precinct.cbxMax, i); + precinct.cbyMax = Math.max(precinct.cbyMax, j); + } else { + precincts[precinctNumber] = precinct = { + cbxMin: i, + cbyMin: j, + cbxMax: i, + cbyMax: j + }; + } + codeblock.precinct = precinct; + } + } + subband.codeblockParameters = { + codeblockWidth: xcb_, + codeblockHeight: ycb_, + numcodeblockwide: cbx1 - cbx0 + 1, + numcodeblockhigh: cby1 - cby1 + 1 + }; + subband.codeblocks = codeblocks; + for (var i = 0, ii = codeblocks.length; i < ii; i++) { + var codeblock = codeblocks[i]; + var precinctNumber = codeblock.precinctNumber; + } + subband.precincts = precincts; + } + function createPacket(resolution, precinctNumber, layerNumber) { + var precinctCodeblocks = []; + // Section B.10.8 Order of info in packet + var subbands = resolution.subbands; + // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence + for (var i = 0, ii = subbands.length; i < ii; i++) { + var subband = subbands[i]; + var codeblocks = subband.codeblocks; + for (var j = 0, jj = codeblocks.length; j < jj; j++) { + var codeblock = codeblocks[j]; + if (codeblock.precinctNumber != precinctNumber) + continue; + precinctCodeblocks.push(codeblock); + } + } + return { + layerNumber: layerNumber, + codeblocks: precinctCodeblocks + }; + } + function LayerResolutionComponentPositionIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var maxDecompositionLevelsCount = 0; + for (var q = 0; q < componentsCount; q++) { + maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, + tile.components[q].codingStyleParameters.decompositionLevelsCount); + } + + var l = 0, r = 0, i = 0, k = 0; + + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.1 Layer-resolution-component-position + for (; l < layersCount; l++) { + for (; r <= maxDecompositionLevelsCount; r++) { + for (; i < componentsCount; i++) { + var component = tile.components[i]; + if (r > component.codingStyleParameters.decompositionLevelsCount) + continue; + + var resolution = component.resolutions[r]; + var numprecincts = resolution.precinctParameters.numprecincts; + for (; k < numprecincts;) { + var packet = createPacket(resolution, k, l); + k++; + return packet; + } + k = 0; + } + i = 0; + } + r = 0; + } + throw 'Out of packets'; + }; + } + function ResolutionLayerComponentPositionIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var maxDecompositionLevelsCount = 0; + for (var q = 0; q < componentsCount; q++) { + maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, + tile.components[q].codingStyleParameters.decompositionLevelsCount); + } + + var r = 0, l = 0, i = 0, k = 0; + + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.2 Resolution-layer-component-position + for (; r <= maxDecompositionLevelsCount; r++) { + for (; l < layersCount; l++) { + for (; i < componentsCount; i++) { + var component = tile.components[i]; + if (r > component.codingStyleParameters.decompositionLevelsCount) + continue; + + var resolution = component.resolutions[r]; + var numprecincts = resolution.precinctParameters.numprecincts; + for (; k < numprecincts;) { + var packet = createPacket(resolution, k, l); + k++; + return packet; + } + k = 0; + } + i = 0; + } + l = 0; + } + throw 'Out of packets'; + }; + } + function buildPackets(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var componentsCount = siz.Csiz; + // Creating resolutions and sub-bands for each component + for (var c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + var decompositionLevelsCount = + component.codingStyleParameters.decompositionLevelsCount; + // Section B.5 Resolution levels and sub-bands + var resolutions = []; + var subbands = []; + for (var r = 0; r <= decompositionLevelsCount; r++) { + var blocksDimensions = getBlocksDimensions(context, component, r); + var resolution = {}; + var scale = 1 << (decompositionLevelsCount - r); + resolution.trx0 = Math.ceil(component.tcx0 / scale); + resolution.try0 = Math.ceil(component.tcy0 / scale); + resolution.trx1 = Math.ceil(component.tcx1 / scale); + resolution.try1 = Math.ceil(component.tcy1 / scale); + buildPrecincts(context, resolution, blocksDimensions); + resolutions.push(resolution); + + var subband; + if (r == 0) { + // one sub-band (LL) with last decomposition + subband = {}; + subband.type = 'LL'; + subband.tbx0 = Math.ceil(component.tcx0 / scale); + subband.tby0 = Math.ceil(component.tcy0 / scale); + subband.tbx1 = Math.ceil(component.tcx1 / scale); + subband.tby1 = Math.ceil(component.tcy1 / scale); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolution.subbands = [subband]; + } else { + var bscale = 1 << (decompositionLevelsCount - r + 1); + var resolutionSubbands = []; + // three sub-bands (HL, LH and HH) with rest of decompositions + subband = {}; + subband.type = 'HL'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5); + subband.tby0 = Math.ceil(component.tcy0 / bscale); + subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5); + subband.tby1 = Math.ceil(component.tcy1 / bscale); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + subband = {}; + subband.type = 'LH'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale); + subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5); + subband.tbx1 = Math.ceil(component.tcx1 / bscale); + subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + subband = {}; + subband.type = 'HH'; + subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5); + subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5); + subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5); + subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5); + subband.resolution = resolution; + buildCodeblocks(context, subband, blocksDimensions); + subbands.push(subband); + resolutionSubbands.push(subband); + + resolution.subbands = resolutionSubbands; + } + } + component.resolutions = resolutions; + component.subbands = subbands; + } + // Generate the packets sequence + var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder; + var packetsIterator; + switch (progressionOrder) { + case 0: + tile.packetsIterator = + new LayerResolutionComponentPositionIterator(context); + break; + case 1: + tile.packetsIterator = + new ResolutionLayerComponentPositionIterator(context); + break; + default: + throw 'Unsupported progression order ' + progressionOrder; + } + } + function parseTilePackets(context, data, offset, dataLength) { + var position = 0; + var buffer, bufferSize = 0, skipNextBit = false; + function readBits(count) { + while (bufferSize < count) { + var b = data[offset + position]; + position++; + if (skipNextBit) { + buffer = (buffer << 7) | b; + bufferSize += 7; + skipNextBit = false; + } else { + buffer = (buffer << 8) | b; + bufferSize += 8; + } + if (b == 0xFF) { + skipNextBit = true; + } + } + bufferSize -= count; + return (buffer >>> bufferSize) & ((1 << count) - 1); + } + function alignToByte() { + bufferSize = 0; + if (skipNextBit) { + position++; + skipNextBit = false; + } + } + function readCodingpasses() { + var value = readBits(1); + if (value == 0) + return 1; + value = (value << 1) | readBits(1); + if (value == 0x02) + return 2; + value = (value << 2) | readBits(2); + if (value <= 0x0E) + return (value & 0x03) + 3; + value = (value << 5) | readBits(5); + if (value <= 0x1FE) + return (value & 0x1F) + 6; + value = (value << 7) | readBits(7); + return (value & 0x7F) + 37; + } + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var packetsIterator = tile.packetsIterator; + while (position < dataLength) { + var packet = packetsIterator.nextPacket(); + if (!readBits(1)) { + alignToByte(); + continue; + } + var layerNumber = packet.layerNumber; + var queue = []; + for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) { + var codeblock = packet.codeblocks[i]; + var precinct = codeblock.precinct; + var codeblockColumn = codeblock.cbx - precinct.cbxMin; + var codeblockRow = codeblock.cby - precinct.cbyMin; + var codeblockIncluded = false; + var firstTimeInclusion = false; + if ('included' in codeblock) { + codeblockIncluded = !!readBits(1); + } else { + // reading inclusion tree + var precinct = codeblock.precinct; + var inclusionTree, zeroBitPlanesTree; + if ('inclusionTree' in precinct) { + inclusionTree = precinct.inclusionTree; + } else { + // building inclusion and zero bit-planes trees + var width = precinct.cbxMax - precinct.cbxMin + 1; + var height = precinct.cbyMax - precinct.cbyMin + 1; + inclusionTree = new InclusionTree(width, height, layerNumber); + zeroBitPlanesTree = new TagTree(width, height); + precinct.inclusionTree = inclusionTree; + precinct.zeroBitPlanesTree = zeroBitPlanesTree; + } + + if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) { + while (true) { + if (readBits(1)) { + var valueReady = !inclusionTree.nextLevel(); + if (valueReady) { + codeblock.included = true; + codeblockIncluded = firstTimeInclusion = true; + break; + } + } else { + inclusionTree.incrementValue(layerNumber); + break; + } + } + } + } + if (!codeblockIncluded) + continue; + if (firstTimeInclusion) { + zeroBitPlanesTree = precinct.zeroBitPlanesTree; + zeroBitPlanesTree.reset(codeblockColumn, codeblockRow); + while (true) { + if (readBits(1)) { + var valueReady = !zeroBitPlanesTree.nextLevel(); + if (valueReady) + break; + } else + zeroBitPlanesTree.incrementValue(); + } + codeblock.zeroBitPlanes = zeroBitPlanesTree.value; + } + var codingpasses = readCodingpasses(); + while (readBits(1)) + codeblock.Lblock++; + var codingpassesLog2 = log2(codingpasses); + // rounding down log2 + var bits = ((codingpasses < (1 << codingpassesLog2)) ? + codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock; + var codedDataLength = readBits(bits); + queue.push({ + codeblock: codeblock, + codingpasses: codingpasses, + dataLength: codedDataLength + }); + } + alignToByte(); + while (queue.length > 0) { + var packetItem = queue.shift(); + var codeblock = packetItem.codeblock; + if (!('data' in codeblock)) + codeblock.data = []; + codeblock.data.push({ + data: data, + start: offset + position, + end: offset + position + packetItem.dataLength, + codingpasses: packetItem.codingpasses + }); + position += packetItem.dataLength; + } + } + return position; + } + function copyCoefficients(coefficients, x0, y0, width, height, + delta, mb, codeblocks, transformation) { + var r = 0.5; // formula (E-6) + for (var i = 0, ii = codeblocks.length; i < ii; ++i) { + var codeblock = codeblocks[i]; + var blockWidth = codeblock.tbx1_ - codeblock.tbx0_; + var blockHeight = codeblock.tby1_ - codeblock.tby0_; + if (blockWidth == 0 || blockHeight == 0) + continue; + if (!('data' in codeblock)) + continue; + + var bitModel, currentCodingpassType; + bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, + codeblock.zeroBitPlanes); + currentCodingpassType = 2; // first bit plane starts from cleanup + + // collect data + var data = codeblock.data, totalLength = 0, codingpasses = 0; + for (var q = 0, qq = data.length; q < qq; q++) { + var dataItem = data[q]; + totalLength += dataItem.end - dataItem.start; + codingpasses += dataItem.codingpasses; + } + var encodedData = new Uint8Array(totalLength), k = 0; + for (var q = 0, qq = data.length; q < qq; q++) { + var dataItem = data[q]; + var chunk = dataItem.data.subarray(dataItem.start, dataItem.end); + encodedData.set(chunk, k); + k += chunk.length; + } + // decoding the item + var decoder = new ArithmeticDecoder(encodedData, 0, totalLength); + bitModel.setDecoder(decoder); + + for (var q = 0; q < codingpasses; q++) { + switch (currentCodingpassType) { + case 0: + bitModel.runSignificancePropogationPass(); + break; + case 1: + bitModel.runMagnitudeRefinementPass(); + break; + case 2: + bitModel.runCleanupPass(); + break; + } + currentCodingpassType = (currentCodingpassType + 1) % 3; + } + + var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width; + var position = 0; + for (var j = 0; j < blockHeight; j++) { + for (var k = 0; k < blockWidth; k++) { + var n = (bitModel.coefficentsSign[position] ? -1 : 1) * + bitModel.coefficentsMagnitude[position]; + var nb = bitModel.bitsDecoded[position], correction; + if (transformation == 0 || mb > nb) { + // use r only if transformation is irreversible or + // not all bitplanes were decoded for reversible transformation + n += n < 0 ? n - r : n > 0 ? n + r : 0; + correction = 1 << (mb - nb); + } else + correction = 1; + coefficients[offset++] = n * correction * delta; + position++; + } + offset += width - blockWidth; + } + } + } + function transformTile(context, tile, c) { + var component = tile.components[c]; + var codingStyleParameters = component.codingStyleParameters; + var quantizationParameters = component.quantizationParameters; + var decompositionLevelsCount = + codingStyleParameters.decompositionLevelsCount; + var spqcds = quantizationParameters.SPqcds; + var scalarExpounded = quantizationParameters.scalarExpounded; + var guardBits = quantizationParameters.guardBits; + var transformation = codingStyleParameters.transformation; + var precision = context.components[c].precision; + + var subbandCoefficients = []; + var k = 0, b = 0; + for (var i = 0; i <= decompositionLevelsCount; i++) { + var resolution = component.resolutions[i]; + + for (var j = 0, jj = resolution.subbands.length; j < jj; j++) { + var mu, epsilon; + if (!scalarExpounded) { + // formula E-5 + mu = spqcds[0].mu; + epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0); + } else { + mu = spqcds[b].mu; + epsilon = spqcds[b].epsilon; + } + + var subband = resolution.subbands[j]; + var width = subband.tbx1 - subband.tbx0; + var height = subband.tby1 - subband.tby0; + var gainLog2 = SubbandsGainLog2[subband.type]; + + // calulate quantization coefficient (Section E.1.1.1) + var delta = Math.pow(2, (precision + gainLog2) - epsilon) * + (1 + mu / 2048); + var mb = (guardBits + epsilon - 1); + + var coefficients = new Float32Array(width * height); + copyCoefficients(coefficients, subband.tbx0, subband.tby0, + width, height, delta, mb, subband.codeblocks, transformation); + + subbandCoefficients.push({ + width: width, + height: height, + items: coefficients + }); + + b++; + } + } + + var transformation = codingStyleParameters.transformation; + var transform = transformation == 0 ? new IrreversibleTransform() : + new ReversibleTransform(); + var result = transform.calculate(subbandCoefficients, + component.tcx0, component.tcy0); + return { + left: component.tcx0, + top: component.tcy0, + width: result.width, + height: result.height, + items: result.items + }; + } + function transformComponents(context) { + var siz = context.SIZ; + var components = context.components; + var componentsCount = siz.Csiz; + var resultImages = []; + for (var i = 0, ii = context.tiles.length; i < ii; i++) { + var tile = context.tiles[i]; + var result = []; + for (var c = 0; c < componentsCount; c++) { + var image = transformTile(context, tile, c); + result.push(image); + } + + // Section G.2.2 Inverse multi component transform + if (tile.codingStyleDefaultParameters.multipleComponentTransform) { + var y0items = result[0].items; + var y1items = result[1].items; + var y2items = result[2].items; + for (var j = 0, jj = y0items.length; j < jj; j++) { + var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j]; + var i1 = y0 - ((y2 + y1) >> 2); + y1items[j] = i1; + y0items[j] = y2 + i1; + y2items[j] = y1 + i1; + } + } + + // Section G.1 DC level shifting to unsigned component values + for (var c = 0; c < componentsCount; c++) { + var component = components[c]; + if (component.isSigned) + continue; + + var offset = 1 << (component.precision - 1); + var tileImage = result[c]; + var items = tileImage.items; + for (var j = 0, jj = items.length; j < jj; j++) + items[j] += offset; + } + + // To simplify things: shift and clamp output to 8 bit unsigned + for (var c = 0; c < componentsCount; c++) { + var component = components[c]; + var offset = component.isSigned ? 128 : 0; + var shift = component.precision - 8; + var tileImage = result[c]; + var items = tileImage.items; + var data = new Uint8Array(items.length); + for (var j = 0, jj = items.length; j < jj; j++) { + var value = (items[j] >> shift) + offset; + data[j] = value < 0 ? 0 : value > 255 ? 255 : value; + } + result[c].items = data; + } + + resultImages.push(result); + } + return resultImages; + } + function initializeTile(context, tileIndex) { + var siz = context.SIZ; + var componentsCount = siz.Csiz; + var tile = context.tiles[tileIndex]; + var resultTiles = []; + for (var c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + var qcdOrQcc = c in context.currentTile.QCC ? + context.currentTile.QCC[c] : context.currentTile.QCD; + component.quantizationParameters = qcdOrQcc; + var codOrCoc = c in context.currentTile.COC ? + context.currentTile.COC[c] : context.currentTile.COD; + component.codingStyleParameters = codOrCoc; + } + tile.codingStyleDefaultParameters = context.currentTile.COD; + } + + // Section B.10.2 Tag trees + var TagTree = (function TagTreeClosure() { + function TagTree(width, height) { + var levelsLength = log2(Math.max(width, height)) + 1; + this.levels = []; + for (var i = 0; i < levelsLength; i++) { + var level = { + width: width, + height: height, + items: [] + }; + this.levels.push(level); + width = Math.ceil(width / 2); + height = Math.ceil(height / 2); + } + } + TagTree.prototype = { + reset: function TagTree_reset(i, j) { + var currentLevel = 0, value = 0; + while (currentLevel < this.levels.length) { + var level = this.levels[currentLevel]; + var index = i + j * level.width; + if (index in level.items) { + value = level.items[index]; + break; + } + level.index = index; + i >>= 1; + j >>= 1; + currentLevel++; + } + currentLevel--; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + this.currentLevel = currentLevel; + delete this.value; + }, + incrementValue: function TagTree_incrementValue() { + var level = this.levels[this.currentLevel]; + level.items[level.index]++; + }, + nextLevel: function TagTree_nextLevel() { + var currentLevel = this.currentLevel; + var level = this.levels[currentLevel]; + var value = level.items[level.index]; + currentLevel--; + if (currentLevel < 0) { + this.value = value; + return false; + } + + this.currentLevel = currentLevel; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + return true; + } + }; + return TagTree; + })(); + + var InclusionTree = (function InclusionTreeClosure() { + function InclusionTree(width, height, defaultValue) { + var levelsLength = log2(Math.max(width, height)) + 1; + this.levels = []; + for (var i = 0; i < levelsLength; i++) { + var items = new Uint8Array(width * height); + for (var j = 0, jj = items.length; j < jj; j++) + items[j] = defaultValue; + + var level = { + width: width, + height: height, + items: items + }; + this.levels.push(level); + + width = Math.ceil(width / 2); + height = Math.ceil(height / 2); + } + } + InclusionTree.prototype = { + reset: function InclusionTree_reset(i, j, stopValue) { + var currentLevel = 0; + while (currentLevel < this.levels.length) { + var level = this.levels[currentLevel]; + var index = i + j * level.width; + level.index = index; + var value = level.items[index]; + + if (value == 0xFF) + break; + + if (value > stopValue) { + this.currentLevel = currentLevel; + // already know about this one, propagating the value to top levels + this.propagateValues(); + return false; + } + + i >>= 1; + j >>= 1; + currentLevel++; + } + this.currentLevel = currentLevel - 1; + return true; + }, + incrementValue: function InclusionTree_incrementValue(stopValue) { + var level = this.levels[this.currentLevel]; + level.items[level.index] = stopValue + 1; + this.propagateValues(); + }, + propagateValues: function InclusionTree_propagateValues() { + var levelIndex = this.currentLevel; + var level = this.levels[levelIndex]; + var currentValue = level.items[level.index]; + while (--levelIndex >= 0) { + var level = this.levels[levelIndex]; + level.items[level.index] = currentValue; + } + }, + nextLevel: function InclusionTree_nextLevel() { + var currentLevel = this.currentLevel; + var level = this.levels[currentLevel]; + var value = level.items[level.index]; + level.items[level.index] = 0xFF; + currentLevel--; + if (currentLevel < 0) + return false; + + this.currentLevel = currentLevel; + var level = this.levels[currentLevel]; + level.items[level.index] = value; + return true; + } + }; + return InclusionTree; + })(); + + // Implements C.3. Arithmetic decoding procedures + var ArithmeticDecoder = (function ArithmeticDecoderClosure() { + var QeTable = [ + {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1}, + {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0}, + {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0}, + {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0}, + {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0}, + {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0}, + {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1}, + {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0}, + {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0}, + {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0}, + {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0}, + {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0}, + {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0}, + {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0}, + {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1}, + {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0}, + {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0}, + {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0}, + {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0}, + {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0}, + {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0}, + {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0}, + {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0}, + {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0}, + {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0}, + {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0}, + {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0}, + {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0}, + {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0}, + {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0}, + {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0}, + {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0}, + {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0}, + {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0}, + {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0}, + {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0}, + {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0}, + {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0}, + {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0}, + {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0}, + {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0}, + {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0}, + {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0}, + {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0}, + {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0}, + {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0}, + {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0} + ]; + + function ArithmeticDecoder(data, start, end) { + this.data = data; + this.bp = start; + this.dataEnd = end; + + this.chigh = data[start]; + this.clow = 0; + + this.byteIn(); + + this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F); + this.clow = (this.clow << 7) & 0xFFFF; + this.ct -= 7; + this.a = 0x8000; + } + + ArithmeticDecoder.prototype = { + byteIn: function ArithmeticDecoder_byteIn() { + var data = this.data; + var bp = this.bp; + if (data[bp] == 0xFF) { + var b1 = data[bp + 1]; + if (b1 > 0x8F) { + this.clow += 0xFF00; + this.ct = 8; + } else { + bp++; + this.clow += (data[bp] << 9); + this.ct = 7; + this.bp = bp; + } + } else { + bp++; + this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00; + this.ct = 8; + this.bp = bp; + } + if (this.clow > 0xFFFF) { + this.chigh += (this.clow >> 16); + this.clow &= 0xFFFF; + } + }, + readBit: function ArithmeticDecoder_readBit(cx) { + var qeIcx = QeTable[cx.index].qe; + this.a -= qeIcx; + + if (this.chigh < qeIcx) { + var d = this.exchangeLps(cx); + this.renormD(); + return d; + } else { + this.chigh -= qeIcx; + if ((this.a & 0x8000) == 0) { + var d = this.exchangeMps(cx); + this.renormD(); + return d; + } else { + return cx.mps; + } + } + }, + renormD: function ArithmeticDecoder_renormD() { + do { + if (this.ct == 0) + this.byteIn(); + + this.a <<= 1; + this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1); + this.clow = (this.clow << 1) & 0xFFFF; + this.ct--; + } while ((this.a & 0x8000) == 0); + }, + exchangeMps: function ArithmeticDecoder_exchangeMps(cx) { + var d; + var qeTableIcx = QeTable[cx.index]; + if (this.a < qeTableIcx.qe) { + d = 1 - cx.mps; + + if (qeTableIcx.switchFlag == 1) { + cx.mps = 1 - cx.mps; + } + cx.index = qeTableIcx.nlps; + } else { + d = cx.mps; + cx.index = qeTableIcx.nmps; + } + return d; + }, + exchangeLps: function ArithmeticDecoder_exchangeLps(cx) { + var d; + var qeTableIcx = QeTable[cx.index]; + if (this.a < qeTableIcx.qe) { + this.a = qeTableIcx.qe; + d = cx.mps; + cx.index = qeTableIcx.nmps; + } else { + this.a = qeTableIcx.qe; + d = 1 - cx.mps; + + if (qeTableIcx.switchFlag == 1) { + cx.mps = 1 - cx.mps; + } + cx.index = qeTableIcx.nlps; + } + return d; + } + }; + + return ArithmeticDecoder; + })(); + + // Section D. Coefficient bit modeling + var BitModel = (function BitModelClosure() { + // Table D-1 + // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4), + // vv - sum of Vi (0..2), and hh - sum of Hi (0..2) + var LLAndLHContextsLabel = new Uint8Array([ + 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4, + 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, + 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8 + ]); + var HLContextLabel = new Uint8Array([ + 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8, + 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, + 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8 + ]); + var HHContextLabel = new Uint8Array([ + 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5, + 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8, + 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8 + ]); + + // Table D-2 + function calcSignContribution(significance0, sign0, significance1, sign1) { + if (significance1) { + if (!sign1) + return significance0 ? (!sign0 ? 1 : 0) : 1; + else + return significance0 ? (!sign0 ? 0 : -1) : -1; + } else + return significance0 ? (!sign0 ? 1 : -1) : 0; + } + // Table D-3 + var SignContextLabels = [ + {contextLabel: 13, xorBit: 0}, + {contextLabel: 12, xorBit: 0}, + {contextLabel: 11, xorBit: 0}, + {contextLabel: 10, xorBit: 0}, + {contextLabel: 9, xorBit: 0}, + {contextLabel: 10, xorBit: 1}, + {contextLabel: 11, xorBit: 1}, + {contextLabel: 12, xorBit: 1}, + {contextLabel: 13, xorBit: 1} + ]; + + function BitModel(width, height, subband, zeroBitPlanes) { + this.width = width; + this.height = height; + + this.contextLabelTable = subband == 'HH' ? HHContextLabel : + subband == 'HL' ? HLContextLabel : LLAndLHContextsLabel; + + var coefficientCount = width * height; + + // coefficients outside the encoding region treated as insignificant + // add border state cells for significanceState + this.neighborsSignificance = new Uint8Array(coefficientCount); + this.coefficentsSign = new Uint8Array(coefficientCount); + this.coefficentsMagnitude = new Uint32Array(coefficientCount); + this.processingFlags = new Uint8Array(coefficientCount); + + var bitsDecoded = new Uint8Array(this.width * this.height); + for (var i = 0, ii = bitsDecoded.length; i < ii; i++) + bitsDecoded[i] = zeroBitPlanes; + this.bitsDecoded = bitsDecoded; + + this.reset(); + } + + BitModel.prototype = { + setDecoder: function BitModel_setDecoder(decoder) { + this.decoder = decoder; + }, + reset: function BitModel_reset() { + this.uniformContext = {index: 46, mps: 0}; + this.runLengthContext = {index: 3, mps: 0}; + this.contexts = []; + this.contexts.push({index: 4, mps: 0}); + for (var i = 1; i <= 16; i++) + this.contexts.push({index: 0, mps: 0}); + }, + setNeighborsSignificance: + function BitModel_setNeighborsSignificance(row, column) { + var neighborsSignificance = this.neighborsSignificance; + var width = this.width, height = this.height; + var index = row * width + column; + if (row > 0) { + if (column > 0) + neighborsSignificance[index - width - 1] += 0x10; + if (column + 1 < width) + neighborsSignificance[index - width + 1] += 0x10; + neighborsSignificance[index - width] += 0x04; + } + if (row + 1 < height) { + if (column > 0) + neighborsSignificance[index + width - 1] += 0x10; + if (column + 1 < width) + neighborsSignificance[index + width + 1] += 0x10; + neighborsSignificance[index + width] += 0x04; + } + if (column > 0) + neighborsSignificance[index - 1] += 0x01; + if (column + 1 < width) + neighborsSignificance[index + 1] += 0x01; + neighborsSignificance[index] |= 0x80; + }, + runSignificancePropogationPass: + function BitModel_runSignificancePropogationPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var contextLabels = this.contextLabels; + var neighborsSignificance = this.neighborsSignificance; + var processingFlags = this.processingFlags; + var contexts = this.contexts; + var labels = this.contextLabelTable; + var bitsDecoded = this.bitsDecoded; + // clear processed flag + var processedInverseMask = ~1; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + for (var q = 0, qq = width * height; q < qq; q++) + processingFlags[q] &= processedInverseMask; + + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + var index = i0 * width + j; + for (var i1 = 0; i1 < 4; i1++, index += width) { + var i = i0 + i1; + if (i >= height) + break; + + if (coefficentsMagnitude[index] || !neighborsSignificance[index]) + continue; + + var contextLabel = labels[neighborsSignificance[index]]; + var cx = contexts[contextLabel]; + var decision = decoder.readBit(cx); + if (decision) { + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + } + bitsDecoded[index]++; + processingFlags[index] |= processedMask; + } + } + } + }, + decodeSignBit: function BitModel_decodeSignBit(row, column) { + var width = this.width, height = this.height; + var index = row * width + column; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var horizontalContribution = calcSignContribution( + column > 0 && coefficentsMagnitude[index - 1], + coefficentsSign[index - 1], + column + 1 < width && coefficentsMagnitude[index + 1], + coefficentsSign[index + 1]); + var verticalContribution = calcSignContribution( + row > 0 && coefficentsMagnitude[index - width], + coefficentsSign[index - width], + row + 1 < height && coefficentsMagnitude[index + width], + coefficentsSign[index + width]); + + var contextLabelAndXor = SignContextLabels[ + 3 * (1 - horizontalContribution) + (1 - verticalContribution)]; + var contextLabel = contextLabelAndXor.contextLabel; + var cx = this.contexts[contextLabel]; + var decoded = this.decoder.readBit(cx); + return decoded ^ contextLabelAndXor.xorBit; + }, + runMagnitudeRefinementPass: + function BitModel_runMagnitudeRefinementPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var coefficentsMagnitude = this.coefficentsMagnitude; + var neighborsSignificance = this.neighborsSignificance; + var contexts = this.contexts; + var bitsDecoded = this.bitsDecoded; + var processingFlags = this.processingFlags; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + for (var i1 = 0; i1 < 4; i1++) { + var i = i0 + i1; + if (i >= height) + break; + var index = i * width + j; + + // significant but not those that have just become + if (!coefficentsMagnitude[index] || + (processingFlags[index] & processedMask) != 0) + continue; + + var contextLabel = 16; + if ((processingFlags[index] & + firstMagnitudeBitMask) != 0) { + processingFlags[i * width + j] ^= firstMagnitudeBitMask; + // first refinement + var significance = neighborsSignificance[index]; + var sumOfSignificance = (significance & 3) + + ((significance >> 2) & 3) + ((significance >> 4) & 7); + contextLabel = sumOfSignificance >= 1 ? 15 : 14; + } + + var cx = contexts[contextLabel]; + var bit = decoder.readBit(cx); + coefficentsMagnitude[index] = + (coefficentsMagnitude[index] << 1) | bit; + bitsDecoded[index]++; + processingFlags[index] |= processedMask; + } + } + } + }, + runCleanupPass: function BitModel_runCleanupPass() { + var decoder = this.decoder; + var width = this.width, height = this.height; + var neighborsSignificance = this.neighborsSignificance; + var significanceState = this.significanceState; + var coefficentsMagnitude = this.coefficentsMagnitude; + var coefficentsSign = this.coefficentsSign; + var contexts = this.contexts; + var labels = this.contextLabelTable; + var bitsDecoded = this.bitsDecoded; + var processingFlags = this.processingFlags; + var processedMask = 1; + var firstMagnitudeBitMask = 2; + var oneRowDown = width; + var twoRowsDown = width * 2; + var threeRowsDown = width * 3; + for (var i0 = 0; i0 < height; i0 += 4) { + for (var j = 0; j < width; j++) { + var index0 = i0 * width + j; + // using the property: labels[neighborsSignificance[index]] == 0 + // when neighborsSignificance[index] == 0 + var allEmpty = i0 + 3 < height && + processingFlags[index0] == 0 && + processingFlags[index0 + oneRowDown] == 0 && + processingFlags[index0 + twoRowsDown] == 0 && + processingFlags[index0 + threeRowsDown] == 0 && + neighborsSignificance[index0] == 0 && + neighborsSignificance[index0 + oneRowDown] == 0 && + neighborsSignificance[index0 + twoRowsDown] == 0 && + neighborsSignificance[index0 + threeRowsDown] == 0; + var i1 = 0, index = index0; + var cx, i; + if (allEmpty) { + cx = this.runLengthContext; + var hasSignificantCoefficent = decoder.readBit(cx); + if (!hasSignificantCoefficent) { + bitsDecoded[index0]++; + bitsDecoded[index0 + oneRowDown]++; + bitsDecoded[index0 + twoRowsDown]++; + bitsDecoded[index0 + threeRowsDown]++; + continue; // next column + } + cx = this.uniformContext; + i1 = (decoder.readBit(cx) << 1) | decoder.readBit(cx); + i = i0 + i1; + index += i1 * width; + + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + + index = index0; + for (var i2 = i0; i2 <= i; i2++, index += width) + bitsDecoded[index]++; + + i1++; + } + for (; i1 < 4; i1++, index += width) { + i = i0 + i1; + if (i >= height) + break; + + if (coefficentsMagnitude[index] || + (processingFlags[index] & processedMask) != 0) + continue; + + var contextLabel = labels[neighborsSignificance[index]]; + cx = contexts[contextLabel]; + var decision = decoder.readBit(cx); + if (decision == 1) { + var sign = this.decodeSignBit(i, j); + coefficentsSign[index] = sign; + coefficentsMagnitude[index] = 1; + this.setNeighborsSignificance(i, j); + processingFlags[index] |= firstMagnitudeBitMask; + } + bitsDecoded[index]++; + } + } + } + } + }; + + return BitModel; + })(); + + // Section F, Discrete wavelet transofrmation + var Transform = (function TransformClosure() { + function Transform() { + } + Transform.prototype.calculate = + function transformCalculate(subbands, u0, v0) { + var ll = subbands[0]; + for (var i = 1, ii = subbands.length, j = 1; i < ii; i += 3, j++) { + ll = this.iterate(ll, subbands[i], subbands[i + 1], + subbands[i + 2], u0, v0); + } + return ll; + }; + Transform.prototype.iterate = function Transform_iterate(ll, hl, lh, hh, + u0, v0) { + var llWidth = ll.width, llHeight = ll.height, llItems = ll.items; + var hlWidth = hl.width, hlHeight = hl.height, hlItems = hl.items; + var lhWidth = lh.width, lhHeight = lh.height, lhItems = lh.items; + var hhWidth = hh.width, hhHeight = hh.height, hhItems = hh.items; + + // Section F.3.3 interleave + var width = llWidth + hlWidth; + var height = llHeight + lhHeight; + var items = new Float32Array(width * height); + for (var i = 0, ii = llHeight; i < ii; i++) { + var k = i * llWidth, l = i * 2 * width; + for (var j = 0, jj = llWidth; j < jj; j++, k++, l += 2) + items[l] = llItems[k]; + } + for (var i = 0, ii = hlHeight; i < ii; i++) { + var k = i * hlWidth, l = i * 2 * width + 1; + for (var j = 0, jj = hlWidth; j < jj; j++, k++, l += 2) + items[l] = hlItems[k]; + } + for (var i = 0, ii = lhHeight; i < ii; i++) { + var k = i * lhWidth, l = (i * 2 + 1) * width; + for (var j = 0, jj = lhWidth; j < jj; j++, k++, l += 2) + items[l] = lhItems[k]; + } + for (var i = 0, ii = hhHeight; i < ii; i++) { + var k = i * hhWidth, l = (i * 2 + 1) * width + 1; + for (var j = 0, jj = hhWidth; j < jj; j++, k++, l += 2) + items[l] = hhItems[k]; + } + + var bufferPadding = 4; + var bufferLength = new Float32Array(Math.max(width, height) + + 2 * bufferPadding); + var buffer = new Float32Array(bufferLength); + var bufferOut = new Float32Array(bufferLength); + + // Section F.3.4 HOR_SR + for (var v = 0; v < height; v++) { + if (width == 1) { + // if width = 1, when u0 even keep items as is, when odd divide by 2 + if ((u0 % 1) != 0) { + items[v * width] /= 2; + } + continue; + } + + var k = v * width; + var l = bufferPadding; + for (var u = 0; u < width; u++, k++, l++) + buffer[l] = items[k]; + + // Section F.3.7 extending... using max extension of 4 + var i1 = bufferPadding - 1, j1 = bufferPadding + 1; + var i2 = bufferPadding + width - 2, j2 = bufferPadding + width; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + + this.filter(buffer, bufferPadding, width, u0, bufferOut); + + k = v * width; + l = bufferPadding; + for (var u = 0; u < width; u++, k++, l++) + items[k] = bufferOut[l]; + } + + // Section F.3.5 VER_SR + for (var u = 0; u < width; u++) { + if (height == 1) { + // if height = 1, when v0 even keep items as is, when odd divide by 2 + if ((v0 % 1) != 0) { + items[u] /= 2; + } + continue; + } + + var k = u; + var l = bufferPadding; + for (var v = 0; v < height; v++, k += width, l++) + buffer[l] = items[k]; + + // Section F.3.7 extending... using max extension of 4 + var i1 = bufferPadding - 1, j1 = bufferPadding + 1; + var i2 = bufferPadding + height - 2, j2 = bufferPadding + height; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + buffer[i1--] = buffer[j1++]; + buffer[j2++] = buffer[i2--]; + + this.filter(buffer, bufferPadding, height, v0, bufferOut); + + k = u; + l = bufferPadding; + for (var v = 0; v < height; v++, k += width, l++) + items[k] = bufferOut[l]; + } + return { + width: width, + height: height, + items: items + }; + }; + return Transform; + })(); + + // Section 3.8.2 Irreversible 9-7 filter + var IrreversibleTransform = (function IrreversibleTransformClosure() { + function IrreversibleTransform() { + Transform.call(this); + } + + IrreversibleTransform.prototype = Object.create(Transform.prototype); + IrreversibleTransform.prototype.filter = + function irreversibleTransformFilter(y, offset, length, i0, x) { + var i0_ = Math.floor(i0 / 2); + var i1_ = Math.floor((i0 + length) / 2); + var offset_ = offset - (i0 % 1); + + var alpha = -1.586134342059924; + var beta = -0.052980118572961; + var gamma = 0.882911075530934; + var delta = 0.443506852043971; + var K = 1.230174104914001; + var K_ = 1 / K; + + // step 1 + var j = offset_ - 2; + for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] = K * y[j]; + + // step 2 + var j = offset_ - 3; + for (var n = i0_ - 2, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] = K_ * y[j]; + + // step 3 + var j = offset_ - 2; + for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2) + x[j] -= delta * (x[j - 1] + x[j + 1]); + + // step 4 + var j = offset_ - 1; + for (var n = i0_ - 1, nn = i1_ + 1; n < nn; n++, j += 2) + x[j] -= gamma * (x[j - 1] + x[j + 1]); + + // step 5 + var j = offset_; + for (var n = i0_, nn = i1_ + 1; n < nn; n++, j += 2) + x[j] -= beta * (x[j - 1] + x[j + 1]); + + // step 6 + var j = offset_ + 1; + for (var n = i0_, nn = i1_; n < nn; n++, j += 2) + x[j] -= alpha * (x[j - 1] + x[j + 1]); + }; + + return IrreversibleTransform; + })(); + + // Section 3.8.1 Reversible 5-3 filter + var ReversibleTransform = (function ReversibleTransformClosure() { + function ReversibleTransform() { + Transform.call(this); + } + + ReversibleTransform.prototype = Object.create(Transform.prototype); + ReversibleTransform.prototype.filter = + function reversibleTransformFilter(y, offset, length, i0, x) { + var i0_ = Math.floor(i0 / 2); + var i1_ = Math.floor((i0 + length) / 2); + var offset_ = offset - (i0 % 1); + + for (var n = i0_, nn = i1_ + 1, j = offset_; n < nn; n++, j += 2) + x[j] = y[j] - Math.floor((y[j - 1] + y[j + 1] + 2) / 4); + + for (var n = i0_, nn = i1_, j = offset_ + 1; n < nn; n++, j += 2) + x[j] = y[j] + Math.floor((x[j - 1] + x[j + 1]) / 2); + }; + + return ReversibleTransform; + })(); + + return JpxImage; +})(); + diff --git a/apps/files_pdfviewer/js/pdfjs/src/metadata.js b/apps/files_pdfviewer/js/pdfjs/src/metadata.js new file mode 100644 index 00000000000..f3805616866 --- /dev/null +++ b/apps/files_pdfviewer/js/pdfjs/src/metadata.js @@ -0,0 +1,66 @@ +/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ + +'use strict'; + +var Metadata = PDFJS.Metadata = (function MetadataClosure() { + function Metadata(meta) { + if (typeof meta === 'string') { + var parser = new DOMParser(); + meta = parser.parseFromString(meta, 'application/xml'); + } else if (!(meta instanceof Document)) { + error('Metadata: Invalid metadata object'); + } + + this.metaDocument = meta; + this.metadata = {}; + this.parse(); + } + + Metadata.prototype = { + parse: function Metadata_parse() { + var doc = this.metaDocument; + var rdf = doc.documentElement; + + if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in + rdf = rdf.firstChild; + while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') + rdf = rdf.nextSibling; + } + + var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; + if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) + return; + + var childNodes = rdf.childNodes, desc, namespace, entries, entry; + + for (var i = 0, length = childNodes.length; i < length; i++) { + desc = childNodes[i]; + if (desc.nodeName.toLowerCase() !== 'rdf:description') + continue; + + entries = []; + for (var ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { + if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') + entries.push(desc.childNodes[ii]); + } + + for (ii = 0, iLength = entries.length; ii < iLength; ii++) { + var entry = entries[ii]; + var name = entry.nodeName.toLowerCase(); + this.metadata[name] = entry.textContent.trim(); + } + } + }, + + get: function Metadata_get(name) { + return this.metadata[name] || null; + }, + + has: function Metadata_has(name) { + return typeof this.metadata[name] !== 'undefined'; + } + }; + + return Metadata; +})(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/metrics.js b/apps/files_pdfviewer/js/pdfjs/src/metrics.js old mode 100755 new mode 100644 index c21b4aed1ce..e64961aa78a --- a/apps/files_pdfviewer/js/pdfjs/src/metrics.js +++ b/apps/files_pdfviewer/js/pdfjs/src/metrics.js @@ -3,6 +3,9 @@ 'use strict'; +// The Metrics object contains glyph widths (in glyph space units). +// As per PDF spec, for most fonts (Type 3 being an exception) a glyph +// space unit corresponds to 1/1000th of text space unit. var Metrics = { 'Courier': 600, 'Courier-Bold': 600, diff --git a/apps/files_pdfviewer/js/pdfjs/src/obj.js b/apps/files_pdfviewer/js/pdfjs/src/obj.js old mode 100755 new mode 100644 index 7aebb732ad2..200b40a7f98 --- a/apps/files_pdfviewer/js/pdfjs/src/obj.js +++ b/apps/files_pdfviewer/js/pdfjs/src/obj.js @@ -3,121 +3,157 @@ 'use strict'; -var Name = (function nameName() { - function constructor(name) { +var Name = (function NameClosure() { + function Name(name) { this.name = name; } - constructor.prototype = { - }; + Name.prototype = {}; - return constructor; + return Name; })(); -var Cmd = (function cmdCmd() { - function constructor(cmd) { +var Cmd = (function CmdClosure() { + function Cmd(cmd) { this.cmd = cmd; } - constructor.prototype = { + Cmd.prototype = {}; + + var cmdCache = {}; + + Cmd.get = function Cmd_get(cmd) { + var cmdValue = cmdCache[cmd]; + if (cmdValue) + return cmdValue; + + return cmdCache[cmd] = new Cmd(cmd); }; - return constructor; + return Cmd; })(); -var Dict = (function dictDict() { - function constructor() { +var Dict = (function DictClosure() { + // xref is optional + function Dict(xref) { + // Map should only be used internally, use functions below to access. this.map = Object.create(null); + this.xref = xref; } - constructor.prototype = { - get: function dictGet(key1, key2, key3) { + Dict.prototype = { + // automatically dereferences Ref objects + get: function Dict_get(key1, key2, key3) { var value; + var xref = this.xref; if (typeof (value = this.map[key1]) != 'undefined' || key1 in this.map || typeof key2 == 'undefined') { - return value; + return xref ? this.xref.fetchIfRef(value) : value; } if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map || typeof key3 == 'undefined') { - return value; + return xref ? this.xref.fetchIfRef(value) : value; } - - return this.map[key3] || null; + value = this.map[key3] || null; + return xref ? this.xref.fetchIfRef(value) : value; + }, + // no dereferencing + getRaw: function Dict_getRaw(key) { + return this.map[key]; + }, + // creates new map and dereferences all Refs + getAll: function Dict_getAll() { + var all = {}; + for (var key in this.map) + all[key] = this.get(key); + return all; }, - set: function dictSet(key, value) { + set: function Dict_set(key, value) { this.map[key] = value; }, - has: function dictHas(key) { + has: function Dict_has(key) { return key in this.map; }, - forEach: function dictForEach(callback) { + forEach: function Dict_forEach(callback) { for (var key in this.map) { - callback(key, this.map[key]); + callback(key, this.get(key)); } } }; - return constructor; + return Dict; })(); -var Ref = (function refRef() { - function constructor(num, gen) { +var Ref = (function RefClosure() { + function Ref(num, gen) { this.num = num; this.gen = gen; } - constructor.prototype = { - }; + Ref.prototype = {}; - return constructor; + return Ref; })(); // The reference is identified by number and generation, // this structure stores only one instance of the reference. -var RefSet = (function refSet() { - function constructor() { +var RefSet = (function RefSetClosure() { + function RefSet() { this.dict = {}; } - constructor.prototype = { - has: function refSetHas(ref) { + RefSet.prototype = { + has: function RefSet_has(ref) { return !!this.dict['R' + ref.num + '.' + ref.gen]; }, - put: function refSetPut(ref) { + put: function RefSet_put(ref) { this.dict['R' + ref.num + '.' + ref.gen] = ref; } }; - return constructor; + return RefSet; })(); -var Catalog = (function catalogCatalog() { - function constructor(xref) { +var Catalog = (function CatalogClosure() { + function Catalog(xref) { this.xref = xref; var obj = xref.getCatalogObj(); assertWellFormed(isDict(obj), 'catalog object is not a dictionary'); this.catDict = obj; } - constructor.prototype = { + Catalog.prototype = { + get metadata() { + var stream = this.catDict.get('Metadata'); + var metadata; + if (stream && isDict(stream.dict)) { + var type = stream.dict.get('Type'); + var subtype = stream.dict.get('Subtype'); + + if (isName(type) && isName(subtype) && + type.name === 'Metadata' && subtype.name === 'XML') { + metadata = stringToPDFString(bytesToString(stream.getBytes())); + } + } + + return shadow(this, 'metadata', metadata); + }, get toplevelPagesDict() { var pagesObj = this.catDict.get('Pages'); - assertWellFormed(isRef(pagesObj), 'invalid top-level pages reference'); - var xrefObj = this.xref.fetch(pagesObj); - assertWellFormed(isDict(xrefObj), 'invalid top-level pages dictionary'); + assertWellFormed(isDict(pagesObj), 'invalid top-level pages dictionary'); // shadow the prototype getter - return shadow(this, 'toplevelPagesDict', xrefObj); + return shadow(this, 'toplevelPagesDict', pagesObj); }, get documentOutline() { - var obj = this.catDict.get('Outlines'); var xref = this.xref; + var obj = this.catDict.get('Outlines'); var root = { items: [] }; - if (isRef(obj)) { - obj = xref.fetch(obj).get('First'); + if (isDict(obj)) { + obj = obj.getRaw('First'); var processed = new RefSet(); if (isRef(obj)) { var queue = [{obj: obj, parent: root}]; @@ -126,18 +162,20 @@ var Catalog = (function catalogCatalog() { processed.put(obj); while (queue.length > 0) { var i = queue.shift(); - var outlineDict = xref.fetch(i.obj); + var outlineDict = xref.fetchIfRef(i.obj); + if (outlineDict === null) + continue; if (!outlineDict.has('Title')) error('Invalid outline item'); var dest = outlineDict.get('A'); if (dest) - dest = xref.fetchIfRef(dest).get('D'); + dest = dest.get('D'); else if (outlineDict.has('Dest')) { - dest = outlineDict.get('Dest'); + dest = outlineDict.getRaw('Dest'); if (isName(dest)) dest = dest.name; } - var title = xref.fetchIfRef(outlineDict.get('Title')); + var title = outlineDict.get('Title'); var outlineItem = { dest: dest, title: stringToPDFString(title), @@ -148,12 +186,12 @@ var Catalog = (function catalogCatalog() { items: [] }; i.parent.items.push(outlineItem); - obj = outlineDict.get('First'); + obj = outlineDict.getRaw('First'); if (isRef(obj) && !processed.has(obj)) { queue.push({obj: obj, parent: outlineItem}); processed.put(obj); } - obj = outlineDict.get('Next'); + obj = outlineDict.getRaw('Next'); if (isRef(obj) && !processed.has(obj)) { queue.push({obj: obj, parent: i.parent}); processed.put(obj); @@ -173,7 +211,7 @@ var Catalog = (function catalogCatalog() { // shadow the prototype getter return shadow(this, 'num', obj); }, - traverseKids: function catalogTraverseKids(pagesDict) { + traverseKids: function Catalog_traverseKids(pagesDict) { var pageCache = this.pageCache; var kids = pagesDict.get('Kids'); assertWellFormed(isArray(kids), @@ -181,7 +219,7 @@ var Catalog = (function catalogCatalog() { for (var i = 0, ii = kids.length; i < ii; ++i) { var kid = kids[i]; assertWellFormed(isRef(kid), - 'page dictionary kid is not a reference'); + 'page dictionary kid is not a reference'); var obj = this.xref.fetch(kid); if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) { pageCache.push(new Page(this.xref, pageCache.length, obj, kid)); @@ -195,8 +233,7 @@ var Catalog = (function catalogCatalog() { } }, get destinations() { - function fetchDestination(xref, ref) { - var dest = xref.fetchIfRef(ref); + function fetchDestination(dest) { return isDict(dest) ? dest.get('D') : dest; } @@ -204,16 +241,16 @@ var Catalog = (function catalogCatalog() { var dests = {}, nameTreeRef, nameDictionaryRef; var obj = this.catDict.get('Names'); if (obj) - nameTreeRef = xref.fetchIfRef(obj).get('Dests'); + nameTreeRef = obj.getRaw('Dests'); else if (this.catDict.has('Dests')) nameDictionaryRef = this.catDict.get('Dests'); if (nameDictionaryRef) { // reading simple destination dictionary - obj = xref.fetchIfRef(nameDictionaryRef); + obj = nameDictionaryRef; obj.forEach(function catalogForEach(key, value) { if (!value) return; - dests[key] = fetchDestination(xref, value); + dests[key] = fetchDestination(value); }); } if (nameTreeRef) { @@ -237,13 +274,13 @@ var Catalog = (function catalogCatalog() { } var names = obj.get('Names'); for (i = 0, n = names.length; i < n; i += 2) { - dests[names[i]] = fetchDestination(xref, names[i + 1]); + dests[names[i]] = fetchDestination(xref.fetchIfRef(names[i + 1])); } } } return shadow(this, 'destinations', dests); }, - getPage: function catalogGetPage(n) { + getPage: function Catalog_getPage(n) { var pageCache = this.pageCache; if (!pageCache) { pageCache = this.pageCache = []; @@ -253,105 +290,101 @@ var Catalog = (function catalogCatalog() { } }; - return constructor; + return Catalog; })(); -var XRef = (function xRefXRef() { - function constructor(stream, startXRef, mainXRefEntriesOffset) { +var XRef = (function XRefClosure() { + function XRef(stream, startXRef, mainXRefEntriesOffset) { this.stream = stream; this.entries = []; this.xrefstms = {}; var trailerDict = this.readXRef(startXRef); - + trailerDict.xref = this; + this.trailer = trailerDict; // prepare the XRef cache this.cache = []; var encrypt = trailerDict.get('Encrypt'); if (encrypt) { var fileId = trailerDict.get('ID'); - this.encrypt = new CipherTransformFactory(this.fetch(encrypt), + this.encrypt = new CipherTransformFactory(encrypt, fileId[0] /*, password */); } // get the root dictionary (catalog) object - if (!isRef(this.root = trailerDict.get('Root'))) + if (!(this.root = trailerDict.get('Root'))) error('Invalid root reference'); } - constructor.prototype = { - readXRefTable: function readXRefTable(parser) { + XRef.prototype = { + readXRefTable: function XRef_readXRefTable(parser) { + // Example of cross-reference table: + // xref + // 0 1 <-- subsection header (first obj #, obj count) + // 0000000000 65535 f <-- actual object (offset, generation #, f/n) + // 23 2 <-- subsection header ... and so on ... + // 0000025518 00002 n + // 0000025635 00000 n + // trailer + // ... + + // Outer loop is over subsection headers var obj; - while (true) { - if (isCmd(obj = parser.getObj(), 'trailer')) - break; - if (!isInt(obj)) - error('Invalid XRef table'); - var first = obj; - if (!isInt(obj = parser.getObj())) - error('Invalid XRef table'); - var n = obj; - if (first < 0 || n < 0 || (first + n) != ((first + n) | 0)) - error('Invalid XRef table: ' + first + ', ' + n); - for (var i = first; i < first + n; ++i) { + while (!isCmd(obj = parser.getObj(), 'trailer')) { + var first = obj, + count = parser.getObj(); + + if (!isInt(first) || !isInt(count)) + error('Invalid XRef table: wrong types in subsection header'); + + // Inner loop is over objects themselves + for (var i = 0; i < count; i++) { var entry = {}; - if (!isInt(obj = parser.getObj())) - error('Invalid XRef table: ' + first + ', ' + n); - entry.offset = obj; - if (!isInt(obj = parser.getObj())) - error('Invalid XRef table: ' + first + ', ' + n); - entry.gen = obj; - obj = parser.getObj(); - if (isCmd(obj, 'n')) { - entry.uncompressed = true; - } else if (isCmd(obj, 'f')) { + entry.offset = parser.getObj(); + entry.gen = parser.getObj(); + var type = parser.getObj(); + + if (isCmd(type, 'f')) entry.free = true; - } else { - error('Invalid XRef table: ' + first + ', ' + n); - } - if (!this.entries[i]) { - // In some buggy PDF files the xref table claims to start at 1 - // instead of 0. - if (i == 1 && first == 1 && - entry.offset == 0 && entry.gen == 65535 && entry.free) { - i = first = 0; - } - this.entries[i] = entry; - } - } - } + else if (isCmd(type, 'n')) + entry.uncompressed = true; - // read the trailer dictionary - var dict; - if (!isDict(dict = parser.getObj())) - error('Invalid XRef table'); - - // get the 'Prev' pointer - var prev; - obj = dict.get('Prev'); - if (isInt(obj)) { - prev = obj; - } else if (isRef(obj)) { - // certain buggy PDF generators generate "/Prev NNN 0 R" instead - // of "/Prev NNN" - prev = obj.num; - } - if (prev) { - this.readXRef(prev); - } + // Validate entry obj + if (!isInt(entry.offset) || !isInt(entry.gen) || + !(entry.free || entry.uncompressed)) { + error('Invalid entry in XRef subsection: ' + first + ', ' + count); + } - // check for 'XRefStm' key - if (isInt(obj = dict.get('XRefStm'))) { - var pos = obj; - // ignore previously loaded xref streams (possible infinite recursion) - if (!(pos in this.xrefstms)) { - this.xrefstms[pos] = 1; - this.readXRef(pos); + if (!this.entries[i + first]) + this.entries[i + first] = entry; } } + // Sanity check: as per spec, first object must have these properties + if (this.entries[0] && + !(this.entries[0].gen === 65535 && this.entries[0].free)) + error('Invalid XRef table: unexpected first object'); + + // Sanity check + if (!isCmd(obj, 'trailer')) + error('Invalid XRef table: could not find trailer dictionary'); + + // Read trailer dictionary, e.g. + // trailer + // << /Size 22 + // /Root 20R + // /Info 10R + // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ] + // >> + // The parser goes through the entire stream << ... >> and provides + // a getter interface for the key-value table + var dict = parser.getObj(); + if (!isDict(dict)) + error('Invalid XRef table: could not parse trailer dictionary'); + return dict; }, - readXRefStream: function readXRefStream(stream) { + readXRefStream: function XRef_readXRefStream(stream) { var streamParameters = stream.parameters; var byteWidths = streamParameters.get('W'); var range = streamParameters.get('Index'); @@ -400,12 +433,9 @@ var XRef = (function xRefXRef() { } range.splice(0, 2); } - var prev = streamParameters.get('Prev'); - if (isInt(prev)) - this.readXRef(prev); return streamParameters; }, - indexObjects: function indexObjects() { + indexObjects: function XRef_indexObjects() { // Simple scan through the PDF content to find objects, // trailers and XRef streams. function readToken(data, offset) { @@ -497,7 +527,7 @@ var XRef = (function xRefXRef() { var dict; for (var i = 0, ii = trailers.length; i < ii; ++i) { stream.pos = trailers[i]; - var parser = new Parser(new Lexer(stream), true); + var parser = new Parser(new Lexer(stream), true, null); var obj = parser.getObj(); if (!isCmd(obj, 'trailer')) continue; @@ -513,50 +543,88 @@ var XRef = (function xRefXRef() { return dict; // nothing helps error('Invalid PDF structure'); - return null; }, - readXRef: function readXref(startXRef) { + readXRef: function XRef_readXRef(startXRef) { var stream = this.stream; stream.pos = startXRef; - var parser = new Parser(new Lexer(stream), true); - var obj = parser.getObj(); - // parse an old-style xref table - if (isCmd(obj, 'xref')) - return this.readXRefTable(parser); - // parse an xref stream - if (isInt(obj)) { - if (!isInt(parser.getObj()) || - !isCmd(parser.getObj(), 'obj') || - !isStream(obj = parser.getObj())) { - error('Invalid XRef stream'); + + try { + var parser = new Parser(new Lexer(stream), true, null); + var obj = parser.getObj(); + var dict; + + // Get dictionary + if (isCmd(obj, 'xref')) { + // Parse end-of-file XRef + dict = this.readXRefTable(parser); + + // Recursively get other XRefs 'XRefStm', if any + obj = dict.get('XRefStm'); + if (isInt(obj)) { + var pos = obj; + // ignore previously loaded xref streams + // (possible infinite recursion) + if (!(pos in this.xrefstms)) { + this.xrefstms[pos] = 1; + this.readXRef(pos); + } + } + } else if (isInt(obj)) { + // Parse in-stream XRef + if (!isInt(parser.getObj()) || + !isCmd(parser.getObj(), 'obj') || + !isStream(obj = parser.getObj())) { + error('Invalid XRef stream'); + } + dict = this.readXRefStream(obj); + } + + // Recursively get previous dictionary, if any + obj = dict.get('Prev'); + if (isInt(obj)) + this.readXRef(obj); + else if (isRef(obj)) { + // The spec says Prev must not be a reference, i.e. "/Prev NNN" + // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R" + this.readXRef(obj.num); } - return this.readXRefStream(obj); + + return dict; + } catch (e) { + log('(while reading XRef): ' + e); } + + warn('Indexing all PDF objects'); return this.indexObjects(); }, - getEntry: function xRefGetEntry(i) { + getEntry: function XRef_getEntry(i) { var e = this.entries[i]; - if (e.free) - error('reading an XRef stream not implemented yet'); - return e; + if (e === null) + return null; + return e.free ? null : e; // returns null is the entry is free }, - fetchIfRef: function xRefFetchIfRef(obj) { + fetchIfRef: function XRef_fetchIfRef(obj) { if (!isRef(obj)) return obj; return this.fetch(obj); }, - fetch: function xRefFetch(ref, suppressEncryption) { + fetch: function XRef_fetch(ref, suppressEncryption) { + assertWellFormed(isRef(ref), 'ref object is not a reference'); var num = ref.num; - var e = this.cache[num]; - if (e) - return e; + if (num in this.cache) + return this.cache[num]; + + var e = this.getEntry(num); + + // the referenced entry can be free + if (e === null) + return (this.cache[num] = e); - e = this.getEntry(num); var gen = ref.gen; var stream, parser; if (e.uncompressed) { if (e.gen != gen) - throw ('inconsistent generation in XRef'); + error('inconsistent generation in XRef'); stream = this.stream.makeSubStream(e.offset); parser = new Parser(new Lexer(stream), true, this); var obj1 = parser.getObj(); @@ -589,7 +657,7 @@ var XRef = (function xRefXRef() { e = parser.getObj(); } // Don't cache streams since they are mutable (except images). - if (!isStream(e) || e.getImage) + if (!isStream(e) || e instanceof JpegStream) this.cache[num] = e; return e; } @@ -603,7 +671,7 @@ var XRef = (function xRefXRef() { if (!isInt(first) || !isInt(n)) { error('invalid first and n parameters for ObjStm stream'); } - parser = new Parser(new Lexer(stream), false); + parser = new Parser(new Lexer(stream), false, this); var i, entries = [], nums = []; // read the object numbers to populate cache for (i = 0; i < n; ++i) { @@ -628,12 +696,12 @@ var XRef = (function xRefXRef() { } return e; }, - getCatalogObj: function xRefGetCatalogObj() { - return this.fetch(this.root); + getCatalogObj: function XRef_getCatalogObj() { + return this.root; } }; - return constructor; + return XRef; })(); /** @@ -642,7 +710,7 @@ var XRef = (function xRefXRef() { * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. */ -var PDFObjects = (function pdfObjects() { +var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } @@ -655,7 +723,7 @@ var PDFObjects = (function pdfObjects() { * Ensures there is an object defined for `objId`. Stores `data` on the * object *if* it is created. */ - ensureObj: function pdfObjectsEnsureObj(objId, data) { + ensureObj: function PDFObjects_ensureObj(objId, data) { if (this.objs[objId]) return this.objs[objId]; return this.objs[objId] = new Promise(objId, data); @@ -670,7 +738,7 @@ var PDFObjects = (function pdfObjects() { * function and the object is already resolved, the callback gets called * right away. */ - get: function pdfObjectsGet(objId, callback) { + get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { @@ -684,18 +752,16 @@ var PDFObjects = (function pdfObjects() { // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! - if (!obj || !obj.isResolved) { - throw 'Requesting object that isn\'t resolved yet ' + objId; - return null; - } else { - return obj.data; - } + if (!obj || !obj.isResolved) + error('Requesting object that isn\'t resolved yet ' + objId); + + return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ - resolve: function pdfObjectsResolve(objId, data) { + resolve: function PDFObjects_resolve(objId, data) { var objs = this.objs; // In case there is a promise already on this object, just resolve it. @@ -706,11 +772,11 @@ var PDFObjects = (function pdfObjects() { } }, - onData: function pdfObjectsOnData(objId, callback) { + onData: function PDFObjects_onData(objId, callback) { this.ensureObj(objId).onData(callback); }, - isResolved: function pdfObjectsIsResolved(objId) { + isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; @@ -719,7 +785,7 @@ var PDFObjects = (function pdfObjects() { } }, - hasData: function pdfObjectsHasData(objId) { + hasData: function PDFObjects_hasData(objId) { var objs = this.objs; if (!objs[objId]) { return false; @@ -731,7 +797,7 @@ var PDFObjects = (function pdfObjects() { /** * Sets the data of an object but *doesn't* resolve it. */ - setData: function pdfObjectsSetData(objId, data) { + setData: function PDFObjects_setData(objId, data) { // Watchout! If you call `this.ensureObj(objId, data)` you're going to // create a *resolved* promise which shouldn't be the case! this.ensureObj(objId).data = data; diff --git a/apps/files_pdfviewer/js/pdfjs/src/parser.js b/apps/files_pdfviewer/js/pdfjs/src/parser.js old mode 100755 new mode 100644 index 93a3f21b52a..1c50d0f5f95 --- a/apps/files_pdfviewer/js/pdfjs/src/parser.js +++ b/apps/files_pdfviewer/js/pdfjs/src/parser.js @@ -9,8 +9,8 @@ function isEOF(v) { return v == EOF; } -var Parser = (function parserParser() { - function constructor(lexer, allowStreams, xref) { +var Parser = (function ParserClosure() { + function Parser(lexer, allowStreams, xref) { this.lexer = lexer; this.allowStreams = allowStreams; this.xref = xref; @@ -18,12 +18,12 @@ var Parser = (function parserParser() { this.refill(); } - constructor.prototype = { - refill: function parserRefill() { + Parser.prototype = { + refill: function Parser_refill() { this.buf1 = this.lexer.getObj(); this.buf2 = this.lexer.getObj(); }, - shift: function parserShift() { + shift: function Parser_shift() { if (isCmd(this.buf2, 'ID')) { this.buf1 = this.buf2; this.buf2 = null; @@ -34,7 +34,7 @@ var Parser = (function parserParser() { this.buf2 = this.lexer.getObj(); } }, - getObj: function parserGetObj(cipherTransform) { + getObj: function Parser_getObj(cipherTransform) { if (isCmd(this.buf1, 'BI')) { // inline image this.shift(); return this.makeInlineImage(cipherTransform); @@ -51,17 +51,16 @@ var Parser = (function parserParser() { } if (isCmd(this.buf1, '<<')) { // dictionary or stream this.shift(); - var dict = new Dict(); + var dict = new Dict(this.xref); while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) { - if (!isName(this.buf1)) { + if (!isName(this.buf1)) error('Dictionary key must be a name object'); - } else { - var key = this.buf1.name; - this.shift(); - if (isEOF(this.buf1)) - break; - dict.set(key, this.getObj(cipherTransform)); - } + + var key = this.buf1.name; + this.shift(); + if (isEOF(this.buf1)) + break; + dict.set(key, this.getObj(cipherTransform)); } if (isEOF(this.buf1)) error('End of file inside dictionary'); @@ -99,38 +98,37 @@ var Parser = (function parserParser() { this.shift(); return obj; }, - makeInlineImage: function parserMakeInlineImage(cipherTransform) { + makeInlineImage: function Parser_makeInlineImage(cipherTransform) { var lexer = this.lexer; var stream = lexer.stream; // parse dictionary var dict = new Dict(); while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) { - if (!isName(this.buf1)) { + if (!isName(this.buf1)) error('Dictionary key must be a name object'); - } else { - var key = this.buf1.name; - this.shift(); - if (isEOF(this.buf1)) - break; - dict.set(key, this.getObj(cipherTransform)); - } + + var key = this.buf1.name; + this.shift(); + if (isEOF(this.buf1)) + break; + dict.set(key, this.getObj(cipherTransform)); } // parse image stream var startPos = stream.pos; - // searching for the /\sEI\s/ + // searching for the /EI\s/ var state = 0, ch; while (state != 4 && (ch = stream.getByte()) != null) { switch (ch) { case 0x20: case 0x0D: case 0x0A: - state = state === 3 ? 4 : 1; + state = state === 3 ? 4 : 0; break; case 0x45: - state = state === 1 ? 2 : 0; + state = 2; break; case 0x49: state = state === 2 ? 3 : 0; @@ -157,12 +155,16 @@ var Parser = (function parserParser() { imageStream = this.filter(imageStream, dict, length); imageStream.parameters = dict; - this.buf2 = new Cmd('EI'); + this.buf2 = Cmd.get('EI'); this.shift(); return imageStream; }, - makeStream: function parserMakeStream(dict, cipherTransform) { + fetchIfRef: function Parser_fetchIfRef(obj) { + // not relying on the xref.fetchIfRef -- xref might not be set + return isRef(obj) ? this.xref.fetch(obj) : obj; + }, + makeStream: function Parser_makeStream(dict, cipherTransform) { var lexer = this.lexer; var stream = lexer.stream; @@ -171,14 +173,9 @@ var Parser = (function parserParser() { var pos = stream.pos; // get length - var length = dict.get('Length'); - var xref = this.xref; - if (xref) - length = xref.fetchIfRef(length); - if (!isInt(length)) { + var length = this.fetchIfRef(dict.get('Length')); + if (!isInt(length)) error('Bad ' + length + ' attribute in stream'); - length = 0; - } // skip over the stream data stream.pos = pos + length; @@ -195,9 +192,9 @@ var Parser = (function parserParser() { stream.parameters = dict; return stream; }, - filter: function parserFilter(stream, dict, length) { - var filter = dict.get('Filter', 'F'); - var params = dict.get('DecodeParms', 'DP'); + filter: function Parser_filter(stream, dict, length) { + var filter = this.fetchIfRef(dict.get('Filter', 'F')); + var params = this.fetchIfRef(dict.get('DecodeParms', 'DP')); if (isName(filter)) return this.makeFilter(stream, filter.name, length, params); if (isArray(filter)) { @@ -207,25 +204,25 @@ var Parser = (function parserParser() { filter = filterArray[i]; if (!isName(filter)) error('Bad filter name: ' + filter); - else { - params = null; - if (isArray(paramsArray) && (i in paramsArray)) - params = paramsArray[i]; - stream = this.makeFilter(stream, filter.name, length, params); - // after the first stream the length variable is invalid - length = null; - } + + params = null; + if (isArray(paramsArray) && (i in paramsArray)) + params = paramsArray[i]; + stream = this.makeFilter(stream, filter.name, length, params); + // after the first stream the length variable is invalid + length = null; } } return stream; }, - makeFilter: function parserMakeFilter(stream, name, length, params) { + makeFilter: function Parser_makeFilter(stream, name, length, params) { if (name == 'FlateDecode' || name == 'Fl') { if (params) { return new PredictorStream(new FlateStream(stream), params); } return new FlateStream(stream); - } else if (name == 'LZWDecode' || name == 'LZW') { + } + if (name == 'LZWDecode' || name == 'LZW') { var earlyChange = 1; if (params) { if (params.has('EarlyChange')) @@ -234,31 +231,41 @@ var Parser = (function parserParser() { new LZWStream(stream, earlyChange), params); } return new LZWStream(stream, earlyChange); - } else if (name == 'DCTDecode' || name == 'DCT') { + } + if (name == 'DCTDecode' || name == 'DCT') { var bytes = stream.getBytes(length); return new JpegStream(bytes, stream.dict, this.xref); - } else if (name == 'ASCII85Decode' || name == 'A85') { + } + if (name == 'JPXDecode' || name == 'JPX') { + var bytes = stream.getBytes(length); + return new JpxStream(bytes, stream.dict); + } + if (name == 'ASCII85Decode' || name == 'A85') { return new Ascii85Stream(stream); - } else if (name == 'ASCIIHexDecode' || name == 'AHx') { + } + if (name == 'ASCIIHexDecode' || name == 'AHx') { return new AsciiHexStream(stream); - } else if (name == 'CCITTFaxDecode' || name == 'CCF') { + } + if (name == 'CCITTFaxDecode' || name == 'CCF') { return new CCITTFaxStream(stream, params); - } else { - TODO('filter "' + name + '" not supported yet'); } + if (name == 'RunLengthDecode') { + return new RunLengthStream(stream); + } + warn('filter "' + name + '" not supported yet'); return stream; } }; - return constructor; + return Parser; })(); -var Lexer = (function lexer() { - function constructor(stream) { +var Lexer = (function LexerClosure() { + function Lexer(stream) { this.stream = stream; } - constructor.isSpace = function lexerIsSpace(ch) { + Lexer.isSpace = function Lexer_isSpace(ch) { return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a'; }; @@ -292,8 +299,8 @@ var Lexer = (function lexer() { return -1; } - constructor.prototype = { - getNumber: function lexerGetNumber(ch) { + Lexer.prototype = { + getNumber: function Lexer_getNumber(ch) { var floating = false; var str = ch; var stream = this.stream; @@ -321,7 +328,7 @@ var Lexer = (function lexer() { error('Invalid floating point number: ' + value); return value; }, - getString: function lexerGetString() { + getString: function Lexer_getString() { var numParen = 1; var done = false; var str = ''; @@ -405,7 +412,7 @@ var Lexer = (function lexer() { } while (!done); return str; }, - getName: function lexerGetName(ch) { + getName: function Lexer_getName(ch) { var str = ''; var stream = this.stream; while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) { @@ -432,7 +439,7 @@ var Lexer = (function lexer() { str.length); return new Name(str); }, - getHexString: function lexerGetHexString(ch) { + getHexString: function Lexer_getHexString(ch) { var str = ''; var stream = this.stream; for (;;) { @@ -461,7 +468,7 @@ var Lexer = (function lexer() { } return str; }, - getObj: function lexerGetObj() { + getObj: function Lexer_getObj() { // skip whitespace and comments var comment = false; var stream = this.stream; @@ -492,14 +499,14 @@ var Lexer = (function lexer() { // array punctuation case '[': case ']': - return new Cmd(ch); + return Cmd.get(ch); // hex string or dict punctuation case '<': ch = stream.lookChar(); if (ch == '<') { // dict punctuation stream.skip(); - return new Cmd('<<'); + return Cmd.get('<<'); } return this.getHexString(ch); // dict punctuation @@ -507,25 +514,23 @@ var Lexer = (function lexer() { ch = stream.lookChar(); if (ch == '>') { stream.skip(); - return new Cmd('>>'); + return Cmd.get('>>'); } case '{': case '}': - return new Cmd(ch); + return Cmd.get(ch); // fall through case ')': error('Illegal character: ' + ch); - return Error; } // command var str = ch; while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) { stream.skip(); - if (str.length == 128) { + if (str.length == 128) error('Command token too long: ' + str.length); - break; - } + str += ch; } if (str == 'true') @@ -534,9 +539,9 @@ var Lexer = (function lexer() { return false; if (str == 'null') return null; - return new Cmd(str); + return Cmd.get(str); }, - skipToNextLine: function lexerSkipToNextLine() { + skipToNextLine: function Lexer_skipToNextLine() { var stream = this.stream; while (true) { var ch = stream.getChar(); @@ -549,17 +554,17 @@ var Lexer = (function lexer() { } } }, - skip: function lexerSkip() { + skip: function Lexer_skip() { this.stream.skip(); } }; - return constructor; + return Lexer; })(); -var Linearization = (function linearizationLinearization() { - function constructor(stream) { - this.parser = new Parser(new Lexer(stream), false); +var Linearization = (function LinearizationClosure() { + function Linearization(stream) { + this.parser = new Parser(new Lexer(stream), false, null); var obj1 = this.parser.getObj(); var obj2 = this.parser.getObj(); var obj3 = this.parser.getObj(); @@ -572,8 +577,8 @@ var Linearization = (function linearizationLinearization() { } } - constructor.prototype = { - getInt: function linearizationGetInt(name) { + Linearization.prototype = { + getInt: function Linearization_getInt(name) { var linDict = this.linDict; var obj; if (isDict(linDict) && @@ -582,9 +587,8 @@ var Linearization = (function linearizationLinearization() { return obj; } error('"' + name + '" field in linearization table is invalid'); - return 0; }, - getHint: function linearizationGetHint(index) { + getHint: function Linearization_getHint(index) { var linDict = this.linDict; var obj1, obj2; if (isDict(linDict) && @@ -595,7 +599,6 @@ var Linearization = (function linearizationLinearization() { return obj2; } error('Hints table in linearization table is invalid: ' + index); - return 0; }, get length() { if (!isDict(this.linDict)) @@ -631,6 +634,6 @@ var Linearization = (function linearizationLinearization() { } }; - return constructor; + return Linearization; })(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/pattern.js b/apps/files_pdfviewer/js/pdfjs/src/pattern.js old mode 100755 new mode 100644 index 72d13d896b2..7659f54363c --- a/apps/files_pdfviewer/js/pdfjs/src/pattern.js +++ b/apps/files_pdfviewer/js/pdfjs/src/pattern.js @@ -3,48 +3,53 @@ 'use strict'; -var Pattern = (function patternPattern() { +var PatternType = { + AXIAL: 2, + RADIAL: 3 +}; + +var Pattern = (function PatternClosure() { // Constructor should define this.getPattern - function constructor() { + function Pattern() { error('should not call Pattern constructor'); } - constructor.prototype = { + Pattern.prototype = { // Input: current Canvas context // Output: the appropriate fillStyle or strokeStyle - getPattern: function pattern_getStyle(ctx) { + getPattern: function Pattern_getPattern(ctx) { error('Should not call Pattern.getStyle: ' + ctx); } }; - constructor.shadingFromIR = function pattern_shadingFromIR(ctx, raw) { - return Shadings[raw[0]].fromIR(ctx, raw); + Pattern.shadingFromIR = function Pattern_shadingFromIR(raw) { + return Shadings[raw[0]].fromIR(raw); }; - constructor.parseShading = function pattern_shading(shading, matrix, xref, - res, ctx) { + Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref, + res) { var dict = isStream(shading) ? shading.dict : shading; var type = dict.get('ShadingType'); switch (type) { - case 2: - case 3: - // both radial and axial shadings are handled by RadialAxial shading - return new Shadings.RadialAxial(dict, matrix, xref, res, ctx); + case PatternType.AXIAL: + case PatternType.RADIAL: + // Both radial and axial shadings are handled by RadialAxial shading. + return new Shadings.RadialAxial(dict, matrix, xref, res); default: return new Shadings.Dummy(); } }; - return constructor; + return Pattern; })(); var Shadings = {}; // Radial and axial shading have very similar implementations // If needed, the implementations can be broken into two classes -Shadings.RadialAxial = (function radialAxialShading() { - function constructor(dict, matrix, xref, res, ctx) { +Shadings.RadialAxial = (function RadialAxialClosure() { + function RadialAxial(dict, matrix, xref, res, ctx) { this.matrix = matrix; this.coordsArr = dict.get('Coords'); this.shadingType = dict.get('ShadingType'); @@ -74,10 +79,9 @@ Shadings.RadialAxial = (function radialAxialShading() { this.extendEnd = extendEnd; var fnObj = dict.get('Function'); - fnObj = xref.fetchIfRef(fnObj); if (isArray(fnObj)) error('No support for array of functions'); - else if (!isPDFFunction(fnObj)) + if (!isPDFFunction(fnObj)) error('Invalid function'); var fn = PDFFunction.parse(xref, fnObj); @@ -89,56 +93,60 @@ Shadings.RadialAxial = (function radialAxialShading() { var colorStops = []; for (var i = t0; i <= t1; i += step) { - var color = fn([i]); - var rgbColor = Util.makeCssRgb.apply(this, cs.getRgb(color)); - colorStops.push([(i - t0) / diff, rgbColor]); + var rgbColor = cs.getRgb(fn([i])); + var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); + colorStops.push([(i - t0) / diff, cssColor]); } this.colorStops = colorStops; } - constructor.fromIR = function radialAxialShadingGetIR(ctx, raw) { + RadialAxial.fromIR = function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; - - var curMatrix = ctx.mozCurrentTransform; - if (curMatrix) { - var userMatrix = ctx.mozCurrentTransformInverse; - - p0 = Util.applyTransform(p0, curMatrix); - p0 = Util.applyTransform(p0, userMatrix); - - p1 = Util.applyTransform(p1, curMatrix); - p1 = Util.applyTransform(p1, userMatrix); - } - - var grad; - if (type == 2) - grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); - else if (type == 3) - grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); - - for (var i = 0, ii = colorStops.length; i < ii; ++i) { - var c = colorStops[i]; - grad.addColorStop(c[0], c[1]); - } - return grad; + return { + type: 'Pattern', + getPattern: function(ctx) { + var curMatrix = ctx.mozCurrentTransform; + if (curMatrix) { + var userMatrix = ctx.mozCurrentTransformInverse; + + p0 = Util.applyTransform(p0, curMatrix); + p0 = Util.applyTransform(p0, userMatrix); + + p1 = Util.applyTransform(p1, curMatrix); + p1 = Util.applyTransform(p1, userMatrix); + } + + var grad; + if (type == PatternType.AXIAL) + grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); + else if (type == PatternType.RADIAL) + grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); + + for (var i = 0, ii = colorStops.length; i < ii; ++i) { + var c = colorStops[i]; + grad.addColorStop(c[0], c[1]); + } + return grad; + } + }; }; - constructor.prototype = { - getIR: function radialAxialShadingGetIR() { + RadialAxial.prototype = { + getIR: function RadialAxial_getIR() { var coordsArr = this.coordsArr; var type = this.shadingType; - if (type == 2) { + if (type == PatternType.AXIAL) { var p0 = [coordsArr[0], coordsArr[1]]; var p1 = [coordsArr[2], coordsArr[3]]; var r0 = null; var r1 = null; - } else if (type == 3) { + } else if (type == PatternType.RADIAL) { var p0 = [coordsArr[0], coordsArr[1]]; var p1 = [coordsArr[3], coordsArr[4]]; var r0 = coordsArr[2]; @@ -157,31 +165,35 @@ Shadings.RadialAxial = (function radialAxialShading() { } }; - return constructor; + return RadialAxial; })(); -Shadings.Dummy = (function dummyShading() { - function constructor() { +Shadings.Dummy = (function DummyClosure() { + function Dummy() { this.type = 'Pattern'; } - constructor.fromIR = function dummyShadingFromIR() { + Dummy.fromIR = function Dummy_fromIR() { return 'hotpink'; }; - constructor.prototype = { - getIR: function dummyShadingGetIR() { + Dummy.prototype = { + getIR: function Dummy_getIR() { return ['Dummy']; } }; - return constructor; + return Dummy; })(); -var TilingPattern = (function tilingPattern() { - var PAINT_TYPE_COLORED = 1, PAINT_TYPE_UNCOLORED = 2; +var TilingPattern = (function TilingPatternClosure() { + var PaintType = { + COLORED: 1, + UNCOLORED: 2 + }; + var MAX_PATTERN_SIZE = 512; function TilingPattern(IR, color, ctx, objs) { - var IRQueue = IR[2]; + var operatorList = IR[2]; this.matrix = IR[3]; var bbox = IR[4]; var xstep = IR[5]; @@ -204,30 +216,30 @@ var TilingPattern = (function tilingPattern() { var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; - // TODO: hack to avoid OOM, we would idealy compute the tiling + // TODO: hack to avoid OOM, we would ideally compute the tiling // pattern to be only as large as the acual size in device space // This could be computed with .mozCurrentTransform, but still // needs to be implemented - while (Math.abs(width) > 512 || Math.abs(height) > 512) { - width = 512; - height = 512; + while (Math.abs(width) > MAX_PATTERN_SIZE || + Math.abs(height) > MAX_PATTERN_SIZE) { + width = height = MAX_PATTERN_SIZE; } - var tmpCanvas = new ScratchCanvas(width, height); + var tmpCanvas = createScratchCanvas(width, height); // set the new canvas element context as the graphics context var tmpCtx = tmpCanvas.getContext('2d'); var graphics = new CanvasGraphics(tmpCtx, objs); switch (paintType) { - case PAINT_TYPE_COLORED: + case PaintType.COLORED: tmpCtx.fillStyle = ctx.fillStyle; tmpCtx.strokeStyle = ctx.strokeStyle; break; - case PAINT_TYPE_UNCOLORED: - color = Util.makeCssRgb.apply(this, color); - tmpCtx.fillStyle = color; - tmpCtx.strokeStyle = color; + case PaintType.UNCOLORED: + var cssColor = Util.makeCssRgb(this, color[0], color[1], color[2]); + tmpCtx.fillStyle = cssColor; + tmpCtx.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); @@ -250,12 +262,12 @@ var TilingPattern = (function tilingPattern() { graphics.endPath(); } - graphics.executeIRQueue(IRQueue); + graphics.executeOperatorList(operatorList); this.canvas = tmpCanvas; } - TilingPattern.getIR = function tiling_getIR(codeIR, dict, args) { + TilingPattern.getIR = function TilingPattern_getIR(operatorList, dict, args) { var matrix = dict.get('Matrix'); var bbox = dict.get('BBox'); var xstep = dict.get('XStep'); @@ -263,12 +275,12 @@ var TilingPattern = (function tilingPattern() { var paintType = dict.get('PaintType'); return [ - 'TilingPattern', args, codeIR, matrix, bbox, xstep, ystep, paintType + 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep, paintType ]; }; TilingPattern.prototype = { - getPattern: function tiling_getPattern() { + getPattern: function TilingPattern_getPattern() { var matrix = this.matrix; var curMatrix = this.curMatrix; var ctx = this.ctx; diff --git a/apps/files_pdfviewer/js/pdfjs/src/pdf.js b/apps/files_pdfviewer/js/pdfjs/src/pdf.js old mode 100755 new mode 100644 diff --git a/apps/files_pdfviewer/js/pdfjs/src/stream.js b/apps/files_pdfviewer/js/pdfjs/src/stream.js old mode 100755 new mode 100644 index 559fb2ca22e..48c462fb2c3 --- a/apps/files_pdfviewer/js/pdfjs/src/stream.js +++ b/apps/files_pdfviewer/js/pdfjs/src/stream.js @@ -3,8 +3,8 @@ 'use strict'; -var Stream = (function streamStream() { - function constructor(arrayBuffer, start, length, dict) { +var Stream = (function StreamClosure() { + function Stream(arrayBuffer, start, length, dict) { this.bytes = new Uint8Array(arrayBuffer); this.start = start || 0; this.pos = this.start; @@ -14,18 +14,18 @@ var Stream = (function streamStream() { // required methods for a stream. if a particular stream does not // implement these, an error should be thrown - constructor.prototype = { + Stream.prototype = { get length() { return this.end - this.start; }, - getByte: function stream_getByte() { + getByte: function Stream_getByte() { if (this.pos >= this.end) return null; return this.bytes[this.pos++]; }, // returns subarray of original buffer // should only be read - getBytes: function stream_getBytes(length) { + getBytes: function Stream_getBytes(length) { var bytes = this.bytes; var pos = this.pos; var strEnd = this.end; @@ -40,38 +40,38 @@ var Stream = (function streamStream() { this.pos = end; return bytes.subarray(pos, end); }, - lookChar: function stream_lookChar() { + lookChar: function Stream_lookChar() { if (this.pos >= this.end) return null; return String.fromCharCode(this.bytes[this.pos]); }, - getChar: function stream_getChar() { + getChar: function Stream_getChar() { if (this.pos >= this.end) return null; return String.fromCharCode(this.bytes[this.pos++]); }, - skip: function stream_skip(n) { + skip: function Stream_skip(n) { if (!n) n = 1; this.pos += n; }, - reset: function stream_reset() { + reset: function Stream_reset() { this.pos = this.start; }, - moveStart: function stream_moveStart() { + moveStart: function Stream_moveStart() { this.start = this.pos; }, - makeSubStream: function stream_makeSubstream(start, length, dict) { + makeSubStream: function Stream_makeSubStream(start, length, dict) { return new Stream(this.bytes.buffer, start, length, dict); }, isStream: true }; - return constructor; + return Stream; })(); -var StringStream = (function stringStream() { - function constructor(str) { +var StringStream = (function StringStreamClosure() { + function StringStream(str) { var length = str.length; var bytes = new Uint8Array(length); for (var n = 0; n < length; ++n) @@ -79,22 +79,22 @@ var StringStream = (function stringStream() { Stream.call(this, bytes); } - constructor.prototype = Stream.prototype; + StringStream.prototype = Stream.prototype; - return constructor; + return StringStream; })(); // super class for the decoding streams -var DecodeStream = (function decodeStream() { - function constructor() { +var DecodeStream = (function DecodeStreamClosure() { + function DecodeStream() { this.pos = 0; this.bufferLength = 0; this.eof = false; this.buffer = null; } - constructor.prototype = { - ensureBuffer: function decodestream_ensureBuffer(requested) { + DecodeStream.prototype = { + ensureBuffer: function DecodeStream_ensureBuffer(requested) { var buffer = this.buffer; var current = buffer ? buffer.byteLength : 0; if (requested < current) @@ -107,7 +107,7 @@ var DecodeStream = (function decodeStream() { buffer2[i] = buffer[i]; return (this.buffer = buffer2); }, - getByte: function decodestream_getByte() { + getByte: function DecodeStream_getByte() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -116,7 +116,7 @@ var DecodeStream = (function decodeStream() { } return this.buffer[this.pos++]; }, - getBytes: function decodestream_getBytes(length) { + getBytes: function DecodeStream_getBytes(length) { var end, pos = this.pos; if (length) { @@ -144,7 +144,7 @@ var DecodeStream = (function decodeStream() { this.pos = end; return this.buffer.subarray(pos, end); }, - lookChar: function decodestream_lookChar() { + lookChar: function DecodeStream_lookChar() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -153,7 +153,7 @@ var DecodeStream = (function decodeStream() { } return String.fromCharCode(this.buffer[this.pos]); }, - getChar: function decodestream_getChar() { + getChar: function DecodeStream_getChar() { var pos = this.pos; while (this.bufferLength <= pos) { if (this.eof) @@ -162,40 +162,40 @@ var DecodeStream = (function decodeStream() { } return String.fromCharCode(this.buffer[this.pos++]); }, - makeSubStream: function decodestream_makeSubstream(start, length, dict) { + makeSubStream: function DecodeStream_makeSubStream(start, length, dict) { var end = start + length; while (this.bufferLength <= end && !this.eof) this.readBlock(); return new Stream(this.buffer, start, length, dict); }, - skip: function decodestream_skip(n) { + skip: function DecodeStream_skip(n) { if (!n) n = 1; this.pos += n; }, - reset: function decodestream_reset() { + reset: function DecodeStream_reset() { this.pos = 0; } }; - return constructor; + return DecodeStream; })(); -var FakeStream = (function fakeStream() { - function constructor(stream) { +var FakeStream = (function FakeStreamClosure() { + function FakeStream(stream) { this.dict = stream.dict; DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function fakeStreamReadBlock() { + FakeStream.prototype = Object.create(DecodeStream.prototype); + FakeStream.prototype.readBlock = function FakeStream_readBlock() { var bufferLength = this.bufferLength; bufferLength += 1024; var buffer = this.ensureBuffer(bufferLength); this.bufferLength = bufferLength; }; - constructor.prototype.getBytes = function fakeStreamGetBytes(length) { + FakeStream.prototype.getBytes = function FakeStream_getBytes(length) { var end, pos = this.pos; if (length) { @@ -217,18 +217,20 @@ var FakeStream = (function fakeStream() { return this.buffer.subarray(pos, end); }; - return constructor; + return FakeStream; })(); -var StreamsSequenceStream = (function streamSequenceStream() { - function constructor(streams) { +var StreamsSequenceStream = (function StreamsSequenceStreamClosure() { + function StreamsSequenceStream(streams) { this.streams = streams; DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype); + + StreamsSequenceStream.prototype.readBlock = + function streamSequenceStreamReadBlock() { - constructor.prototype.readBlock = function streamSequenceStreamReadBlock() { var streams = this.streams; if (streams.length == 0) { this.eof = true; @@ -243,10 +245,10 @@ var StreamsSequenceStream = (function streamSequenceStream() { this.bufferLength = newLength; }; - return constructor; + return StreamsSequenceStream; })(); -var FlateStream = (function flateStream() { +var FlateStream = (function FlateStreamClosure() { var codeLenCodeMap = new Uint32Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); @@ -339,7 +341,7 @@ var FlateStream = (function flateStream() { 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000 ]), 5]; - function constructor(stream) { + function FlateStream(stream) { var bytes = stream.getBytes(); var bytesPos = 0; @@ -364,9 +366,9 @@ var FlateStream = (function flateStream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + FlateStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.getBits = function flateStreamGetBits(bits) { + FlateStream.prototype.getBits = function FlateStream_getBits(bits) { var codeSize = this.codeSize; var codeBuf = this.codeBuf; var bytes = this.bytes; @@ -386,7 +388,7 @@ var FlateStream = (function flateStream() { return b; }; - constructor.prototype.getCode = function flateStreamGetCode(table) { + FlateStream.prototype.getCode = function FlateStream_getCode(table) { var codes = table[0]; var maxLen = table[1]; var codeSize = this.codeSize; @@ -412,7 +414,7 @@ var FlateStream = (function flateStream() { return codeVal; }; - constructor.prototype.generateHuffmanTable = + FlateStream.prototype.generateHuffmanTable = function flateStreamGenerateHuffmanTable(lengths) { var n = lengths.length; @@ -451,7 +453,7 @@ var FlateStream = (function flateStream() { return [codes, maxLen]; }; - constructor.prototype.readBlock = function flateStreamReadBlock() { + FlateStream.prototype.readBlock = function FlateStream_readBlock() { // read block header var hdr = this.getBits(3); if (hdr & 1) @@ -582,11 +584,11 @@ var FlateStream = (function flateStream() { } }; - return constructor; + return FlateStream; })(); -var PredictorStream = (function predictorStream() { - function constructor(stream, params) { +var PredictorStream = (function PredictorStreamClosure() { + function PredictorStream(stream, params) { var predictor = this.predictor = params.get('Predictor') || 1; if (predictor <= 1) @@ -613,15 +615,14 @@ var PredictorStream = (function predictorStream() { return this; } - constructor.prototype = Object.create(DecodeStream.prototype); + PredictorStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlockTiff = + PredictorStream.prototype.readBlockTiff = function predictorStreamReadBlockTiff() { var rowBytes = this.rowBytes; var bufferLength = this.bufferLength; var buffer = this.ensureBuffer(bufferLength + rowBytes); - var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes); var bits = this.bits; var colors = this.colors; @@ -630,6 +631,7 @@ var PredictorStream = (function predictorStream() { var inbuf = 0, outbuf = 0; var inbits = 0, outbits = 0; + var pos = bufferLength; if (bits === 1) { for (var i = 0; i < rowBytes; ++i) { @@ -637,19 +639,21 @@ var PredictorStream = (function predictorStream() { inbuf = (inbuf << 8) | c; // bitwise addition is exclusive or // first shift inbuf and then add - currentRow[i] = (c ^ (inbuf >> colors)) & 0xFF; + buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF; // truncate inbuf (assumes colors < 16) inbuf &= 0xFFFF; } } else if (bits === 8) { for (var i = 0; i < colors; ++i) - currentRow[i] = rawBytes[i]; - for (; i < rowBytes; ++i) - currentRow[i] = currentRow[i - colors] + rawBytes[i]; + buffer[pos++] = rawBytes[i]; + for (; i < rowBytes; ++i) { + buffer[pos] = buffer[pos - colors] + rawBytes[i]; + pos++; + } } else { var compArray = new Uint8Array(colors + 1); var bitMask = (1 << bits) - 1; - var j = 0, k = 0; + var j = 0, k = bufferLength; var columns = this.columns; for (var i = 0; i < columns; ++i) { for (var kk = 0; kk < colors; ++kk) { @@ -663,20 +667,22 @@ var PredictorStream = (function predictorStream() { outbuf = (outbuf << bits) | compArray[kk]; outbits += bits; if (outbits >= 8) { - currentRow[k++] = (outbuf >> (outbits - 8)) & 0xFF; + buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF; outbits -= 8; } } } if (outbits > 0) { - currentRow[k++] = (outbuf << (8 - outbits)) + + buffer[k++] = (outbuf << (8 - outbits)) + (inbuf & ((1 << (8 - outbits)) - 1)); } } this.bufferLength += rowBytes; }; - constructor.prototype.readBlockPng = function predictorStreamReadBlockPng() { + PredictorStream.prototype.readBlockPng = + function predictorStreamReadBlockPng() { + var rowBytes = this.rowBytes; var pixBytes = this.pixBytes; @@ -686,32 +692,35 @@ var PredictorStream = (function predictorStream() { var bufferLength = this.bufferLength; var buffer = this.ensureBuffer(bufferLength + rowBytes); - var currentRow = buffer.subarray(bufferLength, bufferLength + rowBytes); var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength); if (prevRow.length == 0) prevRow = new Uint8Array(rowBytes); + var j = bufferLength; switch (predictor) { case 0: for (var i = 0; i < rowBytes; ++i) - currentRow[i] = rawBytes[i]; + buffer[j++] = rawBytes[i]; break; case 1: for (var i = 0; i < pixBytes; ++i) - currentRow[i] = rawBytes[i]; - for (; i < rowBytes; ++i) - currentRow[i] = (currentRow[i - pixBytes] + rawBytes[i]) & 0xFF; + buffer[j++] = rawBytes[i]; + for (; i < rowBytes; ++i) { + buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF; + j++; + } break; case 2: for (var i = 0; i < rowBytes; ++i) - currentRow[i] = (prevRow[i] + rawBytes[i]) & 0xFF; + buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF; break; case 3: for (var i = 0; i < pixBytes; ++i) - currentRow[i] = (prevRow[i] >> 1) + rawBytes[i]; + buffer[j++] = (prevRow[i] >> 1) + rawBytes[i]; for (; i < rowBytes; ++i) { - currentRow[i] = (((prevRow[i] + currentRow[i - pixBytes]) >> 1) + + buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) + rawBytes[i]) & 0xFF; + j++; } break; case 4: @@ -720,12 +729,12 @@ var PredictorStream = (function predictorStream() { for (var i = 0; i < pixBytes; ++i) { var up = prevRow[i]; var c = rawBytes[i]; - currentRow[i] = up + c; + buffer[j++] = up + c; } for (; i < rowBytes; ++i) { var up = prevRow[i]; var upLeft = prevRow[i - pixBytes]; - var left = currentRow[i - pixBytes]; + var left = buffer[j - pixBytes]; var p = left + up - upLeft; var pa = p - left; @@ -740,11 +749,11 @@ var PredictorStream = (function predictorStream() { var c = rawBytes[i]; if (pa <= pb && pa <= pc) - currentRow[i] = left + c; + buffer[j++] = left + c; else if (pb <= pc) - currentRow[i] = up + c; + buffer[j++] = up + c; else - currentRow[i] = upLeft + c; + buffer[j++] = upLeft + c; } break; default: @@ -753,7 +762,7 @@ var PredictorStream = (function predictorStream() { this.bufferLength += rowBytes; }; - return constructor; + return PredictorStream; })(); /** @@ -763,7 +772,7 @@ var PredictorStream = (function predictorStream() { * a library to decode these images and the stream behaves like all the other * DecodeStreams. */ -var JpegStream = (function jpegStream() { +var JpegStream = (function JpegStreamClosure() { function isAdobeImage(bytes) { var maxBytesScanned = Math.max(bytes.length - 16, 1024); // Looking for APP14, 'Adobe' @@ -794,63 +803,184 @@ var JpegStream = (function jpegStream() { return newBytes; } - function constructor(bytes, dict, xref) { + function JpegStream(bytes, dict, xref) { // TODO: per poppler, some images may have 'junk' before that // need to be removed this.dict = dict; - // Flag indicating wether the image can be natively loaded. - this.isNative = true; - - this.colorTransform = -1; + this.isAdobeImage = false; + this.colorTransform = dict.get('ColorTransform') || -1; if (isAdobeImage(bytes)) { - // when bug 674619 land, let's check if browser can do - // normal cmyk and then we won't have to the following - var cs = xref.fetchIfRef(dict.get('ColorSpace')); - - // DeviceRGB and DeviceGray are the only Adobe images that work natively - if (isName(cs) && (cs.name === 'DeviceRGB' || cs.name === 'DeviceGray')) { - bytes = fixAdobeImage(bytes); - this.src = bytesToString(bytes); - } else { - this.colorTransform = dict.get('ColorTransform'); - this.isNative = false; - this.bytes = bytes; - } - } else { - this.src = bytesToString(bytes); + this.isAdobeImage = true; + bytes = fixAdobeImage(bytes); } + this.bytes = bytes; + DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + JpegStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) { + JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) { if (this.bufferLength) return; - var jpegImage = new JpegImage(); - jpegImage.colorTransform = this.colorTransform; - jpegImage.parse(this.bytes); - var width = jpegImage.width; - var height = jpegImage.height; - var data = jpegImage.getData(width, height); + try { + var jpegImage = new JpegImage(); + if (this.colorTransform != -1) + jpegImage.colorTransform = this.colorTransform; + jpegImage.parse(this.bytes); + var width = jpegImage.width; + var height = jpegImage.height; + var data = jpegImage.getData(width, height); + this.buffer = data; + this.bufferLength = data.length; + } catch (e) { + error('JPEG error: ' + e); + } + }; + JpegStream.prototype.getIR = function JpegStream_getIR() { + return bytesToString(this.bytes); + }; + JpegStream.prototype.getChar = function JpegStream_getChar() { + error('internal error: getChar is not valid on JpegStream'); + }; + /** + * Checks if the image can be decoded and displayed by the browser without any + * further processing such as color space conversions. + */ + JpegStream.prototype.isNativelySupported = + function JpegStream_isNativelySupported(xref, res) { + var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res); + // when bug 674619 lands, let's check if browser can do + // normal cmyk and then we won't need to decode in JS + if (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') + return true; + if (cs.name === 'DeviceCMYK' && !this.isAdobeImage && + this.colorTransform < 1) + return true; + return false; + }; + /** + * Checks if the image can be decoded by the browser. + */ + JpegStream.prototype.isNativelyDecodable = + function JpegStream_isNativelyDecodable(xref, res) { + var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res); + var numComps = cs.numComps; + if (numComps == 1 || numComps == 3) + return true; + + return false; + }; + + return JpegStream; +})(); + +/** + * For JPEG 2000's we use a library to decode these images and + * the stream behaves like all the other DecodeStreams. + */ +var JpxStream = (function JpxStreamClosure() { + function JpxStream(bytes, dict) { + this.dict = dict; + this.bytes = bytes; + + DecodeStream.call(this); + } + + JpxStream.prototype = Object.create(DecodeStream.prototype); + + JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) { + if (this.bufferLength) + return; + + var jpxImage = new JpxImage(); + jpxImage.parse(this.bytes); + + var width = jpxImage.width; + var height = jpxImage.height; + var componentsCount = jpxImage.componentsCount; + if (componentsCount != 1 && componentsCount != 3 && componentsCount != 4) + error('JPX with ' + componentsCount + ' components is not supported'); + + var data = new Uint8Array(width * height * componentsCount); + + for (var k = 0, kk = jpxImage.tiles.length; k < kk; k++) { + var tileCompoments = jpxImage.tiles[k]; + var tileWidth = tileCompoments[0].width; + var tileHeight = tileCompoments[0].height; + var tileLeft = tileCompoments[0].left; + var tileTop = tileCompoments[0].top; + + var dataPosition, sourcePosition, data0, data1, data2, data3, rowFeed; + switch (componentsCount) { + case 1: + data0 = tileCompoments[0].items; + + dataPosition = width * tileTop + tileLeft; + rowFeed = width - tileWidth; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) + data[dataPosition++] = data0[sourcePosition++]; + dataPosition += rowFeed; + } + break; + case 3: + data0 = tileCompoments[0].items; + data1 = tileCompoments[1].items; + data2 = tileCompoments[2].items; + + dataPosition = (width * tileTop + tileLeft) * 3; + rowFeed = (width - tileWidth) * 3; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) { + data[dataPosition++] = data0[sourcePosition]; + data[dataPosition++] = data1[sourcePosition]; + data[dataPosition++] = data2[sourcePosition]; + sourcePosition++; + } + dataPosition += rowFeed; + } + break; + case 4: + data0 = tileCompoments[0].items; + data1 = tileCompoments[1].items; + data2 = tileCompoments[2].items; + data3 = tileCompoments[3].items; + + dataPosition = (width * tileTop + tileLeft) * 4; + rowFeed = (width - tileWidth) * 4; + sourcePosition = 0; + for (var j = 0; j < tileHeight; j++) { + for (var i = 0; i < tileWidth; i++) { + data[dataPosition++] = data0[sourcePosition]; + data[dataPosition++] = data1[sourcePosition]; + data[dataPosition++] = data2[sourcePosition]; + data[dataPosition++] = data3[sourcePosition]; + sourcePosition++; + } + dataPosition += rowFeed; + } + break; + } + } + this.buffer = data; this.bufferLength = data.length; }; - constructor.prototype.getIR = function jpegStreamGetIR() { - return this.src; - }; - constructor.prototype.getChar = function jpegStreamGetChar() { - error('internal error: getChar is not valid on JpegStream'); + JpxStream.prototype.getChar = function JpxStream_getChar() { + error('internal error: getChar is not valid on JpxStream'); }; - return constructor; + return JpxStream; })(); -var DecryptStream = (function decryptStream() { - function constructor(str, decrypt) { +var DecryptStream = (function DecryptStreamClosure() { + function DecryptStream(str, decrypt) { this.str = str; this.dict = str.dict; this.decrypt = decrypt; @@ -860,9 +990,9 @@ var DecryptStream = (function decryptStream() { var chunkSize = 512; - constructor.prototype = Object.create(DecodeStream.prototype); + DecryptStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function decryptStreamReadBlock() { + DecryptStream.prototype.readBlock = function DecryptStream_readBlock() { var chunk = this.str.getBytes(chunkSize); if (!chunk || chunk.length == 0) { this.eof = true; @@ -879,11 +1009,11 @@ var DecryptStream = (function decryptStream() { this.bufferLength = bufferLength; }; - return constructor; + return DecryptStream; })(); -var Ascii85Stream = (function ascii85Stream() { - function constructor(str) { +var Ascii85Stream = (function Ascii85StreamClosure() { + function Ascii85Stream(str) { this.str = str; this.dict = str.dict; this.input = new Uint8Array(5); @@ -891,9 +1021,9 @@ var Ascii85Stream = (function ascii85Stream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + Ascii85Stream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function ascii85StreamReadBlock() { + Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() { var tildaCode = '~'.charCodeAt(0); var zCode = 'z'.charCodeAt(0); var str = this.str; @@ -948,11 +1078,11 @@ var Ascii85Stream = (function ascii85Stream() { } }; - return constructor; + return Ascii85Stream; })(); -var AsciiHexStream = (function asciiHexStream() { - function constructor(str) { +var AsciiHexStream = (function AsciiHexStreamClosure() { + function AsciiHexStream(str) { this.str = str; this.dict = str.dict; @@ -986,9 +1116,9 @@ var AsciiHexStream = (function asciiHexStream() { 102: 15 }; - constructor.prototype = Object.create(DecodeStream.prototype); + AsciiHexStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function asciiHexStreamReadBlock() { + AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() { var gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n, decodeLength, buffer, bufferLength, i, length; @@ -1018,10 +1148,55 @@ var AsciiHexStream = (function asciiHexStream() { this.eof = true; }; - return constructor; + return AsciiHexStream; +})(); + +var RunLengthStream = (function RunLengthStreamClosure() { + function RunLengthStream(str) { + this.str = str; + this.dict = str.dict; + + DecodeStream.call(this); + } + + RunLengthStream.prototype = Object.create(DecodeStream.prototype); + + RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() { + // The repeatHeader has following format. The first byte defines type of run + // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes + // (in addition to the second byte from the header), n = 129 through 255 - + // duplicate the second byte from the header (257 - n) times, n = 128 - end. + var repeatHeader = this.str.getBytes(2); + if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] == 128) { + this.eof = true; + return; + } + + var bufferLength = this.bufferLength; + var n = repeatHeader[0]; + if (n < 128) { + // copy n bytes + var buffer = this.ensureBuffer(bufferLength + n + 1); + buffer[bufferLength++] = repeatHeader[1]; + if (n > 0) { + var source = this.str.getBytes(n); + buffer.set(source, bufferLength); + bufferLength += n; + } + } else { + n = 257 - n; + var b = repeatHeader[1]; + var buffer = this.ensureBuffer(bufferLength + n + 1); + for (var i = 0; i < n; i++) + buffer[bufferLength++] = b; + } + this.bufferLength = bufferLength; + }; + + return RunLengthStream; })(); -var CCITTFaxStream = (function ccittFaxStream() { +var CCITTFaxStream = (function CCITTFaxStreamClosure() { var ccittEOL = -2; var twoDimPass = 0; @@ -1449,7 +1624,7 @@ var CCITTFaxStream = (function ccittFaxStream() { [2, 2], [2, 2], [2, 2], [2, 2] ]; - function constructor(str, params) { + function CCITTFaxStream(str, params) { this.str = str; this.dict = str.dict; @@ -1494,9 +1669,9 @@ var CCITTFaxStream = (function ccittFaxStream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + CCITTFaxStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBlock = function ccittFaxStreamReadBlock() { + CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() { while (!this.eof) { var c = this.lookChar(); this.buf = EOF; @@ -1505,7 +1680,7 @@ var CCITTFaxStream = (function ccittFaxStream() { } }; - constructor.prototype.addPixels = + CCITTFaxStream.prototype.addPixels = function ccittFaxStreamAddPixels(a1, blackPixels) { var codingLine = this.codingLine; var codingPos = this.codingPos; @@ -1525,7 +1700,7 @@ var CCITTFaxStream = (function ccittFaxStream() { this.codingPos = codingPos; }; - constructor.prototype.addPixelsNeg = + CCITTFaxStream.prototype.addPixelsNeg = function ccittFaxStreamAddPixelsNeg(a1, blackPixels) { var codingLine = this.codingLine; var codingPos = this.codingPos; @@ -1554,7 +1729,7 @@ var CCITTFaxStream = (function ccittFaxStream() { this.codingPos = codingPos; }; - constructor.prototype.lookChar = function ccittFaxStreamLookChar() { + CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() { if (this.buf != EOF) return this.buf; @@ -1852,10 +2027,10 @@ var CCITTFaxStream = (function ccittFaxStream() { // values. The first array element indicates whether a valid code is being // returned. The second array element is the actual code. The third array // element indicates whether EOF was reached. - var findTableCode = function ccittFaxStreamFindTableCode(start, end, table, - limit) { - var limitValue = limit || 0; + CCITTFaxStream.prototype.findTableCode = + function ccittFaxStreamFindTableCode(start, end, table, limit) { + var limitValue = limit || 0; for (var i = start; i <= end; ++i) { var code = this.lookBits(i); if (code == EOF) @@ -1873,18 +2048,20 @@ var CCITTFaxStream = (function ccittFaxStream() { return [false, 0, false]; }; - constructor.prototype.getTwoDimCode = function ccittFaxStreamGetTwoDimCode() { + CCITTFaxStream.prototype.getTwoDimCode = + function ccittFaxStreamGetTwoDimCode() { + var code = 0; var p; if (this.eoblock) { code = this.lookBits(7); p = twoDimTable[code]; - if (p[0] > 0) { + if (p && p[0] > 0) { this.eatBits(p[0]); return p[1]; } } else { - var result = findTableCode(1, 7, twoDimTable); + var result = this.findTableCode(1, 7, twoDimTable); if (result[0] && result[2]) return result[1]; } @@ -1892,7 +2069,9 @@ var CCITTFaxStream = (function ccittFaxStream() { return EOF; }; - constructor.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() { + CCITTFaxStream.prototype.getWhiteCode = + function ccittFaxStreamGetWhiteCode() { + var code = 0; var p; var n; @@ -1911,11 +2090,11 @@ var CCITTFaxStream = (function ccittFaxStream() { return p[1]; } } else { - var result = findTableCode(1, 9, whiteTable2); + var result = this.findTableCode(1, 9, whiteTable2); if (result[0]) return result[1]; - result = findTableCode(11, 12, whiteTable1); + result = this.findTableCode(11, 12, whiteTable1); if (result[0]) return result[1]; } @@ -1924,7 +2103,9 @@ var CCITTFaxStream = (function ccittFaxStream() { return 1; }; - constructor.prototype.getBlackCode = function ccittFaxStreamGetBlackCode() { + CCITTFaxStream.prototype.getBlackCode = + function ccittFaxStreamGetBlackCode() { + var code, p; if (this.eoblock) { code = this.lookBits(13); @@ -1942,15 +2123,15 @@ var CCITTFaxStream = (function ccittFaxStream() { return p[1]; } } else { - var result = findTableCode(2, 6, blackTable3); + var result = this.findTableCode(2, 6, blackTable3); if (result[0]) return result[1]; - result = findTableCode(7, 12, blackTable2, 64); + result = this.findTableCode(7, 12, blackTable2, 64); if (result[0]) return result[1]; - result = findTableCode(10, 13, blackTable1); + result = this.findTableCode(10, 13, blackTable1); if (result[0]) return result[1]; } @@ -1959,7 +2140,7 @@ var CCITTFaxStream = (function ccittFaxStream() { return 1; }; - constructor.prototype.lookBits = function ccittFaxStreamLookBits(n) { + CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) { var c; while (this.inputBits < n) { if ((c = this.str.getByte()) == null) { @@ -1974,16 +2155,16 @@ var CCITTFaxStream = (function ccittFaxStream() { return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n)); }; - constructor.prototype.eatBits = function ccittFaxStreamEatBits(n) { + CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) { if ((this.inputBits -= n) < 0) this.inputBits = 0; }; - return constructor; + return CCITTFaxStream; })(); -var LZWStream = (function lzwStream() { - function constructor(str, earlyChange) { +var LZWStream = (function LZWStreamClosure() { + function LZWStream(str, earlyChange) { this.str = str; this.dict = str.dict; this.cachedData = 0; @@ -2009,9 +2190,9 @@ var LZWStream = (function lzwStream() { DecodeStream.call(this); } - constructor.prototype = Object.create(DecodeStream.prototype); + LZWStream.prototype = Object.create(DecodeStream.prototype); - constructor.prototype.readBits = function lzwStreamReadBits(n) { + LZWStream.prototype.readBits = function LZWStream_readBits(n) { var bitsCached = this.bitsCached; var cachedData = this.cachedData; while (bitsCached < n) { @@ -2029,7 +2210,7 @@ var LZWStream = (function lzwStream() { return (cachedData >>> bitsCached) & ((1 << n) - 1); }; - constructor.prototype.readBlock = function lzwStreamReadBlock() { + LZWStream.prototype.readBlock = function LZWStream_readBlock() { var blockSize = 512; var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize; var i, j, q; @@ -2108,6 +2289,6 @@ var LZWStream = (function lzwStream() { this.bufferLength = currentBufferLength; }; - return constructor; + return LZWStream; })(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/util.js b/apps/files_pdfviewer/js/pdfjs/src/util.js old mode 100755 new mode 100644 index 4fb96f062a8..de7f3c1d548 --- a/apps/files_pdfviewer/js/pdfjs/src/util.js +++ b/apps/files_pdfviewer/js/pdfjs/src/util.js @@ -76,24 +76,102 @@ function stringToBytes(str) { var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; -var Util = (function utilUtil() { - function constructor() {} - constructor.makeCssRgb = function makergb(r, g, b) { +var Util = (function UtilClosure() { + function Util() {} + + Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { var ri = (255 * r) | 0, gi = (255 * g) | 0, bi = (255 * b) | 0; return 'rgb(' + ri + ',' + gi + ',' + bi + ')'; }; - constructor.makeCssCmyk = function makecmyk(c, m, y, k) { + + Util.makeCssCmyk = function Util_makeCssCmyk(c, m, y, k) { c = (new DeviceCmykCS()).getRgb([c, m, y, k]); var ri = (255 * c[0]) | 0, gi = (255 * c[1]) | 0, bi = (255 * c[2]) | 0; return 'rgb(' + ri + ',' + gi + ',' + bi + ')'; }; - constructor.applyTransform = function apply(p, m) { + + // For 2d affine transforms + Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; - return constructor; + // Apply a generic 3d matrix M on a 3-vector v: + // | a b c | | X | + // | d e f | x | Y | + // | g h i | | Z | + // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], + // with v as [X,Y,Z] + Util.apply3dTransform = function Util_apply3dTransform(m, v) { + return [ + m[0] * v[0] + m[1] * v[1] + m[2] * v[2], + m[3] * v[0] + m[4] * v[1] + m[5] * v[2], + m[6] * v[0] + m[7] * v[1] + m[8] * v[2] + ]; + } + + // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) + // For coordinate systems whose origin lies in the bottom-left, this + // means normalization to (BL,TR) ordering. For systems with origin in the + // top-left, this means (TL,BR) ordering. + Util.normalizeRect = function Util_normalizeRect(rect) { + var r = rect.slice(0); // clone rect + if (rect[0] > rect[2]) { + r[0] = rect[2]; + r[2] = rect[0]; + } + if (rect[1] > rect[3]) { + r[1] = rect[3]; + r[3] = rect[1]; + } + return r; + } + + // Returns a rectangle [x1, y1, x2, y2] corresponding to the + // intersection of rect1 and rect2. If no intersection, returns 'false' + // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] + Util.intersect = function Util_intersect(rect1, rect2) { + function compare(a, b) { + return a - b; + }; + + // Order points along the axes + var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), + orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), + result = []; + + rect1 = Util.normalizeRect(rect1); + rect2 = Util.normalizeRect(rect2); + + // X: first and second points belong to different rectangles? + if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || + (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { + // Intersection must be between second and third points + result[0] = orderedX[1]; + result[2] = orderedX[2]; + } else { + return false; + } + + // Y: first and second points belong to different rectangles? + if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || + (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { + // Intersection must be between second and third points + result[1] = orderedY[1]; + result[3] = orderedY[2]; + } else { + return false; + } + + return result; + } + + Util.sign = function Util_sign(num) { + return num < 0 ? -1 : 1; + }; + + return Util; })(); var PDFStringTranslateTable = [ @@ -197,7 +275,7 @@ function isPDFFunction(v) { * can be set. If any of these happens twice or the data is required before * it was set, an exception is throw. */ -var Promise = (function promise() { +var Promise = (function PromiseClosure() { var EMPTY_PROMISE = {}; /** @@ -206,6 +284,8 @@ var Promise = (function promise() { */ function Promise(name, data) { this.name = name; + this.isRejected = false; + this.error = null; // If you build a promise and pass in some data it's already resolved. if (data != null) { this.isResolved = true; @@ -216,8 +296,35 @@ var Promise = (function promise() { this._data = EMPTY_PROMISE; } this.callbacks = []; + this.errbacks = []; + }; + /** + * Builds a promise that is resolved when all the passed in promises are + * resolved. + * @param {Promise[]} promises Array of promises to wait for. + * @return {Promise} New dependant promise. + */ + Promise.all = function Promise_all(promises) { + var deferred = new Promise(); + var unresolved = promises.length; + var results = []; + if (unresolved === 0) { + deferred.resolve(results); + return deferred; + } + for (var i = 0; i < unresolved; ++i) { + var promise = promises[i]; + promise.then((function(i) { + return function(value) { + results[i] = value; + unresolved--; + if (unresolved === 0) + deferred.resolve(results); + }; + })(i)); + } + return deferred; }; - Promise.prototype = { hasData: false, @@ -226,8 +333,8 @@ var Promise = (function promise() { return; } if (this._data !== EMPTY_PROMISE) { - throw 'Promise ' + this.name + - ': Cannot set the data of a promise twice'; + error('Promise ' + this.name + + ': Cannot set the data of a promise twice'); } this._data = value; this.hasData = true; @@ -239,12 +346,12 @@ var Promise = (function promise() { get data() { if (this._data === EMPTY_PROMISE) { - throw 'Promise ' + this.name + ': Cannot get data that isn\'t set'; + error('Promise ' + this.name + ': Cannot get data that isn\'t set'); } return this._data; }, - onData: function promiseOnData(callback) { + onData: function Promise_onData(callback) { if (this._data !== EMPTY_PROMISE) { callback(this._data); } else { @@ -252,13 +359,16 @@ var Promise = (function promise() { } }, - resolve: function promiseResolve(data) { + resolve: function Promise_resolve(data) { if (this.isResolved) { - throw 'A Promise can be resolved only once ' + this.name; + error('A Promise can be resolved only once ' + this.name); + } + if (this.isRejected) { + error('The Promise was already rejected ' + this.name); } this.isResolved = true; - this.data = data; + this.data = data || null; var callbacks = this.callbacks; for (var i = 0, ii = callbacks.length; i < ii; i++) { @@ -266,17 +376,39 @@ var Promise = (function promise() { } }, - then: function promiseThen(callback) { + reject: function Promise_reject(reason) { + if (this.isRejected) { + error('A Promise can be rejected only once ' + this.name); + } + if (this.isResolved) { + error('The Promise was already resolved ' + this.name); + } + + this.isRejected = true; + this.error = reason || null; + var errbacks = this.errbacks; + + for (var i = 0, ii = errbacks.length; i < ii; i++) { + errbacks[i].call(null, reason); + } + }, + + then: function Promise_then(callback, errback) { if (!callback) { - throw 'Requiring callback' + this.name; + error('Requiring callback' + this.name); } // If the promise is already resolved, call the callback directly. if (this.isResolved) { var data = this.data; callback.call(null, data); + } else if (this.isRejected && errback) { + var error = this.error; + errback.call(null, error); } else { this.callbacks.push(callback); + if (errback) + this.errbacks.push(errback); } } }; @@ -284,3 +416,55 @@ var Promise = (function promise() { return Promise; })(); +var StatTimer = (function StatTimerClosure() { + function rpad(str, pad, length) { + while (str.length < length) + str += pad; + return str; + } + function StatTimer() { + this.started = {}; + this.times = []; + this.enabled = true; + } + StatTimer.prototype = { + time: function StatTimer_time(name) { + if (!this.enabled) + return; + if (name in this.started) + throw 'Timer is already running for ' + name; + this.started[name] = Date.now(); + }, + timeEnd: function StatTimer_timeEnd(name) { + if (!this.enabled) + return; + if (!(name in this.started)) + throw 'Timer has not been started for ' + name; + this.times.push({ + 'name': name, + 'start': this.started[name], + 'end': Date.now() + }); + // Remove timer from started so it can be called again. + delete this.started[name]; + }, + toString: function StatTimer_toString() { + var times = this.times; + var out = ''; + // Find the longest name for padding purposes. + var longest = 0; + for (var i = 0, ii = times.length; i < ii; ++i) { + var name = times[i]['name']; + if (name.length > longest) + longest = name.length; + } + for (var i = 0, ii = times.length; i < ii; ++i) { + var span = times[i]; + var duration = span.end - span.start; + out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; + } + return out; + } + }; + return StatTimer; +})(); diff --git a/apps/files_pdfviewer/js/pdfjs/src/utils/cffStandardStrings.js b/apps/files_pdfviewer/js/pdfjs/src/utils/cffStandardStrings.js old mode 100755 new mode 100644 diff --git a/apps/files_pdfviewer/js/pdfjs/src/utils/fonts_utils.js b/apps/files_pdfviewer/js/pdfjs/src/utils/fonts_utils.js old mode 100755 new mode 100644 index 2a1f0ea72ae..65c02fce277 --- a/apps/files_pdfviewer/js/pdfjs/src/utils/fonts_utils.js +++ b/apps/files_pdfviewer/js/pdfjs/src/utils/fonts_utils.js @@ -122,9 +122,9 @@ function readFontDictData(aString, aMap) { token = ''; var parsed = false; while (!parsed) { - var byte = aString[i++]; + var octet = aString[i++]; - var nibbles = [parseInt(byte / 16, 10), parseInt(byte % 16, 10)]; + var nibbles = [parseInt(octet / 16, 10), parseInt(octet % 16, 10)]; for (var j = 0; j < nibbles.length; j++) { var nibble = nibbles[j]; switch (nibble) { @@ -336,7 +336,7 @@ var Type2Parser = function type2Parser(aFilePath) { var privateDict = []; for (var i = 0; i < priv.size; i++) privateDict.push(aStream.getByte()); - dump('private:' + privateDict); + dump('privateData:' + privateDict); parseAsToken(privateDict, CFFDictPrivateDataMap); for (var p in font.map) diff --git a/apps/files_pdfviewer/js/pdfjs/src/worker.js b/apps/files_pdfviewer/js/pdfjs/src/worker.js old mode 100755 new mode 100644 index 67f1bf658e1..42bd610503f --- a/apps/files_pdfviewer/js/pdfjs/src/worker.js +++ b/apps/files_pdfviewer/js/pdfjs/src/worker.js @@ -6,6 +6,8 @@ function MessageHandler(name, comObj) { this.name = name; this.comObj = comObj; + this.callbackIndex = 1; + var callbacks = this.callbacks = {}; var ah = this.actionHandler = {}; ah['console_log'] = [function ahConsoleLog(data) { @@ -17,11 +19,32 @@ function MessageHandler(name, comObj) { comObj.onmessage = function messageHandlerComObjOnMessage(event) { var data = event.data; - if (data.action in ah) { + if (data.isReply) { + var callbackId = data.callbackId; + if (data.callbackId in callbacks) { + var callback = callbacks[callbackId]; + delete callbacks[callbackId]; + callback(data.data); + } else { + error('Cannot resolve callback ' + callbackId); + } + } else if (data.action in ah) { var action = ah[data.action]; - action[0].call(action[1], data.data); + if (data.callbackId) { + var promise = new Promise(); + promise.then(function(resolvedData) { + comObj.postMessage({ + isReply: true, + callbackId: data.callbackId, + data: resolvedData + }); + }); + action[0].call(action[1], data.data, promise); + } else { + action[0].call(action[1], data.data); + } } else { - throw 'Unkown action from worker: ' + data.action; + error('Unkown action from worker: ' + data.action); } }; } @@ -30,44 +53,47 @@ MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { - throw 'There is already an actionName called "' + actionName + '"'; + error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, - - send: function messageHandlerSend(actionName, data) { - this.comObj.postMessage({ + /** + * Sends a message to the comObj to invoke the action with the supplied data. + * @param {String} actionName Action to call. + * @param {JSON} data JSON data to send. + * @param {function} [callback] Optional callback that will handle a reply. + */ + send: function messageHandlerSend(actionName, data, callback) { + var message = { action: actionName, data: data - }); + }; + if (callback) { + var callbackId = this.callbackIndex++; + this.callbacks[callbackId] = callback; + message.callbackId = callbackId; + } + this.comObj.postMessage(message); } }; var WorkerMessageHandler = { setup: function wphSetup(handler) { - var pdfDoc = null; + var pdfModel = null; handler.on('test', function wphSetupTest(data) { handler.send('test', data instanceof Uint8Array); }); - handler.on('workerSrc', function wphSetupWorkerSrc(data) { - // In development, the `workerSrc` message is handled in the - // `worker_loader.js` file. In production the workerProcessHandler is - // called for this. This servers as a dummy to prevent calling an - // undefined action `workerSrc`. - }); - handler.on('doc', function wphSetupDoc(data) { // Create only the model of the PDFDoc, which is enough for // processing the content of the pdf. - pdfDoc = new PDFDocModel(new Stream(data)); + pdfModel = new PDFDocModel(new Stream(data)); }); handler.on('page_request', function wphSetupPageRequest(pageNum) { pageNum = parseInt(pageNum); - var page = pdfDoc.getPage(pageNum); // The following code does quite the same as // Page.prototype.startRendering, but stops at one point and sends the @@ -77,12 +103,42 @@ var WorkerMessageHandler = { var start = Date.now(); var dependency = []; + var operatorList = null; + try { + var page = pdfModel.getPage(pageNum); + // Pre compile the pdf page and fetch the fonts/images. + operatorList = page.getOperatorList(handler, dependency); + } catch (e) { + var minimumStackMessage = + 'worker.js: while trying to getPage() and getOperatorList()'; + + // Turn the error into an obj that can be serialized + if (typeof e === 'string') { + e = { + message: e, + stack: minimumStackMessage + }; + } else if (typeof e === 'object') { + e = { + message: e.message || e.toString(), + stack: e.stack || minimumStackMessage + }; + } else { + e = { + message: 'Unknown exception type: ' + (typeof e), + stack: minimumStackMessage + }; + } - // Pre compile the pdf page and fetch the fonts/images. - var IRQueue = page.getIRQueue(handler, dependency); + handler.send('page_error', { + pageNum: pageNum, + error: e + }); + return; + } - console.log('page=%d - getIRQueue: time=%dms, len=%d', pageNum, - Date.now() - start, IRQueue.fnArray.length); + console.log('page=%d - getOperatorList: time=%dms, len=%d', pageNum, + Date.now() - start, operatorList.fnArray.length); // Filter the dependecies for fonts. var fonts = {}; @@ -95,59 +151,10 @@ var WorkerMessageHandler = { handler.send('page', { pageNum: pageNum, - IRQueue: IRQueue, + operatorList: operatorList, depFonts: Object.keys(fonts) }); }, this); - - handler.on('font', function wphSetupFont(data) { - var objId = data[0]; - var name = data[1]; - var file = data[2]; - var properties = data[3]; - - var font = { - name: name, - file: file, - properties: properties - }; - - // Some fonts don't have a file, e.g. the build in ones like Arial. - if (file) { - var fontFileDict = new Dict(); - fontFileDict.map = file.dict.map; - - var fontFile = new Stream(file.bytes, file.start, - file.end - file.start, fontFileDict); - - // Check if this is a FlateStream. Otherwise just use the created - // Stream one. This makes complex_ttf_font.pdf work. - var cmf = file.bytes[0]; - if ((cmf & 0x0f) == 0x08) { - font.file = new FlateStream(fontFile); - } else { - font.file = fontFile; - } - } - - var obj = new Font(font.name, font.file, font.properties); - - var str = ''; - var objData = obj.data; - if (objData) { - var length = objData.length; - for (var j = 0; j < length; ++j) - str += String.fromCharCode(objData[j]); - } - - obj.str = str; - - // Remove the data array form the font object, as it's not needed - // anymore as we sent over the ready str. - delete obj.data; - - handler.send('font_ready', [objId, obj]); - }); } }; @@ -168,6 +175,7 @@ var workerConsole = { action: 'console_error', data: args }); + throw 'pdf.js execution error'; }, time: function time(name) { @@ -177,7 +185,7 @@ var workerConsole = { timeEnd: function timeEnd(name) { var time = consoleTimer[name]; if (time == null) { - throw 'Unkown timer name ' + name; + error('Unkown timer name ' + name); } this.log('Timer:', name, Date.now() - time); } diff --git a/apps/files_pdfviewer/js/pdfjs/src/worker_loader.js b/apps/files_pdfviewer/js/pdfjs/src/worker_loader.js old mode 100755 new mode 100644 index 7141fa3e39d..69eb1414f0b --- a/apps/files_pdfviewer/js/pdfjs/src/worker_loader.js +++ b/apps/files_pdfviewer/js/pdfjs/src/worker_loader.js @@ -3,51 +3,32 @@ 'use strict'; -function onMessageLoader(evt) { - // Reset the `onmessage` function as it was only set to call - // this function the first time a message is passed to the worker - // but shouldn't get called anytime afterwards. - this.onmessage = null; - - if (evt.data.action !== 'workerSrc') { - throw 'Worker expects first message to be `workerSrc`'; - } - - // Content of `PDFJS.workerSrc` as defined on the main thread. - var workerSrc = evt.data.data; - - // Extract the directory that contains the source files to load. - // Assuming the source files have the same relative possition as the - // `workerSrc` file. - var dir = workerSrc.substring(0, workerSrc.lastIndexOf('/') + 1); - - // List of files to include; - var files = [ - 'core.js', - 'util.js', - 'canvas.js', - 'obj.js', - 'function.js', - 'charsets.js', - 'cidmaps.js', - 'colorspace.js', - 'crypto.js', - 'evaluator.js', - 'fonts.js', - 'glyphlist.js', - 'image.js', - 'metrics.js', - 'parser.js', - 'pattern.js', - 'stream.js', - 'worker.js', - '../external/jpgjs/jpg.js' - ]; - - // Load all the files. - for (var i = 0; i < files.length; i++) { - importScripts(dir + files[i]); - } +// List of files to include; +var files = [ + 'core.js', + 'util.js', + 'canvas.js', + 'obj.js', + 'function.js', + 'charsets.js', + 'cidmaps.js', + 'colorspace.js', + 'crypto.js', + 'evaluator.js', + 'fonts.js', + 'glyphlist.js', + 'image.js', + 'metrics.js', + 'parser.js', + 'pattern.js', + 'stream.js', + 'worker.js', + '../external/jpgjs/jpg.js', + 'jpx.js', + 'bidi.js' +]; + +// Load all the files. +for (var i = 0; i < files.length; i++) { + importScripts(files[i]); } - -this.onmessage = onMessageLoader; diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/bookmark.svg b/apps/files_pdfviewer/js/pdfjs/web/images/bookmark.svg old mode 100755 new mode 100644 index 2c1fa130d17..bee6efefdfb --- a/apps/files_pdfviewer/js/pdfjs/web/images/bookmark.svg +++ b/apps/files_pdfviewer/js/pdfjs/web/images/bookmark.svg @@ -20,7 +20,8 @@ height="48.000000px" width="48.000000px" inkscape:output_extension="org.inkscape.output.svg.inkscape" - version="1.1"> + version="1.1" + viewbox="0 0 48 48"> + + diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/comment.svg b/apps/files_pdfviewer/js/pdfjs/web/images/comment.svg new file mode 100644 index 00000000000..84feef1c89f --- /dev/null +++ b/apps/files_pdfviewer/js/pdfjs/web/images/comment.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/document-print.svg b/apps/files_pdfviewer/js/pdfjs/web/images/document-print.svg old mode 100755 new mode 100644 index 0b8837ba1df..4d062fbb69a --- a/apps/files_pdfviewer/js/pdfjs/web/images/document-print.svg +++ b/apps/files_pdfviewer/js/pdfjs/web/images/document-print.svg @@ -16,7 +16,8 @@ id="svg2994" height="48px" width="48px" - inkscape:output_extension="org.inkscape.output.svg.inkscape"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/pin-up.svg b/apps/files_pdfviewer/js/pdfjs/web/images/pin-up.svg new file mode 100644 index 00000000000..e55cec7a044 --- /dev/null +++ b/apps/files_pdfviewer/js/pdfjs/web/images/pin-up.svg @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/zoom-in.svg b/apps/files_pdfviewer/js/pdfjs/web/images/zoom-in.svg old mode 100755 new mode 100644 index 6eaed448110..48ee42dd9b8 --- a/apps/files_pdfviewer/js/pdfjs/web/images/zoom-in.svg +++ b/apps/files_pdfviewer/js/pdfjs/web/images/zoom-in.svg @@ -16,7 +16,8 @@ inkscape:version="0.46" sodipodi:docbase="/home/jimmac/src/cvs/tango-icon-theme/scalable/actions" sodipodi:docname="list-add.svg" - inkscape:output_extension="org.inkscape.output.svg.inkscape"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> diff --git a/apps/files_pdfviewer/js/pdfjs/web/images/zoom-out.svg b/apps/files_pdfviewer/js/pdfjs/web/images/zoom-out.svg old mode 100755 new mode 100644 index 5f109a05c38..eb13b60e376 --- a/apps/files_pdfviewer/js/pdfjs/web/images/zoom-out.svg +++ b/apps/files_pdfviewer/js/pdfjs/web/images/zoom-out.svg @@ -16,7 +16,8 @@ inkscape:version="0.46" sodipodi:docbase="/home/jimmac/src/cvs/tango-icon-theme/scalable/actions" sodipodi:docname="list-remove.svg" - inkscape:output_extension="org.inkscape.output.svg.inkscape"> + inkscape:output_extension="org.inkscape.output.svg.inkscape" + viewbox="0 0 48 48"> -- GitLab From 738601f4fe2e899fbb77564fd71f7d9f14cffb3f Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 15 Apr 2012 14:01:59 +0000 Subject: [PATCH 140/430] Remove google web font --- apps/files_texteditor/js/aceeditor/ace.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/files_texteditor/js/aceeditor/ace.js b/apps/files_texteditor/js/aceeditor/ace.js index d8f08d58878..8315fd13f75 100644 --- a/apps/files_texteditor/js/aceeditor/ace.js +++ b/apps/files_texteditor/js/aceeditor/ace.js @@ -1 +1 @@ -(function(){function g(a){var e=function(a,b){return d("",a,b)};e.packaged=!0;var f=b;a&&(b[a]||(b[a]={}),f=b[a]),f.define&&(c.original=f.define),f.define=c,f.require&&(d.original=f.require),f.require=e}var a="",b=function(){return this}();if(typeof requirejs!="undefined")return;var c=function(a,b,d){if(typeof a!="string"){c.original?c.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(d=b),c.modules||(c.modules={}),c.modules[a]=d},d=function(a,b,c){if(Object.prototype.toString.call(b)==="[object Array]"){var e=[];for(var g=0,h=b.length;g1&&h(b,"")>-1&&(i=RegExp(this.source,d.replace.call(g(this),"g","")),d.replace.call(a.slice(b.index),i,function(){for(var a=1;ab.index&&this.lastIndex--}return b},f||(RegExp.prototype.test=function(a){var b=d.exec.call(this,a);return b&&this.global&&!b[0].length&&this.lastIndex>b.index&&this.lastIndex--,!!b})}),define("ace/lib/es5-shim",["require","exports","module"],function(a,b,c){function p(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(b){}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if(typeof b!="function")throw new TypeError;var c=g.call(arguments,1),d=function(){if(this instanceof d){var e=function(){};e.prototype=b.prototype;var f=new e,h=b.apply(f,c.concat(g.call(arguments)));return h!==null&&Object(h)===h?h:f}return b.apply(a,c.concat(g.call(arguments)))};return d});var d=Function.prototype.call,e=Array.prototype,f=Object.prototype,g=e.slice,h=d.bind(f.toString),i=d.bind(f.hasOwnProperty),j,k,l,m,n;if(n=i(f,"__defineGetter__"))j=d.bind(f.__defineGetter__),k=d.bind(f.__defineSetter__),l=d.bind(f.__lookupGetter__),m=d.bind(f.__lookupSetter__);Array.isArray||(Array.isArray=function(a){return h(a)=="[object Array]"}),Array.prototype.forEach||(Array.prototype.forEach=function(a){var b=G(this),c=arguments[1],d=0,e=b.length>>>0;if(h(a)!="[object Function]")throw new TypeError;while(d>>0,d=Array(c),e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=[],e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d=0,e;if(arguments.length>=2)e=arguments[1];else do{if(d in b){e=b[d++];break}if(++d>=c)throw new TypeError}while(!0);for(;d>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d,e=c-1;if(arguments.length>=2)d=arguments[1];else do{if(e in b){d=b[e--];break}if(--e<0)throw new TypeError}while(!0);do e in this&&(d=a.call(void 0,d,b[e],e,b));while(e--);return d}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=G(this),c=b.length>>>0;if(!c)return-1;var d=0;arguments.length>1&&(d=E(arguments[1])),d=d>=0?d:Math.max(0,c+d);for(;d>>0;if(!c)return-1;var d=c-1;arguments.length>1&&(d=Math.min(d,E(arguments[1]))),d=d>=0?d:c-Math.abs(d);for(;d>=0;d--)if(d in b&&a===b[d])return d;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(a){return a.__proto__||(a.constructor?a.constructor.prototype:f)});if(!Object.getOwnPropertyDescriptor){var o="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(a,b){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(o+a);if(!i(a,b))return;var c,d,e;c={enumerable:!0,configurable:!0};if(n){var g=a.__proto__;a.__proto__=f;var d=l(a,b),e=m(a,b);a.__proto__=g;if(d||e)return d&&(c.get=d),e&&(c.set=e),c}return c.value=a[b],c}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(a){return Object.keys(a)}),Object.create||(Object.create=function(a,b){var c;if(a===null)c={"__proto__":null};else{if(typeof a!="object")throw new TypeError("typeof prototype["+typeof a+"] != 'object'");var d=function(){};d.prototype=a,c=new d,c.__proto__=a}return b!==void 0&&Object.defineProperties(c,b),c});if(Object.defineProperty){var q=p({}),r=typeof document=="undefined"||p(document.createElement("div"));if(!q||!r)var s=Object.defineProperty}if(!Object.defineProperty||s){var t="Property description must be an object: ",u="Object.defineProperty called on non-object: ",v="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(a,b,c){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(u+a);if(typeof c!="object"&&typeof c!="function"||c===null)throw new TypeError(t+c);if(s)try{return s.call(Object,a,b,c)}catch(d){}if(i(c,"value"))if(n&&(l(a,b)||m(a,b))){var e=a.__proto__;a.__proto__=f,delete a[b],a[b]=c.value,a.__proto__=e}else a[b]=c.value;else{if(!n)throw new TypeError(v);i(c,"get")&&j(a,b,c.get),i(c,"set")&&k(a,b,c.set)}return a}}Object.defineProperties||(Object.defineProperties=function(a,b){for(var c in b)i(b,c)&&Object.defineProperty(a,c,b[c]);return a}),Object.seal||(Object.seal=function(a){return a}),Object.freeze||(Object.freeze=function(a){return a});try{Object.freeze(function(){})}catch(w){Object.freeze=function(a){return function b(b){return typeof b=="function"?b:a(b)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(a){return a}),Object.isSealed||(Object.isSealed=function(a){return!1}),Object.isFrozen||(Object.isFrozen=function(a){return!1}),Object.isExtensible||(Object.isExtensible=function(a){if(Object(a)===a)throw new TypeError;var b="";while(i(a,b))b+="?";a[b]=!0;var c=i(a,b);return delete a[b],c});if(!Object.keys){var x=!0,y=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],z=y.length;for(var A in{toString:null})x=!1;Object.keys=function bd(a){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.keys called on a non-object");var bd=[];for(var b in a)i(a,b)&&bd.push(b);if(x)for(var c=0,d=z;c9999?"+":"")+("00000"+Math.abs(d)).slice(0<=d&&d<=9999?-4:-6),b=a.length;while(b--)c=a[b],c<10&&(a[b]="0"+c);return d+"-"+a.slice(0,2).join("-")+"T"+a.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};Date.now||(Date.now=function(){return(new Date).getTime()}),Date.prototype.toJSON||(Date.prototype.toJSON=function(a){if(typeof this.toISOString!="function")throw new TypeError;return this.toISOString()}),Date.parse("+275760-09-13T00:00:00.000Z")!==864e13&&(Date=function(a){var b=function e(b,c,d,f,g,h,i){var j=arguments.length;if(this instanceof a){var k=j==1&&String(b)===b?new a(e.parse(b)):j>=7?new a(b,c,d,f,g,h,i):j>=6?new a(b,c,d,f,g,h):j>=5?new a(b,c,d,f,g):j>=4?new a(b,c,d,f):j>=3?new a(b,c,d):j>=2?new a(b,c):j>=1?new a(b):new a;return k.constructor=e,k}return a.apply(this,arguments)},c=new RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$");for(var d in a)b[d]=a[d];return b.now=a.now,b.UTC=a.UTC,b.prototype=a.prototype,b.prototype.constructor=b,b.parse=function f(b){var d=c.exec(b);if(d){d.shift();for(var e=1;e<7;e++)d[e]=+(d[e]||(e<3?1:0)),e==1&&d[e]--;var f=+d.pop(),g=+d.pop(),h=d.pop(),i=0;if(h){if(g>23||f>59)return NaN;i=(g*60+f)*6e4*(h=="+"?-1:1)}var j=+d[0];return 0<=j&&j<=99?(d[0]=j+400,a.UTC.apply(this,d)+i-126227808e5):a.UTC.apply(this,d)+i}return a.parse.apply(this,arguments)},b}(Date));var B="\t\n \f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||B.trim()){B="["+B+"]";var C=new RegExp("^"+B+B+"*"),D=new RegExp(B+B+"*$");String.prototype.trim=function(){return String(this).replace(C,"").replace(D,"")}}var E=function(a){return a=+a,a!==a?a=0:a!==0&&a!==1/0&&a!==-Infinity&&(a=(a>0||-1)*Math.floor(Math.abs(a))),a},F="a"[0]!="a",G=function(a){if(a==null)throw new TypeError;return F&&typeof a=="string"&&a?a.split(""):Object(a)}}),define("ace/lib/dom",["require","exports","module"],function(a,b,c){"use strict";var d="http://www.w3.org/1999/xhtml";b.createElement=function(a,b){return document.createElementNS?document.createElementNS(b||d,a):document.createElement(a)},b.setText=function(a,b){a.innerText!==undefined&&(a.innerText=b),a.textContent!==undefined&&(a.textContent=b)},b.hasCssClass=function(a,b){var c=a.className.split(/\s+/g);return c.indexOf(b)!==-1},b.addCssClass=function(a,c){b.hasCssClass(a,c)||(a.className+=" "+c)},b.removeCssClass=function(a,b){var c=a.className.split(/\s+/g);for(;;){var d=c.indexOf(b);if(d==-1)break;c.splice(d,1)}a.className=c.join(" ")},b.toggleCssClass=function(a,b){var c=a.className.split(/\s+/g),d=!0;for(;;){var e=c.indexOf(b);if(e==-1)break;d=!1,c.splice(e,1)}return d&&c.push(b),a.className=c.join(" "),d},b.setCssClass=function(a,c,d){d?b.addCssClass(a,c):b.removeCssClass(a,c)},b.hasCssString=function(a,b){var c=0,d;b=b||document;if(b.createStyleSheet&&(d=b.styleSheets)){while(cd&&(d=Math.abs(a.wheelDeltaY));if(d>5e3)var b=400;else var b=8;a.wheelDeltaX!==undefined?(a.wheelX=-a.wheelDeltaX/b,a.wheelY=-a.wheelDeltaY/b):(a.wheelX=0,a.wheelY=-a.wheelDelta/b)}else a.axis&&a.axis==a.HORIZONTAL_AXIS?(a.wheelX=(a.detail||0)*5,a.wheelY=0):(a.wheelX=0,a.wheelY=(a.detail||0)*5);c(a)};b.addListener(a,"DOMMouseScroll",e),b.addListener(a,"mousewheel",e)},b.addMultiMouseDownListener=function(a,c,d,f,g){var h=0,i,j,k=function(a){h+=1,h==1&&(i=a.clientX,j=a.clientY,setTimeout(function(){h=0},f||600));var e=b.getButton(a)==c;if(!e||Math.abs(a.clientX-i)>5||Math.abs(a.clientY-j)>5)h=0;h==d&&(h=0,g(a));if(e)return b.preventDefault(a)};b.addListener(a,"mousedown",k),e.isOldIE&&b.addListener(a,"dblclick",k)},b.addCommandKeyListener=function(a,c){var d=b.addListener;if(e.isOldGecko){var f=null;d(a,"keydown",function(a){f=a.keyCode}),d(a,"keypress",function(a){return g(c,a,f)})}else{var h=null;d(a,"keydown",function(a){return h=a.keyIdentifier||a.keyCode,g(c,a,a.keyCode)}),e.isMac&&e.isOpera&&d(a,"keypress",function(a){var b=a.keyIdentifier||a.keyCode;if(h!==b)return g(c,a,h);h=null})}};if(window.postMessage){var h=1;b.nextTick=function(a,c){c=c||window;var d="zero-timeout-message-"+h;b.addListener(c,"message",function e(f){f.data==d&&(b.stopPropagation(f),b.removeListener(c,"message",e),a())}),c.postMessage(d,"*")}}else b.nextTick=function(a,b){b=b||window,window.setTimeout(a,0)}}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(a,b,c){"use strict";var d=a("./oop"),e=function(){var a={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,meta:8,command:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:'"'}};for(var b in a.FUNCTION_KEYS){var c=a.FUNCTION_KEYS[b].toUpperCase();a[c]=parseInt(b,10)}return d.mixin(a,a.MODIFIER_KEYS),d.mixin(a,a.PRINTABLE_KEYS),d.mixin(a,a.FUNCTION_KEYS),a}();d.mixin(b,e),b.keyCodeToString=function(a){return(e[a]||String.fromCharCode(a)).toLowerCase()}}),define("ace/lib/oop",["require","exports","module"],function(a,b,c){"use strict",b.inherits=function(){var a=function(){};return function(b,c){a.prototype=c.prototype,b.super_=c.prototype,b.prototype=new a,b.prototype.constructor=b}}(),b.mixin=function(a,b){for(var c in b)a[c]=b[c]},b.implement=function(a,c){b.mixin(a,c)}}),define("ace/lib/useragent",["require","exports","module"],function(a,b,c){"use strict";var d=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),e=navigator.userAgent;b.isWin=d=="win",b.isMac=d=="mac",b.isLinux=d=="linux",b.isIE=navigator.appName=="Microsoft Internet Explorer"&&parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]),b.isOldIE=b.isIE&&b.isIE<9,b.isGecko=b.isMozilla=window.controllers&&window.navigator.product==="Gecko",b.isOldGecko=b.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,b.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",b.isWebKit=parseFloat(e.split("WebKit/")[1])||undefined,b.isChrome=parseFloat(e.split(" Chrome/")[1])||undefined,b.isAIR=e.indexOf("AdobeAIR")>=0,b.isIPad=e.indexOf("iPad")>=0,b.isTouchPad=e.indexOf("TouchPad")>=0,b.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},b.getOS=function(){return b.isMac?b.OS.MAC:b.isLinux?b.OS.LINUX:b.OS.WINDOWS}}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands"],function(a,b,c){"use strict",a("./lib/fixoldbrowsers");var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/useragent"),g=a("./keyboard/textinput").TextInput,h=a("./mouse/mouse_handler").MouseHandler,i=a("./mouse/fold_handler").FoldHandler,j=a("./keyboard/keybinding").KeyBinding,k=a("./edit_session").EditSession,l=a("./search").Search,m=a("./range").Range,n=a("./lib/event_emitter").EventEmitter,o=a("./commands/command_manager").CommandManager,p=a("./commands/default_commands").commands,q=function(a,b){var c=a.getContainerElement();this.container=c,this.renderer=a,this.textInput=new g(a.getTextAreaContainer(),this),this.keyBinding=new j(this),f.isIPad||(this.$mouseHandler=new h(this),new i(this)),this.$blockScrolling=0,this.$search=(new l).set({wrap:!0}),this.commands=new o(f.isMac?"mac":"win",p),this.setSession(b||new k(""))};((function(){d.implement(this,n),this.setKeyboardHandler=function(a){this.keyBinding.setKeyboardHandler(a)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(a){if(this.session==a)return;if(this.session){var b=this.session;this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeLeftTop",this.$onScrollLeftChange);var c=this.session.getSelection();c.removeEventListener("changeCursor",this.$onCursorChange),c.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=a,this.$onDocumentChange=this.onDocumentChange.bind(this),a.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(a),this.$onChangeMode=this.onChangeMode.bind(this),a.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),a.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.updateText.bind(this.renderer),a.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),a.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),a.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),a.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=a.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.onCursorChange(),this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull(),this._emit("changeSession",{session:a,oldSession:b})},this.getSession=function(){return this.session},this.getSelection=function(){return this.selection},this.resize=function(){this.renderer.onResize()},this.setTheme=function(a){this.renderer.setTheme(a)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(a){this.renderer.setStyle(a)},this.unsetStyle=function(a){this.renderer.unsetStyle(a)},this.setFontSize=function(a){this.container.style.fontSize=a},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var a=this;this.$highlightPending=!0,setTimeout(function(){a.$highlightPending=!1;var b=a.session.findMatchingBracket(a.getCursorPosition());if(b){var c=new m(b.row,b.column,b.row,b.column+1);a.session.$bracketHighlight=a.session.addMarker(c,"ace_bracket","text")}},10)},this.focus=function(){var a=this;setTimeout(function(){a.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.onDocumentChange=function(a){var b=a.data,c=b.range,d;c.start.row==c.end.row&&b.action!="insertLines"&&b.action!="removeLines"?d=c.end.row:d=Infinity,this.renderer.updateLines(c.start.row,d),this._emit("change",a),this.onCursorChange()},this.onTokenizerUpdate=function(a){var b=a.data;this.renderer.updateLines(b.first,b.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.renderer.updateCursor(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.renderer.moveTextAreaToCursor(this.textInput.getElement()),this.$highlightBrackets(),this.$updateHighlightActiveLine()},this.$updateHighlightActiveLine=function(){var a=this.getSession();a.$highlightLineMarker&&a.removeMarker(a.$highlightLineMarker),a.$highlightLineMarker=null;if(this.getHighlightActiveLine()&&(this.getSelectionStyle()!="line"||!this.selection.isMultiLine())){var b=this.getCursorPosition(),c=this.session.getFoldLine(b.row),d;c?d=new m(c.start.row,0,c.end.row+1,0):d=new m(b.row,0,b.row+1,0),a.$highlightLineMarker=a.addMarker(d,"ace_active_line","background")}},this.onSelectionChange=function(a){var b=this.getSession();b.$selectionMarker&&b.removeMarker(b.$selectionMarker),b.$selectionMarker=null;if(!this.selection.isEmpty()){var c=this.selection.getRange(),d=this.getSelectionStyle();b.$selectionMarker=b.addMarker(c,"ace_selection",d)}else this.$updateHighlightActiveLine();this.$highlightSelectedWord&&this.session.getMode().highlightSelection(this)},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.setBreakpoints(this.session.getBreakpoints())},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(){this.renderer.updateText()},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getCopyText=function(){var a="";return this.selection.isEmpty()||(a=this.session.getTextRange(this.getSelectionRange())),this._emit("copy",a),a},this.onCut=function(){if(this.$readOnly)return;var a=this.getSelectionRange();this._emit("cut",a),this.selection.isEmpty()||(this.session.remove(a),this.clearSelection())},this.insert=function(a){var b=this.session,c=b.getMode(),d=this.getCursorPosition();if(this.getBehavioursEnabled()){var e=c.transformAction(b.getState(d.row),"insertion",this,b,a);e&&(a=e.text)}a=a.replace("\t",this.session.getTabString());if(!this.selection.isEmpty())d=this.session.remove(this.getSelectionRange()),this.clearSelection();else if(this.session.getOverwrite()){var f=new m.fromPoints(d,d);f.end.column+=a.length,this.session.remove(f)}this.clearSelection();var g=d.column,h=b.getState(d.row),i=c.checkOutdent(h,b.getLine(d.row),a),j=b.getLine(d.row),k=c.getNextLineIndent(h,j.slice(0,d.column),b.getTabString()),l=b.insert(d,a);e&&e.selection&&(e.selection.length==2?this.selection.setSelectionRange(new m(d.row,g+e.selection[0],d.row,g+e.selection[1])):this.selection.setSelectionRange(new m(d.row+e.selection[0],e.selection[1],d.row+e.selection[2],e.selection[3])));var h=b.getState(d.row);if(b.getDocument().isNewLine(a)){this.moveCursorTo(d.row+1,0);var n=b.getTabSize(),o=Number.MAX_VALUE;for(var p=d.row+1;p<=l.row;++p){var q=0;j=b.getLine(p);for(var r=0;r0;++r)j.charAt(r)=="\t"?s-=n:j.charAt(r)==" "&&(s-=1);b.remove(new m(p,0,p,r))}b.indentRows(d.row+1,l.row,k)}i&&c.autoOutdent(h,b,d.row)},this.onTextInput=function(a,b){b&&this._emit("paste",a),this.keyBinding.onTextInput(a,b)},this.onCommandKey=function(a,b,c){this.keyBinding.onCommandKey(a,b,c)},this.setOverwrite=function(a){this.session.setOverwrite(a)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(a){this.$mouseHandler.setScrollSpeed(a)},this.getScrollSpeed=function(){return this.$mouseHandler.getScrollSpeed()},this.setDragDelay=function(a){this.$mouseHandler.setDragDelay(a)},this.getDragDelay=function(){return this.$mouseHandler.getDragDelay()},this.$selectionStyle="line",this.setSelectionStyle=function(a){if(this.$selectionStyle==a)return;this.$selectionStyle=a,this.onSelectionChange(),this._emit("changeSelectionStyle",{data:a})},this.getSelectionStyle=function(){return this.$selectionStyle},this.$highlightActiveLine=!0,this.setHighlightActiveLine=function(a){if(this.$highlightActiveLine==a)return;this.$highlightActiveLine=a,this.$updateHighlightActiveLine()},this.getHighlightActiveLine=function(){return this.$highlightActiveLine},this.$highlightSelectedWord=!0,this.setHighlightSelectedWord=function(a){if(this.$highlightSelectedWord==a)return;this.$highlightSelectedWord=a,a?this.session.getMode().highlightSelection(this):this.session.getMode().clearSelectionHighlight(this)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setShowInvisibles=function(a){if(this.getShowInvisibles()==a)return;this.renderer.setShowInvisibles(a)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setShowPrintMargin=function(a){this.renderer.setShowPrintMargin(a)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(a){this.renderer.setPrintMarginColumn(a)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.$readOnly=!1,this.setReadOnly=function(a){this.$readOnly=a},this.getReadOnly=function(){return this.$readOnly},this.$modeBehaviours=!0,this.setBehavioursEnabled=function(a){this.$modeBehaviours=a},this.getBehavioursEnabled=function(){return this.$modeBehaviours},this.setShowFoldWidgets=function(a){var b=this.renderer.$gutterLayer;if(b.getShowFoldWidgets()==a)return;this.renderer.$gutterLayer.setShowFoldWidgets(a),this.$showFoldWidgets=a,this.renderer.updateFull()},this.getShowFoldWidgets=function(){return this.renderer.$gutterLayer.getShowFoldWidgets()},this.remove=function(a){this.selection.isEmpty()&&(a=="left"?this.selection.selectLeft():this.selection.selectRight());var b=this.getSelectionRange();if(this.getBehavioursEnabled()){var c=this.session,d=c.getState(b.start.row),e=c.getMode().transformAction(d,"deletion",this,c,b);e&&(b=e)}this.session.remove(b),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var a=this.getSelectionRange();a.start.column==a.end.column&&a.start.row==a.end.row&&(a.end.column=0,a.end.row++),this.session.remove(a),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var a=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(a)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var a=this.getCursorPosition(),b=a.column;if(b===0)return;var c=this.session.getLine(a.row),d,e;b=this.getFirstVisibleRow()&&a<=this.getLastVisibleRow()},this.isRowFullyVisible=function(a){return a>=this.renderer.getFirstFullyVisibleRow()&&a<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$getPageDownRow=function(){return this.renderer.getScrollBottomRow()},this.$getPageUpRow=function(){var a=this.renderer.getScrollTopRow(),b=this.renderer.getScrollBottomRow();return a-(b-a)},this.selectPageDown=function(){var a=this.$getPageDownRow()+Math.floor(this.$getVisibleRowCount()/2);this.scrollPageDown();var b=this.getSelection(),c=this.session.documentToScreenPosition(b.getSelectionLead()),d=this.session.screenToDocumentPosition(a,c.column);b.selectTo(d.row,d.column)},this.selectPageUp=function(){var a=this.renderer.getScrollTopRow()-this.renderer.getScrollBottomRow(),b=this.$getPageUpRow()+Math.round(a/2);this.scrollPageUp();var c=this.getSelection(),d=this.session.documentToScreenPosition(c.getSelectionLead()),e=this.session.screenToDocumentPosition(b,d.column);c.selectTo(e.row,e.column)},this.gotoPageDown=function(){var a=this.$getPageDownRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.gotoPageUp=function(){var a=this.$getPageUpRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.scrollPageDown=function(){this.scrollToRow(this.$getPageDownRow())},this.scrollPageUp=function(){this.renderer.scrollToRow(this.$getPageUpRow())},this.scrollToRow=function(a){this.renderer.scrollToRow(a)},this.scrollToLine=function(a,b){this.renderer.scrollToLine(a,b)},this.centerSelection=function(){var a=this.getSelectionRange(),b=Math.floor(a.start.row+(a.end.row-a.start.row)/2);this.renderer.scrollToLine(b,!0)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(a,b){this.selection.moveCursorTo(a,b)},this.moveCursorToPosition=function(a){this.selection.moveCursorToPosition(a)},this.jumpToMatching=function(){var a=this.getCursorPosition(),b=this.session.findMatchingBracket(a);b||(a.column+=1,b=this.session.findMatchingBracket(a)),b||(a.column-=2,b=this.session.findMatchingBracket(a)),b&&(this.clearSelection(),this.moveCursorTo(b.row,b.column))},this.gotoLine=function(a,b){this.selection.clearSelection(),this.session.unfold({row:a-1,column:b||0}),this.$blockScrolling+=1,this.moveCursorTo(a-1,b||0),this.$blockScrolling-=1,this.isRowFullyVisible(this.getCursorPosition().row)||this.scrollToLine(a,!0)},this.navigateTo=function(a,b){this.clearSelection(),this.moveCursorTo(a,b)},this.navigateUp=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(-a,0)},this.navigateDown=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(a,0)},this.navigateLeft=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().start;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().end;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(a,b){b&&this.$search.set(b);var c=this.$search.find(this.session);if(!c)return;this.$tryReplace(c,a),c!==null&&this.selection.setSelectionRange(c)},this.replaceAll=function(a,b){b&&this.$search.set(b);var c=this.$search.findAll(this.session);if(!c.length)return;var d=this.getSelectionRange();this.clearSelection(),this.selection.moveCursorTo(0,0),this.$blockScrolling+=1;for(var e=c.length-1;e>=0;--e)this.$tryReplace(c[e],a);this.selection.setSelectionRange(d),this.$blockScrolling-=1},this.$tryReplace=function(a,b){var c=this.session.getTextRange(a);return b=this.$search.replace(c,b),b!==null?(a.end=this.session.replace(a,b),a):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(a,b){this.clearSelection(),b=b||{},b.needle=a,this.$search.set(b),this.$find()},this.findNext=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!1),this.$search.set(a),this.$find()},this.findPrevious=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!0),this.$search.set(a),this.$find()},this.$find=function(a){this.selection.isEmpty()||this.$search.set({needle:this.session.getTextRange(this.getSelectionRange())}),typeof a!="undefined"&&this.$search.set({backwards:a});var b=this.$search.find(this.session);b&&(this.session.unfold(b),this.gotoLine(b.end.row+1,b.end.column),this.selection.setSelectionRange(b))},this.undo=function(){this.session.getUndoManager().undo()},this.redo=function(){this.session.getUndoManager().redo()},this.destroy=function(){this.renderer.destroy()}})).call(q.prototype),b.Editor=q}),define("ace/lib/lang",["require","exports","module"],function(a,b,c){"use strict",b.stringReverse=function(a){return a.split("").reverse().join("")},b.stringRepeat=function(a,b){return(new Array(b+1)).join(a)};var d=/^\s\s*/,e=/\s\s*$/;b.stringTrimLeft=function(a){return a.replace(d,"")},b.stringTrimRight=function(a){return a.replace(e,"")},b.copyObject=function(a){var b={};for(var c in a)b[c]=a[c];return b},b.copyArray=function(a){var b=[];for(var c=0,d=a.length;c128)return;setTimeout(function(){h||m()},0)},p=function(a){h=!0,b.onCompositionStart(),e.isGecko||setTimeout(q,0)},q=function(){if(!h)return;b.onCompositionUpdate(c.value)},r=function(a){h=!1,b.onCompositionEnd()},s=function(a){i=!0;var d=b.getCopyText();d?c.value=d:a.preventDefault(),l(),setTimeout(function(){m()},0)},t=function(a){i=!0;var d=b.getCopyText();d?(c.value=d,b.onCut()):a.preventDefault(),l(),setTimeout(function(){m()},0)};d.addCommandKeyListener(c,b.onCommandKey.bind(b));if(e.isOldIE){var u={13:1,27:1};d.addListener(c,"keyup",function(a){h&&(!c.value||u[a.keyCode])&&setTimeout(r,0);if((c.value.charCodeAt(0)|0)<129)return;h?q():p()})}"onpropertychange"in c&&!("oninput"in c)?d.addListener(c,"propertychange",o):d.addListener(c,"input",n),d.addListener(c,"paste",function(a){j=!0,a.clipboardData&&a.clipboardData.getData?(m(a.clipboardData.getData("text/plain")),a.preventDefault()):o()}),"onbeforecopy"in c&&typeof clipboardData!="undefined"?(d.addListener(c,"beforecopy",function(a){var c=b.getCopyText();c?clipboardData.setData("Text",c):a.preventDefault()}),d.addListener(a,"keydown",function(a){if(a.ctrlKey&&a.keyCode==88){var c=b.getCopyText();c&&(clipboardData.setData("Text",c),b.onCut()),d.preventDefault(a)}})):(d.addListener(c,"copy",s),d.addListener(c,"cut",t)),d.addListener(c,"compositionstart",p),e.isGecko&&d.addListener(c,"text",q),e.isWebKit&&d.addListener(c,"keyup",q),d.addListener(c,"compositionend",r),d.addListener(c,"blur",function(){b.onBlur()}),d.addListener(c,"focus",function(){b.onFocus(),l()}),this.focus=function(){b.onFocus(),l(),c.focus()},this.blur=function(){c.blur()},this.isFocused=v,this.getElement=function(){return c},this.onContextMenu=function(a,b){a&&(k||(k=c.style.cssText),c.style.cssText="position:fixed; z-index:1000;left:"+(a.x-2)+"px; top:"+(a.y-2)+"px;"),b&&(c.value="")},this.onContextMenuClose=function(){setTimeout(function(){k&&(c.style.cssText=k,k=""),m()},0)}};b.TextInput=g}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event"],function(a,b,c){"use strict";var d=a("../lib/event"),e=a("./default_handlers").DefaultHandlers,f=a("./default_gutter_handler").GutterHandler,g=a("./mouse_event").MouseEvent,h=function(a){this.editor=a,new e(a),new f(a),d.addListener(a.container,"mousedown",function(b){return a.focus(),d.preventDefault(b)}),d.addListener(a.container,"selectstart",function(a){return d.preventDefault(a)});var b=a.renderer.getMouseEventTarget();d.addListener(b,"mousedown",this.onMouseEvent.bind(this,"mousedown")),d.addListener(b,"click",this.onMouseEvent.bind(this,"click")),d.addListener(b,"mousemove",this.onMouseMove.bind(this,"mousemove")),d.addMultiMouseDownListener(b,0,2,500,this.onMouseEvent.bind(this,"dblclick")),d.addMultiMouseDownListener(b,0,3,600,this.onMouseEvent.bind(this,"tripleclick")),d.addMultiMouseDownListener(b,0,4,600,this.onMouseEvent.bind(this,"quadclick")),d.addMouseWheelListener(a.container,this.onMouseWheel.bind(this,"mousewheel"));var c=a.renderer.$gutter;d.addListener(c,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),d.addListener(c,"click",this.onMouseEvent.bind(this,"gutterclick")),d.addListener(c,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),d.addListener(c,"mousemove",this.onMouseMove.bind(this,"gutter"))};((function(){this.$scrollSpeed=1,this.setScrollSpeed=function(a){this.$scrollSpeed=a},this.getScrollSpeed=function(){return this.$scrollSpeed},this.onMouseEvent=function(a,b){this.editor._emit(a,new g(b,this.editor))},this.$dragDelay=250,this.setDragDelay=function(a){this.$dragDelay=a},this.getDragDelay=function(){return this.$dragDelay},this.onMouseMove=function(a,b){var c=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!c||!c.length)return;this.editor._emit(a,new g(b,this.editor))},this.onMouseWheel=function(a,b){var c=new g(b,this.editor);c.speed=this.$scrollSpeed*2,c.wheelX=b.wheelX,c.wheelY=b.wheelY,this.editor._emit(a,c)}})).call(h.prototype),b.MouseHandler=h}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/event","ace/lib/dom","ace/lib/browser_focus"],function(a,b,c){function k(a){this.editor=a,this.$clickSelection=null,this.browserFocus=new f,a.setDefaultHandler("mousedown",this.onMouseDown.bind(this)),a.setDefaultHandler("dblclick",this.onDoubleClick.bind(this)),a.setDefaultHandler("tripleclick",this.onTripleClick.bind(this)),a.setDefaultHandler("quadclick",this.onQuadClick.bind(this)),a.setDefaultHandler("mousewheel",this.onScroll.bind(this))}function l(a,b,c,d){return Math.sqrt(Math.pow(c-a,2)+Math.pow(d-b,2))}"use strict";var d=a("../lib/event"),e=a("../lib/dom"),f=a("../lib/browser_focus").BrowserFocus,g=0,h=1,i=2,j=5;((function(){this.onMouseDown=function(a){function C(b){a.getShiftKey()?m.selection.selectToPosition(b):n.$clickSelection||(m.moveCursorToPosition(b),m.selection.clearSelection(b.row,b.column)),q=h}var b=a.inSelection(),c=a.pageX,f=a.pageY,k=a.getDocumentPosition(),m=this.editor,n=this,o=m.getSelectionRange(),p=o.isEmpty(),q=g;if(b&&(!this.browserFocus.isFocused()||(new Date).getTime()-this.browserFocus.lastFocus<20||!m.isFocused())){m.focus();return}var r=a.getButton();if(r!==0){p&&m.moveCursorToPosition(k),r==2&&(m.textInput.onContextMenu({x:a.clientX,y:a.clientY},p),d.capture(m.container,function(){},m.textInput.onContextMenuClose));return}b||C(k);var s=c,t=f,u=(new Date).getTime(),v,w,x,y=function(a){s=d.getDocumentX(a),t=d.getDocumentY(a)},z=function(a){clearInterval(F),q==g?C(k):q==i&&A(a),n.$clickSelection=null,q=g},A=function(a){e.removeCssClass(m.container,"ace_dragging"),m.session.removeMarker(x),m.$mouseHandler.$clickSelection||v||(m.moveCursorToPosition(k),m.selection.clearSelection(k.row,k.column));if(!v)return;if(w.contains(v.row,v.column)){v=null;return}m.clearSelection();if(a&&(a.ctrlKey||a.altKey))var b=m.session,c=b.insert(v,b.getTextRange(w));else var c=m.moveText(w,v);if(!c){v=null;return}m.selection.setSelectionRange(c)},B=function(){if(q==g){var a=l(c,f,s,t),b=(new Date).getTime();if(a>j){q=h;var d=m.renderer.screenToTextCoordinates(s,t);d.row=Math.max(0,Math.min(d.row,m.session.getLength()-1)),C(d)}else if(b-u>m.getDragDelay()){q=i,w=m.getSelectionRange();var k=m.getSelectionStyle();x=m.session.addMarker(w,"ace_selection",k),m.clearSelection(),e.addCssClass(m.container,"ace_dragging")}}q==i?E():q==h&&D()},D=function(){var a,b=m.renderer.screenToTextCoordinates(s,t);b.row=Math.max(0,Math.min(b.row,m.session.getLength()-1)),n.$clickSelection?n.$clickSelection.contains(b.row,b.column)?m.selection.setSelectionRange(n.$clickSelection):(n.$clickSelection.compare(b.row,b.column)==-1?a=n.$clickSelection.end:a=n.$clickSelection.start,m.selection.setSelectionAnchor(a.row,a.column),m.selection.selectToPosition(b)):m.selection.selectToPosition(b),m.renderer.scrollCursorIntoView()},E=function(){v=m.renderer.screenToTextCoordinates(s,t),v.row=Math.max(0,Math.min(v.row,m.session.getLength()-1)),m.moveCursorToPosition(v)};d.capture(m.container,y,z);var F=setInterval(B,20);return a.preventDefault()},this.onDoubleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectWord(),this.$clickSelection=c.getSelectionRange()},this.onTripleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectLine(),this.$clickSelection=c.getSelectionRange()},this.onQuadClick=function(a){var b=this.editor;b.selectAll(),this.$clickSelection=b.getSelectionRange()},this.onScroll=function(a){var b=this.editor;b.renderer.scrollBy(a.wheelX*a.speed,a.wheelY*a.speed);if(b.renderer.isScrollableBy(a.wheelX*a.speed,a.wheelY*a.speed))return a.preventDefault()}})).call(k.prototype),b.DefaultHandlers=k}),define("ace/lib/browser_focus",["require","exports","module","ace/lib/oop","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./oop"),e=a("./event"),f=a("./event_emitter").EventEmitter,g=function(a){a=a||window,this.lastFocus=(new Date).getTime(),this._isFocused=!0;var b=this;"onfocusin"in a.document?(e.addListener(a.document,"focusin",function(a){b._setFocused(!0)}),e.addListener(a.document,"focusout",function(a){b._setFocused(!!a.toElement)})):(e.addListener(a,"blur",function(a){b._setFocused(!1)}),e.addListener(a,"focus",function(a){b._setFocused(!0)}))};((function(){d.implement(this,f),this.isFocused=function(){return this._isFocused},this._setFocused=function(a){if(this._isFocused==a)return;a&&(this.lastFocus=(new Date).getTime()),this._isFocused=a,this._emit("changeFocus")}})).call(g.prototype),b.BrowserFocus=g}),define("ace/lib/event_emitter",["require","exports","module"],function(a,b,c){"use strict";var d={};d._emit=d._dispatchEvent=function(a,b){this._eventRegistry=this._eventRegistry||{},this._defaultHandlers=this._defaultHandlers||{};var c=this._eventRegistry[a]||[],d=this._defaultHandlers[a];if(!c.length&&!d)return;b=b||{},b.type=a,b.stopPropagation||(b.stopPropagation=function(){this.propagationStopped=!0}),b.preventDefault||(b.preventDefault=function(){this.defaultPrevented=!0});for(var e=0;e=4352&&a<=4447||a>=4515&&a<=4519||a>=4602&&a<=4607||a>=9001&&a<=9002||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12283||a>=12288&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12589||a>=12593&&a<=12686||a>=12688&&a<=12730||a>=12736&&a<=12771||a>=12784&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=13054||a>=13056&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=55216&&a<=55238||a>=55243&&a<=55291||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=65281&&a<=65376||a>=65504&&a<=65510}d.implement(this,f),this.setDocument=function(a){if(this.doc)throw new Error("Document is already set");this.doc=a,a.on("change",this.onChange.bind(this)),this.on("changeFold",this.onChangeFold.bind(this)),this.bgTokenizer&&(this.bgTokenizer.setDocument(this.getDocument()),this.bgTokenizer.start(0))},this.getDocument=function(){return this.doc},this.$resetRowCache=function(a){if(a==0){this.$rowCache=[];return}var b=this.$rowCache;for(var c=0;c=a){b.splice(c,b.length);return}},this.onChangeFold=function(a){var b=a.data;this.$resetRowCache(b.start.row)},this.onChange=function(a){var b=a.data;this.$modified=!0,this.$resetRowCache(b.range.start.row);var c=this.$updateInternalDataOnChange(a);!this.$fromUndo&&this.$undoManager&&!b.ignore&&(this.$deltasDoc.push(b),c&&c.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:c}),this.$informUndoManager.schedule()),this.bgTokenizer.start(b.range.start.row),this._emit("change",a)},this.setValue=function(a){this.doc.setValue(a),this.selection.moveCursorTo(0,0),this.selection.clearSelection(),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(a){return this.bgTokenizer.getState(a)},this.getTokens=function(a,b){return this.bgTokenizer.getTokens(a,b)},this.getTokenAt=function(a,b){var c=this.bgTokenizer.getTokens(a,a)[0].tokens,d,e=0;if(b==null)f=c.length-1,e=this.getLine(a).length;else for(var f=0;f=b)break}return d=c[f],d?(d.index=f,d.start=e-d.value.length,d):null},this.setUndoManager=function(a){this.$undoManager=a,this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(a){var b=this;this.$syncInformUndoManager=function(){b.$informUndoManager.cancel(),b.$deltasFold.length&&(b.$deltas.push({group:"fold",deltas:b.$deltasFold}),b.$deltasFold=[]),b.$deltasDoc.length&&(b.$deltas.push({group:"doc",deltas:b.$deltasDoc}),b.$deltasDoc=[]),b.$deltas.length>0&&a.execute({action:"aceupdate",args:[b.$deltas,b]}),b.$deltas=[]},this.$informUndoManager=e.deferredCall(this.$syncInformUndoManager)}},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?e.stringRepeat(" ",this.getTabSize()):"\t"},this.$useSoftTabs=!0,this.setUseSoftTabs=function(a){if(this.$useSoftTabs===a)return;this.$useSoftTabs=a},this.getUseSoftTabs=function(){return this.$useSoftTabs},this.$tabSize=4,this.setTabSize=function(a){if(isNaN(a)||this.$tabSize===a)return;this.$modified=!0,this.$tabSize=a,this._emit("changeTabSize")},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(a){return this.$useSoftTabs&&a.column%this.$tabSize==0},this.$overwrite=!1,this.setOverwrite=function(a){if(this.$overwrite==a)return;this.$overwrite=a,this._emit("changeOverwrite")},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(a){this.$breakpoints=[];for(var b=0;b0&&(d=!!c.charAt(b-1).match(this.tokenRe)),d||(d=!!c.charAt(b).match(this.tokenRe));var e=d?this.tokenRe:this.nonTokenRe,f=b;if(f>0){do f--;while(f>=0&&c.charAt(f).match(e));f++}var g=b;while(g=this.doc.getLength()-1)return 0;var c=this.doc.removeLines(a,b);return this.doc.insertLines(a+1,c),1},this.duplicateLines=function(a,b){var a=this.$clipRowToDocument(a),b=this.$clipRowToDocument(b),c=this.getLines(a,b);this.doc.insertLines(a,c);var d=b-a+1;return d},this.$clipRowToDocument=function(a){return Math.max(0,Math.min(a,this.doc.getLength()-1))},this.$clipColumnToRow=function(a,b){return b<0?0:Math.min(this.doc.getLine(a).length,b)},this.$clipPositionToDocument=function(a,b){b=Math.max(0,b);if(a<0)a=0,b=0;else{var c=this.doc.getLength();a>=c?(a=c-1,b=this.doc.getLine(c-1).length):b=Math.min(this.doc.getLine(a).length,b)}return{row:a,column:b}},this.$clipRangeToDocument=function(a){a.start.row<0?(a.start.row=0,a.start.column=0):a.start.column=this.$clipColumnToRow(a.start.row,a.start.column);var b=this.doc.getLength()-1;return a.end.row>b?(a.end.row=b,a.end.column=this.doc.getLine(b).length):a.end.column=this.$clipColumnToRow(a.end.row,a.end.column),a},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(a){if(a!=this.$useWrapMode){this.$useWrapMode=a,this.$modified=!0,this.$resetRowCache(0);if(a){var b=this.getLength();this.$wrapData=[];for(var c=0;c0?(this.$wrapLimit=b,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._emit("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(a){var b=this.$wrapLimitRange.min;b&&(a=Math.max(b,a));var c=this.$wrapLimitRange.max;return c&&(a=Math.min(c,a)),Math.max(1,a)},this.getWrapLimit=function(){return this.$wrapLimit},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(a){var b=this.$useWrapMode,c,d=a.data.action,e=a.data.range.start.row,f=a.data.range.end.row,g=a.data.range.start,h=a.data.range.end,i=null;d.indexOf("Lines")!=-1?(d=="insertLines"?f=e+a.data.lines.length:f=e,c=a.data.lines?a.data.lines.length:f-e):c=f-e;if(c!=0)if(d.indexOf("remove")!=-1){b&&this.$wrapData.splice(e,c);var j=this.$foldData;i=this.getFoldsInRange(a.data.range),this.removeFolds(i);var k=this.getFoldLine(h.row),l=0;if(k){k.addRemoveChars(h.row,h.column,g.column-h.column),k.shiftRow(-c);var m=this.getFoldLine(e);m&&m!==k&&(m.merge(k),k=m),l=j.indexOf(k)+1}for(l;l=h.row&&k.shiftRow(-c)}f=e}else{var n;if(b){n=[e,0];for(var o=0;o=e&&k.shiftRow(c)}}else{c=Math.abs(a.data.range.start.column-a.data.range.end.column),d.indexOf("remove")!=-1&&(i=this.getFoldsInRange(a.data.range),this.removeFolds(i),c=-c);var k=this.getFoldLine(e);k&&k.addRemoveChars(e,g.column,c)}return b&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),b&&this.$updateWrapData(e,f),i},this.$updateWrapData=function(a,b){var c=this.doc.getAllLines(),d=this.getTabSize(),f=this.$wrapData,i=this.$wrapLimit,j,k,m=a;b=Math.min(b,c.length-1);while(m<=b){k=this.getFoldLine(m,k);if(!k)j=this.$getDisplayTokens(e.stringTrimRight(c[m])),f[m]=this.$computeWrapSplits(j,i,d),m++;else{j=[],k.walk(function(a,b,d,e){var f;if(a){f=this.$getDisplayTokens(a,j.length),f[0]=g;for(var i=1;i=l)j.pop();f[k.start.row]=this.$computeWrapSplits(j,i,d),m=k.end.row+1}}};var b=1,c=2,g=3,h=4,j=9,l=10,m=11,n=12;this.$computeWrapSplits=function(a,b){function i(b){var d=a.slice(e,b),g=d.length;d.join("").replace(/12/g,function(){g-=1}).replace(/2/g,function(){g-=1}),f+=g,c.push(f),e=b}if(a.length==0)return[];var c=[],d=a.length,e=0,f=0;while(d-e>b){var k=e+b;if(a[k]>=l){while(a[k]>=l)k++;i(k);continue}if(a[k]==g||a[k]==h){for(k;k!=e-1;k--)if(a[k]==g)break;if(k>e){i(k);continue}k=e+b;for(k;km&&a[k]m&&a[k]==j)k--;if(k>m){i(++k);continue}k=e+b,i(k)}return c},this.$getDisplayTokens=function(a,d){var e=[],f;d=d||0;for(var g=0;g39&&h<48||h>57&&h<64?e.push(j):h>=4352&&o(h)?e.push(b,c):e.push(b)}return e},this.$getStringScreenWidth=function(a,b,c){if(b==0)return[0,0];b==null&&(b=c+a.length*Math.max(this.getTabSize(),2)),c=c||0;var d,e;for(e=0;e=4352&&o(d)?c+=2:c+=1;if(c>b)break}return[c,e]},this.getRowLength=function(a){return!this.$useWrapMode||!this.$wrapData[a]?1:this.$wrapData[a].length+1},this.getRowHeight=function(a,b){return this.getRowLength(b)*a.lineHeight},this.getScreenLastRowColumn=function(a){return this.documentToScreenColumn(a,this.doc.getLine(a).length)},this.getDocumentLastRowColumn=function(a,b){var c=this.documentToScreenRow(a,b);return this.getScreenLastRowColumn(c)},this.getDocumentLastRowColumnPosition=function(a,b){var c=this.documentToScreenRow(a,b);return this.screenToDocumentPosition(c,Number.MAX_VALUE/10)},this.getRowSplitData=function(a){return this.$useWrapMode?this.$wrapData[a]:undefined},this.getScreenTabSize=function(a){return this.$tabSize-a%this.$tabSize},this.screenToDocumentRow=function(a,b){return this.screenToDocumentPosition(a,b).row},this.screenToDocumentColumn=function(a,b){return this.screenToDocumentPosition(a,b).column},this.screenToDocumentPosition=function(a,b){if(a<0)return{row:0,column:0};var c,d=0,e=0,f,g=0,h=0,i=this.$rowCache;for(var j=0;j=a||d>=l)break;g+=h,d++,d>n&&(d=m.end.row+1,m=this.getNextFoldLine(d,m),n=m?m.start.row:Infinity),k&&i.push({docRow:d,screenRow:g})}if(m&&m.start.row<=d)c=this.getFoldDisplayLine(m),d=m.start.row;else{if(g+h<=a||d>l)return{row:l,column:this.getLine(l).length};c=this.getLine(d),m=null}if(this.$useWrapMode){var o=this.$wrapData[d];o&&(f=o[a-g],a>g&&o.length&&(e=o[a-g-1]||o[o.length-1],c=c.substring(e)))}return e+=this.$getStringScreenWidth(c,b)[1],this.$useWrapMode?e>=f&&(e=f-1):e=Math.min(e,c.length),m?m.idxToPosition(e):{row:d,column:e}},this.documentToScreenPosition=function(a,b){if(typeof b=="undefined")var c=this.$clipPositionToDocument(a.row,a.column);else c=this.$clipPositionToDocument(a,b);a=c.row,b=c.column;var d;if(this.$useWrapMode){d=this.$wrapData;if(a>d.length-1)return{row:this.getScreenLength(),column:d.length==0?0:d[d.length-1].length-1}}var e=0,f=null,g=null;g=this.getFoldAt(a,b,1),g&&(a=g.start.row,b=g.start.column);var h,i=0,j=this.$rowCache;for(var k=0;k=n){h=m.end.row+1;if(h>a)break;m=this.getNextFoldLine(h,m),n=m?m.start.row:Infinity}else h=i+1;e+=this.getRowLength(i),i=h,l&&j.push({docRow:i,screenRow:e})}var o="";m&&i>=n?(o=this.getFoldDisplayLine(m,a,b),f=m.start.row):(o=this.getLine(a).substring(0,b),f=a);if(this.$useWrapMode){var p=d[f],q=0;while(o.length>=p[q])e++,q++;o=o.substring(p[q-1]||0,o.length)}return{row:e,column:this.$getStringScreenWidth(o)[0]}},this.documentToScreenColumn=function(a,b){return this.documentToScreenPosition(a,b).column},this.documentToScreenRow=function(a,b){return this.documentToScreenPosition(a,b).row},this.getScreenLength=function(){var a=0,b=null;if(!this.$useWrapMode){a=this.getLength();var c=this.$foldData;for(var d=0;dg&&(f=b.end.row+1,b=this.$foldData[d++],g=b?b.start.row:Infinity)}return a}})).call(l.prototype),a("./edit_session/folding").Folding.call(l.prototype),a("./edit_session/bracket_match").BracketMatch.call(l.prototype),b.EditSession=l}),define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/event_emitter").EventEmitter,g=a("./range").Range,h=function(a){this.session=a,this.doc=a.getDocument(),this.clearSelection(),this.selectionLead=this.doc.createAnchor(0,0),this.selectionAnchor=this.doc.createAnchor(0,0);var b=this;this.selectionLead.on("change",function(a){b._emit("changeCursor"),b.$isEmpty||b._emit("changeSelection"),!b.$preventUpdateDesiredColumnOnChange&&a.old.column!=a.value.column&&b.$updateDesiredColumn()}),this.selectionAnchor.on("change",function(){b.$isEmpty||b._emit("changeSelection")})};((function(){d.implement(this,f),this.isEmpty=function(){return this.$isEmpty||this.selectionAnchor.row==this.selectionLead.row&&this.selectionAnchor.column==this.selectionLead.column},this.isMultiLine=function(){return this.isEmpty()?!1:this.getRange().isMultiLine()},this.getCursor=function(){return this.selectionLead.getPosition()},this.setSelectionAnchor=function(a,b){this.selectionAnchor.setPosition(a,b),this.$isEmpty&&(this.$isEmpty=!1,this._emit("changeSelection"))},this.getSelectionAnchor=function(){return this.$isEmpty?this.getSelectionLead():this.selectionAnchor.getPosition()},this.getSelectionLead=function(){return this.selectionLead.getPosition()},this.shiftSelection=function(a){if(this.$isEmpty){this.moveCursorTo(this.selectionLead.row,this.selectionLead.column+a);return}var b=this.getSelectionAnchor(),c=this.getSelectionLead(),d=this.isBackwards();(!d||b.column!==0)&&this.setSelectionAnchor(b.row,b.column+a),(d||c.column!==0)&&this.$moveSelection(function(){this.moveCursorTo(c.row,c.column+a)})},this.isBackwards=function(){var a=this.selectionAnchor,b=this.selectionLead;return a.row>b.row||a.row==b.row&&a.column>b.column},this.getRange=function(){var a=this.selectionAnchor,b=this.selectionLead;return this.isEmpty()?g.fromPoints(b,b):this.isBackwards()?g.fromPoints(b,a):g.fromPoints(a,b)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var a=this.doc.getLength()-1;this.setSelectionAnchor(a,this.doc.getLine(a).length),this.moveCursorTo(0,0)},this.setSelectionRange=function(a,b){b?(this.setSelectionAnchor(a.end.row,a.end.column),this.selectTo(a.start.row,a.start.column)):(this.setSelectionAnchor(a.start.row,a.start.column),this.selectTo(a.end.row,a.end.column)),this.$updateDesiredColumn()},this.$updateDesiredColumn=function(){var a=this.getCursor();this.$desiredColumn=this.session.documentToScreenColumn(a.row,a.column)},this.$moveSelection=function(a){var b=this.selectionLead;this.$isEmpty&&this.setSelectionAnchor(b.row,b.column),a.call(this)},this.selectTo=function(a,b){this.$moveSelection(function(){this.moveCursorTo(a,b)})},this.selectToPosition=function(a){this.$moveSelection(function(){this.moveCursorToPosition(a)})},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.selectWord=function(){var a=this.getCursor(),b=this.session.getWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectAWord=function(){var a=this.getCursor(),b=this.session.getAWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectLine=function(){var a=this.selectionLead.row,b,c=this.session.getFoldLine(a);c?(a=c.start.row,b=c.end.row):b=a,this.setSelectionAnchor(a,0),this.$moveSelection(function(){this.moveCursorTo(b+1,0)})},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,-1))this.moveCursorTo(b.start.row,b.start.column);else if(a.column==0)a.row>0&&this.moveCursorTo(a.row-1,this.doc.getLine(a.row-1).length);else{var c=this.session.getTabSize();this.session.isTabStop(a)&&this.doc.getLine(a.row).slice(a.column-c,a.column).split(" ").length-1==c?this.moveCursorBy(0,-c):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,1))this.moveCursorTo(b.end.row,b.end.column);else if(this.selectionLead.column==this.doc.getLine(this.selectionLead.row).length)this.selectionLead.row=c.length){this.moveCursorTo(a,c.length),this.moveCursorRight(),a0&&this.moveCursorWordLeft();return}if(g=this.session.tokenRe.exec(f))b-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(a,b)},this.moveCursorBy=function(a,b){var c=this.session.documentToScreenPosition(this.selectionLead.row,this.selectionLead.column),d=b===0&&this.$desiredColumn||c.column,e=this.session.screenToDocumentPosition(c.row+a,d);this.moveCursorTo(e.row,e.column+b,b===0)},this.moveCursorToPosition=function(a){this.moveCursorTo(a.row,a.column)},this.moveCursorTo=function(a,b,c){var d=this.session.getFoldAt(a,b,1);d&&(a=d.start.row,b=d.start.column),this.$preventUpdateDesiredColumnOnChange=!0,this.selectionLead.setPosition(a,b),this.$preventUpdateDesiredColumnOnChange=!1,c||this.$updateDesiredColumn(this.selectionLead.column)},this.moveCursorToScreen=function(a,b,c){var d=this.session.screenToDocumentPosition(a,b);a=d.row,b=d.column,this.moveCursorTo(a,b,c)}})).call(h.prototype),b.Selection=h}),define("ace/range",["require","exports","module"],function(a,b,c){"use strict";var d=function(a,b,c,d){this.start={row:a,column:b},this.end={row:c,column:d}};((function(){this.isEequal=function(a){return this.start.row==a.start.row&&this.end.row==a.end.row&&this.start.column==a.start.column&&this.end.column==a.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(a,b){return this.compare(a,b)==0},this.compareRange=function(a){var b,c=a.end,d=a.start;return b=this.compare(c.row,c.column),b==1?(b=this.compare(d.row,d.column),b==1?2:b==0?1:0):b==-1?-2:(b=this.compare(d.row,d.column),b==-1?-1:b==1?42:0)},this.comparePoint=function(a){return this.compare(a.row,a.column)},this.containsRange=function(a){return this.comparePoint(a.start)==0&&this.comparePoint(a.end)==0},this.isEnd=function(a,b){return this.end.row==a&&this.end.column==b},this.isStart=function(a,b){return this.start.row==a&&this.start.column==b},this.setStart=function(a,b){typeof a=="object"?(this.start.column=a.column,this.start.row=a.row):(this.start.row=a,this.start.column=b)},this.setEnd=function(a,b){typeof a=="object"?(this.end.column=a.column,this.end.row=a.row):(this.end.row=a,this.end.column=b)},this.inside=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)||this.isStart(a,b)?!1:!0:!1},this.insideStart=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)?!1:!0:!1},this.insideEnd=function(a,b){return this.compare(a,b)==0?this.isStart(a,b)?!1:!0:!1},this.compare=function(a,b){return!this.isMultiLine()&&a===this.start.row?bthis.end.column?1:0:athis.end.row?1:this.start.row===a?b>=this.start.column?0:-1:this.end.row===a?b<=this.end.column?0:1:0},this.compareStart=function(a,b){return this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.compareEnd=function(a,b){return this.end.row==a&&this.end.column==b?1:this.compare(a,b)},this.compareInside=function(a,b){return this.end.row==a&&this.end.column==b?1:this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.clipRows=function(a,b){if(this.end.row>b)var c={row:b+1,column:0};if(this.start.row>b)var e={row:b+1,column:0};if(this.start.row=0&&/^[\w\d]/.test(h)||e<=g&&/[\w\d]$/.test(h))return;h=f.substring(c.start.column,c.end.column);if(!/^[\w\d]+$/.test(h))return;var i=a.getCursorPosition(),j={wrap:!0,wholeWord:!0,caseSensitive:!0,needle:h},k=a.$search.getOptions();a.$search.set(j);var l=a.$search.findAll(b);l.forEach(function(a){if(!a.contains(i.row,i.column)){var c=b.addMarker(a,"ace_selected_word","text");b.$selectionOccurrences.push(c)}}),a.$search.set(k)},this.clearSelectionHighlight=function(a){if(!a.session.$selectionOccurrences)return;a.session.$selectionOccurrences.forEach(function(b){a.session.removeMarker(b)}),a.session.$selectionOccurrences=[]},this.createModeDelegates=function(a){if(!this.$embeds)return;this.$modes={};for(var b=0;b1&&(m=g.slice(n+2,n+1+e[n].len)),typeof l.token=="function"?k=l.token.apply(this,m):k=l.token;var o=l.next;o&&o!==c&&(c=o,d=this.rules[c],e=this.matchMappings[c],i=f.lastIndex,f=this.regExps[c],f.lastIndex=i);break}if(m[0]){typeof k=="string"&&(m=[m.join("")],k=[k]);for(var n=0;n=b&&(a.row=Math.max(0,b-1),a.column=this.getLine(b-1).length),a},this.insert=function(a,b){if(b.length==0)return a;a=this.$clipPosition(a),this.getLength()<=1&&this.$detectNewLine(b);var c=this.$split(b),d=c.splice(0,1)[0],e=c.length==0?null:c.splice(c.length-1,1)[0];return a=this.insertInLine(a,d),e!==null&&(a=this.insertNewLine(a),a=this.insertLines(a.row,c),a=this.insertInLine(a,e||"")),a},this.insertLines=function(a,b){if(b.length==0)return{row:a,column:0};var c=[a,0];c.push.apply(c,b),this.$lines.splice.apply(this.$lines,c);var d=new f(a,0,a+b.length,0),e={action:"insertLines",range:d,lines:b};return this._emit("change",{data:e}),d.end},this.insertNewLine=function(a){a=this.$clipPosition(a);var b=this.$lines[a.row]||"";this.$lines[a.row]=b.substring(0,a.column),this.$lines.splice(a.row+1,0,b.substring(a.column,b.length));var c={row:a.row+1,column:0},d={action:"insertText",range:f.fromPoints(a,c),text:this.getNewLineCharacter()};return this._emit("change",{data:d}),c},this.insertInLine=function(a,b){if(b.length==0)return a;var c=this.$lines[a.row]||"";this.$lines[a.row]=c.substring(0,a.column)+b+c.substring(a.column);var d={row:a.row,column:a.column+b.length},e={action:"insertText",range:f.fromPoints(a,d),text:b};return this._emit("change",{data:e}),d},this.remove=function(a){a.start=this.$clipPosition(a.start),a.end=this.$clipPosition(a.end);if(a.isEmpty())return a.start;var b=a.start.row,c=a.end.row;if(a.isMultiLine()){var d=a.start.column==0?b:b+1,e=c-1;a.end.column>0&&this.removeInLine(c,0,a.end.column),e>=d&&this.removeLines(d,e),d!=b&&(this.removeInLine(b,a.start.column,this.getLine(b).length),this.removeNewLine(a.start.row))}else this.removeInLine(b,a.start.column,a.end.column);return a.start},this.removeInLine=function(a,b,c){if(b==c)return;var d=new f(a,b,a,c),e=this.getLine(a),g=e.substring(b,c),h=e.substring(0,b)+e.substring(c,e.length);this.$lines.splice(a,1,h);var i={action:"removeText",range:d,text:g};return this._emit("change",{data:i}),d.start},this.removeLines=function(a,b){var c=new f(a,0,b+1,0),d=this.$lines.splice(a,b-a+1),e={action:"removeLines",range:c,nl:this.getNewLineCharacter(),lines:d};return this._emit("change",{data:e}),d},this.removeNewLine=function(a){var b=this.getLine(a),c=this.getLine(a+1),d=new f(a,b.length,a+1,0),e=b+c;this.$lines.splice(a,2,e);var g={action:"removeText",range:d,text:this.getNewLineCharacter()};this._emit("change",{data:g})},this.replace=function(a,b){if(b.length==0&&a.isEmpty())return a.start;if(b==this.getTextRange(a))return a.end;this.remove(a);if(b)var c=this.insert(a.start,b);else c=a.start;return c},this.applyDeltas=function(a){for(var b=0;b=0;b--){var c=a[b],d=f.fromPoints(c.range.start,c.range.end);c.action=="insertLines"?this.removeLines(d.start.row,d.end.row-1):c.action=="insertText"?this.remove(d):c.action=="removeLines"?this.insertLines(d.start.row,c.lines):c.action=="removeText"&&this.insert(d.start,c.text)}}})).call(h.prototype),b.Document=h}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=b.Anchor=function(a,b,c){this.document=a,typeof c=="undefined"?this.setPosition(b.row,b.column):this.setPosition(b,c),this.$onChange=this.onChange.bind(this),a.on("change",this.$onChange)};((function(){d.implement(this,e),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.onChange=function(a){var b=a.data,c=b.range;if(c.start.row==c.end.row&&c.start.row!=this.row)return;if(c.start.row>this.row)return;if(c.start.row==this.row&&c.start.column>this.column)return;var d=this.row,e=this.column;b.action==="insertText"?c.start.row===d&&c.start.column<=e?c.start.row===c.end.row?e+=c.end.column-c.start.column:(e-=c.start.column,d+=c.end.row-c.start.row):c.start.row!==c.end.row&&c.start.row=e?e=c.start.column:e=Math.max(0,e-(c.end.column-c.start.column)):c.start.row!==c.end.row&&c.start.row=this.document.getLength()?(c.row=Math.max(0,this.document.getLength()-1),c.column=this.document.getLine(c.row).length):a<0?(c.row=0,c.column=0):(c.row=a,c.column=Math.min(this.document.getLine(c.row).length,Math.max(0,b))),b<0&&(c.column=0),c}})).call(f.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=function(a,b){this.running=!1,this.lines=[],this.currentLine=0,this.tokenizer=a;var c=this;this.$worker=function(){if(!c.running)return;var a=new Date,b=c.currentLine,d=c.doc,e=0,f=d.getLength();while(c.currentLine20){c.fireUpdateEvent(b,c.currentLine-1),c.running=setTimeout(c.$worker,20);return}}c.running=!1,c.fireUpdateEvent(b,f-1)}};((function(){d.implement(this,e),this.setTokenizer=function(a){this.tokenizer=a,this.lines=[],this.start(0)},this.setDocument=function(a){this.doc=a,this.lines=[],this.stop()},this.fireUpdateEvent=function(a,b){var c={first:a,last:b};this._emit("update",{data:c})},this.start=function(a){this.currentLine=Math.min(a||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(a,b){return this.$tokenizeRows(a,b)},this.getState=function(a){return this.$tokenizeRows(a,a)[0].state},this.$tokenizeRows=function(a,b){if(!this.doc||isNaN(a)||isNaN(b))return[{state:"start",tokens:[]}];var c=[],d="start",e=!1;a>0&&this.lines[a-1]?(d=this.lines[a-1].state,e=!0):a==0?(d="start",e=!0):this.lines.length>0&&(d=this.lines[this.lines.length-1].state);var f=this.doc.getLines(a,b);for(var g=a;g<=b;g++)if(!this.lines[g]){var h=this.tokenizer.getLineTokens(f[g-a]||"",d),d=h.state;c.push(h),e&&(this.lines[g]=h)}else{var h=this.lines[g];d=h.state,c.push(h)}return c}})).call(f.prototype),b.BackgroundTokenizer=f}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(a,b,c){function h(){this.getFoldAt=function(a,b,c){var d=this.getFoldLine(a);if(!d)return null;var e=d.folds;for(var f=0;f=a)return e;if(e.end.row>a)return null}return null},this.getNextFoldLine=function(a,b){var c=this.$foldData,d=0;b&&(d=c.indexOf(b)),d==-1&&(d=0);for(d;d=a)return e}return null},this.getFoldedRowCount=function(a,b){var c=this.$foldData,d=b-a+1;for(var e=0;e=b){h=a?d-=b-h:d=0);break}g>=a&&(h>=a?d-=g-h:d-=g-a+1)}return d},this.$addFoldLine=function(a){return this.$foldData.push(a),this.$foldData.sort(function(a,b){return a.start.row-b.start.row}),a},this.addFold=function(a,b){var c=this.$foldData,d=!1,g;a instanceof f?g=a:g=new f(b,a),this.$clipRangeToDocument(g.range);var h=g.start.row,i=g.start.column,j=g.end.row,k=g.end.column;if(g.placeholder.length<2)throw"Placeholder has to be at least 2 characters";if(h==j&&k-i<2)throw"The range has to be at least 2 characters width";var l=this.getFoldAt(h,i,1),m=this.getFoldAt(j,k,-1);if(l&&m==l)return l.addSubFold(g);if(l&&!l.range.isStart(h,i)||m&&!m.range.isEnd(j,k))throw"A fold can't intersect already existing fold"+g.range+l.range;var n=this.getFoldsInRange(g.range);n.length>0&&(this.removeFolds(n),g.subFolds=n);for(var o=0;othis.endRow)throw"Can't add a fold to this FoldLine as it has no connection";this.folds.push(a),this.folds.sort(function(a,b){return-a.range.compareEnd(b.start.row,b.start.column)}),this.range.compareEnd(a.start.row,a.start.column)>0?(this.end.row=a.end.row,this.end.column=a.end.column):this.range.compareStart(a.end.row,a.end.column)<0&&(this.start.row=a.start.row,this.start.column=a.start.column)}else if(a.start.row==this.end.row)this.folds.push(a),this.end.row=a.end.row,this.end.column=a.end.column;else if(a.end.row==this.start.row)this.folds.unshift(a),this.start.row=a.start.row,this.start.column=a.start.column;else throw"Trying to add fold to FoldRow that doesn't have a matching row";a.foldLine=this},this.containsRow=function(a){return a>=this.start.row&&a<=this.end.row},this.walk=function(a,b,c){var d=0,e=this.folds,f,g,h,i=!0;b==null&&(b=this.end.row,c=this.end.column);for(var j=0;j=this.$rowTokens.length){this.$row+=1;if(this.$row>=a)return this.$row=a-1,null;this.$rowTokens=this.$session.getTokens(this.$row,this.$row)[0].tokens,this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var a=this.$rowTokens,b=this.$tokenIndex,c=a[b].start;if(c!==undefined)return c;c=0;while(b>0)b-=1,c+=a[b].value.length;return c}})).call(d.prototype),b.TokenIterator=d}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator"],function(a,b,c){function e(){this.findMatchingBracket=function(a){if(a.column==0)return null;var b=this.getLine(a.row).charAt(a.column-1);if(b=="")return null;var c=b.match(/([\(\[\{])|([\)\]\}])/);return c?c[1]?this.$findClosingBracket(c[1],a):this.$findOpeningBracket(c[2],a):null},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("rparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn()-2,j=g.value;for(;;){while(i>=0){var k=j.charAt(i);if(k==c){e-=1;if(e==0)return{row:f.getCurrentTokenRow(),column:i+f.getCurrentTokenColumn()}}else k==a&&(e+=1);i-=1}do g=f.stepBackward();while(g&&!h.test(g.type));if(g==null)break;j=g.value,i=j.length-1}return null},this.$findClosingBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("lparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn();for(;;){var j=g.value,k=j.length;while(i=0;h--){var i=g[h],j=c.$rangeFromMatch(f,i.offset,i.str.length);if(d(j))return!0}})}}},this.$rangeFromMatch=function(a,b,c){return new f(a,b,a,b+c)},this.$assembleRegExp=function(){if(this.$options.regExp)var a=this.$options.needle;else a=d.escapeRegExp(this.$options.needle);this.$options.wholeWord&&(a="\\b"+a+"\\b");var b="g";this.$options.caseSensitive||(b+="i");var c=new RegExp(a,b);return c},this.$forwardLineIterator=function(a){function k(e){var f=a.getLine(e);return b&&e==c.end.row&&(f=f.substring(0,c.end.column)),j&&e==d.row&&(f=f.substring(0,d.column)),f}var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"start":"end"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap,j=!1;return{forEach:function(a){var b=d.row,c=k(b),g=d.column,l=!1;j=!1;while(!a(c,g,b)){if(l)return;b++,g=0;if(b>h)if(i)b=e,g=f,j=!0;else return;b==d.row&&(l=!0),c=k(b)}}}},this.$backwardLineIterator=function(a){var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"end":"start"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap;return{forEach:function(g){var j=d.row,k=a.getLine(j).substring(0,d.column),l=0,m=!1,n=!1;while(!g(k,l,j)){if(m)return;j--,l=0;if(j0},this.hasRedo=function(){return this.$redoStack.length>0}})).call(d.prototype),b.UndoManager=d}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/lib/event_emitter","text!ace/css/editor.css"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/useragent"),h=a("./layer/gutter").Gutter,i=a("./layer/marker").Marker,j=a("./layer/text").Text,k=a("./layer/cursor").Cursor,l=a("./scrollbar").ScrollBar,m=a("./renderloop").RenderLoop,n=a("./lib/event_emitter").EventEmitter,o=a("text!./css/editor.css");e.importCssString(o,"ace_editor");var p=function(a,b){var c=this;this.container=a,e.addCssClass(a,"ace_editor"),this.setTheme(b),this.$gutter=e.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=e.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=e.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new h(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onResize.bind(this,!0)),this.$markerBack=new i(this.content);var d=this.$textLayer=new j(this.content);this.canvas=d.element,this.$markerFront=new i(this.content),this.characterWidth=d.getCharacterWidth(),this.lineHeight=d.getLineHeight(),this.$cursorLayer=new k(this.content),this.$cursorPadding=8,this.$horizScroll=!0,this.$horizScrollAlwaysVisible=!0,this.scrollBar=new l(a),this.scrollBar.addEventListener("scroll",function(a){c.session.setScrollTop(a.data)}),this.scrollTop=0,this.scrollLeft=0,f.addListener(this.scroller,"scroll",function(){c.session.setScrollLeft(c.scroller.scrollLeft)}),this.cursorPos={row:0,column:0},this.$textLayer.addEventListener("changeCharaterSize",function(){c.characterWidth=d.getCharacterWidth(),c.lineHeight=d.getLineHeight(),c.$updatePrintMargin(),c.onResize(!0),c.$loop.schedule(c.CHANGE_FULL)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:1,characterWidth:1,minHeight:1,maxHeight:1,offset:0,height:1},this.$loop=new m(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.setPadding(4),this.$updatePrintMargin()};((function(){this.showGutter=!0,this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,d.implement(this,n),this.setSession=function(a){this.session=a,this.$cursorLayer.setSession(a),this.$markerBack.setSession(a),this.$markerFront.setSession(a),this.$gutterLayer.setSession(a),this.$textLayer.setSession(a),this.$loop.schedule(this.CHANGE_FULL)},this.updateLines=function(a,b){b===undefined&&(b=Infinity),this.$changedLines?(this.$changedLines.firstRow>a&&(this.$changedLines.firstRow=a),this.$changedLines.lastRowc.lastRow+1)return;if(bc&&this.session.setScrollTop(c),this.scrollTop+this.$size.scrollerHeightb&&(bthis.layerConfig.width+2*this.$padding?this.$desiredScrollLeft=b:this.scrollToX(Math.round(b+this.characterWidth-this.$size.scrollerWidth)))},this.getScrollTop=function(){return this.session.getScrollTop()},this.getScrollLeft=function(){return this.session.getScrollTop()},this.getScrollTopRow=function(){return this.scrollTop/this.lineHeight},this.getScrollBottomRow=function(){return Math.max(0,Math.floor((this.scrollTop+this.$size.scrollerHeight)/this.lineHeight)-1)},this.scrollToRow=function(a){this.session.setScrollTop(a*this.lineHeight)},this.scrollToLine=function(a,b){var c={lineHeight:this.lineHeight},d=0;for(var e=1;e0)return!0;if(b>0&&this.session.getScrollTop()+this.$size.scrollerHeighth&&(e=g.end.row+1,g=this.session.getNextFoldLine(e,g),h=g?g.start.row:Infinity);if(e>f)break;var j=this.$annotations[e]||b;c.push("
    ",e+1);if(i){var k=i[e];k==null&&(k=i[e]=this.session.getFoldWidget(e)),k&&c.push("")}var l=this.session.getRowLength(e)-1;while(l--)c.push("
    ¦");c.push("
    "),e++}this.element=d.setInnerHtml(this.element,c.join("")),this.element.style.height=a.minHeight+"px";var m=this.element.offsetWidth;m!==this.gutterWidth&&(this.gutterWidth=m,this._emit("changeGutterWidth",m))},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(a){a?d.addCssClass(this.element,"ace_folding-enabled"):d.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=a},this.getShowFoldWidgets=function(){return this.$showFoldWidgets}})).call(g.prototype),b.Gutter=g}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../range").Range,e=a("../lib/dom"),f=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_marker-layer",a.appendChild(this.element)};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.setMarkers=function(a){this.markers=a},this.update=function(a){var a=a||this.config;if(!a)return;this.config=a;var b=[];for(var c in this.markers){var d=this.markers[c],f=d.range.clipRows(a.firstRow,a.lastRow);if(f.isEmpty())continue;f=f.toScreenRange(this.session);if(d.renderer){var g=this.$getTop(f.start.row,a),h=Math.round(this.$padding+f.start.column*a.characterWidth);d.renderer(b,f,h,g,a)}else f.isMultiLine()?d.type=="text"?this.drawTextMarker(b,f,d.clazz,a):this.drawMultiLineMarker(b,f,d.clazz,a,d.type):this.drawSingleLineMarker(b,f,d.clazz,a,null,d.type)}this.element=e.setInnerHtml(this.element,b.join(""))},this.$getTop=function(a,b){return(a-b.firstRowScreen)*b.lineHeight},this.drawTextMarker=function(a,b,c,e){var f=b.start.row,g=new d(f,b.start.column,f,this.session.getScreenLastRowColumn(f));this.drawSingleLineMarker(a,g,c,e,1,"text"),f=b.end.row,g=new d(f,0,f,b.end.column),this.drawSingleLineMarker(a,g,c,e,0,"text");for(f=b.start.row+1;f
    "),j=this.$getTop(b.end.row,d),i=Math.round(b.end.column*d.characterWidth),a.push("
    "),h=(b.end.row-b.start.row-1)*d.lineHeight;if(h<0)return;j=this.$getTop(b.start.row+1,d),a.push("
    ")},this.drawSingleLineMarker=function(a,b,c,d,e,f){var g=f==="background"?0:this.$padding,h=d.lineHeight;if(f==="background")var i=d.width;else i=Math.round((b.end.column+(e||0)-b.start.column)*d.characterWidth);var j=this.$getTop(b.start.row,d),k=Math.round(g+b.start.column*d.characterWidth);a.push("
    ")}})).call(f.prototype),b.Marker=f}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/dom"),f=a("../lib/lang"),g=a("../lib/useragent"),h=a("../lib/event_emitter").EventEmitter,i=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_text-layer",a.appendChild(this.element),this.$characterSize=this.$measureSizes()||{width:0,height:0},this.$pollSizeChanges()};((function(){d.implement(this,h),this.EOF_CHAR="¶",this.EOL_CHAR="¬",this.TAB_CHAR="→",this.SPACE_CHAR="·",this.$padding=0,this.setPadding=function(a){this.$padding=a,this.element.style.padding="0 "+a+"px"},this.getLineHeight=function(){return this.$characterSize.height||1},this.getCharacterWidth=function(){return this.$characterSize.width||1},this.checkForSizeChanges=function(){var a=this.$measureSizes();a&&(this.$characterSize.width!==a.width||this.$characterSize.height!==a.height)&&(this.$characterSize=a,this._emit("changeCharaterSize",{data:a}))},this.$pollSizeChanges=function(){var a=this;this.$pollSizeChangesTimer=setInterval(function(){a.checkForSizeChanges()},500)},this.$fontStyles={fontFamily:1,fontSize:1,fontWeight:1,fontStyle:1,lineHeight:1},this.$measureSizes=function(){var a=1e3;if(!this.$measureNode){var b=this.$measureNode=e.createElement("div"),c=b.style;c.width=c.height="auto",c.left=c.top=-a*40+"px",c.visibility="hidden",c.position="absolute",c.overflow="visible",c.whiteSpace="nowrap",b.innerHTML=f.stringRepeat("Xy",a);if(this.element.ownerDocument.body)this.element.ownerDocument.body.appendChild(b);else{var d=this.element.parentNode;while(!e.hasCssClass(d,"ace_editor"))d=d.parentNode;d.appendChild(b)}}var c=this.$measureNode.style,g=e.computedStyle(this.element);for(var h in this.$fontStyles)c[h]=g[h];var i={height:this.$measureNode.offsetHeight,width:this.$measureNode.offsetWidth/(a*2)};return i.width==0&&i.height==0?null:i},this.setSession=function(a){this.session=a},this.showInvisibles=!1,this.setShowInvisibles=function(a){return this.showInvisibles==a?!1:(this.showInvisibles=a,!0)},this.$tabStrings=[],this.$computeTabString=function(){var a=this.session.getTabSize(),b=this.$tabStrings=[0];for(var c=1;c"+this.TAB_CHAR+(new Array(c)).join(" ")+""):b.push((new Array(c+1)).join(" "))},this.updateLines=function(a,b,c){this.$computeTabString(),(this.config.lastRow!=a.lastRow||this.config.firstRow!=a.firstRow)&&this.scrollLines(a),this.config=a;var d=Math.max(b,a.firstRow),f=Math.min(c,a.lastRow),g=this.element.childNodes,h=0;for(var i=a.firstRow;i0;d--)c.removeChild(c.firstChild);if(b.lastRow>a.lastRow)for(var d=this.session.getFoldedRowCount(a.lastRow+1,b.lastRow);d>0;d--)c.removeChild(c.lastChild);if(a.firstRowb.lastRow){var e=this.$renderLinesFragment(a,b.lastRow+1,a.lastRow);c.appendChild(e)}},this.$renderLinesFragment=function(a,b,c){var d=this.element.ownerDocument.createDocumentFragment(),f=b,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>c)break;var i=e.createElement("div"),j=[],k=this.session.getTokens(f,f);k.length==1&&this.$renderLine(j,f,k[0].tokens,!1),i.innerHTML=j.join("");if(this.$useLineGroups())i.className="ace_line_group",d.appendChild(i);else{var l=i.childNodes;while(l.length)d.appendChild(l[0])}f++}return d},this.update=function(a){this.$computeTabString(),this.config=a;var b=[],c=a.firstRow,d=a.lastRow,f=c,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>d)break;this.$useLineGroups()&&b.push("
    ");var i=this.session.getTokens(f,f);i.length==1&&this.$renderLine(b,f,i[0].tokens,!1),this.$useLineGroups()&&b.push("
    "),f++}this.element=e.setInnerHtml(this.element,b.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(a,b,c,d){var e=this,f=/\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g,h=function(a,c,d,f,h){if(a.charCodeAt(0)==32)return(new Array(a.length+1)).join(" ");if(a=="\t"){var i=e.session.getScreenTabSize(b+f);return b+=i-1,e.$tabStrings[i]}if(a=="&")return g.isOldGecko?"&":"&";if(a=="<")return"<";if(a==" "){var j=e.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",k=e.showInvisibles?e.SPACE_CHAR:"";return b+=1,""+k+""}if(a.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)){if(e.showInvisibles){var k=(new Array(a.length+1)).join(e.SPACE_CHAR);return""+k+""}return" "}return b+=1,""+a+""},i=d.replace(f,h);if(!this.$textToken[c.type]){var j="ace_"+c.type.replace(/\./g," ace_"),k="";c.type=="fold"&&(k=" style='width:"+c.value.length*this.config.characterWidth+"px;' "),a.push("",i,"")}else a.push(i);return b+d.length},this.$renderLineCore=function(a,b,c,d,e){var f=0,g=0,h,i=0,j=this;!d||d.length==0?h=Number.MAX_VALUE:h=d[0],e||a.push("
    ");for(var k=0;k=h)i=j.$renderToken(a,i,l,m.substring(0,h-f)),m=m.substring(h-f),f=h,e||a.push("
    ","
    "),g++,i=0,h=d[g]||Number.MAX_VALUE;m.length!=0&&(f+=m.length,i=j.$renderToken(a,i,l,m))}}this.showInvisibles&&(b!==this.session.getLength()-1?a.push(""+this.EOL_CHAR+""):a.push(""+this.EOF_CHAR+"")),e||a.push("
    ")},this.$renderLine=function(a,b,c,d){if(!this.session.isRowFolded(b)){var e=this.session.getRowSplitData(b);this.$renderLineCore(a,b,c,e,d)}else this.$renderFoldLine(a,b,c,d)},this.$renderFoldLine=function(a,b,c,d){function h(a,b,c){var d=0,e=0;while(e+a[d].value.lengthc-b&&(f=f.substring(0,c-b)),g.push({type:a[d].type,value:f}),e=b+f.length,d+=1}while(ec&&(f=f.substring(0,c-e)),g.push({type:a[d].type,value:f}),e+=f.length,d+=1}}var e=this.session,f=e.getFoldLine(b),g=[];f.walk(function(a,b,d,e,f){a?g.push({type:"fold",value:a}):(f&&(c=this.session.getTokens(b,b)[0].tokens),c.length!=0&&h(c,e,d))}.bind(this),f.end.row,this.session.getLine(f.end.row).length);var i=this.session.$useWrapMode?this.session.$wrapData[b]:null;this.$renderLineCore(a,b,g,i,d)},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}})).call(i.prototype),b.Text=i}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../lib/dom"),e=function(a){this.element=d.createElement("div"),this.element.className="ace_layer ace_cursor-layer",a.appendChild(this.element),this.cursor=d.createElement("div"),this.cursor.className="ace_cursor ace_hidden",this.element.appendChild(this.cursor),this.isVisible=!1};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.hideCursor=function(){this.isVisible=!1,d.addCssClass(this.cursor,"ace_hidden"),clearInterval(this.blinkId)},this.showCursor=function(){this.isVisible=!0,d.removeCssClass(this.cursor,"ace_hidden"),this.cursor.style.visibility="visible",this.restartTimer()},this.restartTimer=function(){clearInterval(this.blinkId);if(!this.isVisible)return;var a=this.cursor;this.blinkId=setInterval(function(){a.style.visibility="hidden",setTimeout(function(){a.style.visibility="visible"},400)},1e3)},this.getPixelPosition=function(a){if(!this.config||!this.session)return{left:0,top:0};var b=this.session.selection.getCursor(),c=this.session.documentToScreenPosition(b),d=Math.round(this.$padding+c.column*this.config.characterWidth),e=(c.row-(a?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:d,top:e}},this.update=function(a){this.config=a,this.pixelPos=this.getPixelPosition(!0),this.cursor.style.left=this.pixelPos.left+"px",this.cursor.style.top=this.pixelPos.top+"px",this.cursor.style.width=a.characterWidth+"px",this.cursor.style.height=a.lineHeight+"px";var b=this.session.getOverwrite();b!=this.overwrite&&(this.overwrite=b,b?d.addCssClass(this.cursor,"ace_overwrite"):d.removeCssClass(this.cursor,"ace_overwrite")),this.restartTimer()},this.destroy=function(){clearInterval(this.blinkId)}})).call(e.prototype),b.Cursor=e}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/event_emitter").EventEmitter,h=function(a){this.element=e.createElement("div"),this.element.className="ace_sb",this.inner=e.createElement("div"),this.element.appendChild(this.inner),a.appendChild(this.element),this.width=e.scrollbarWidth(a.ownerDocument),this.element.style.width=(this.width||15)+5+"px",f.addListener(this.element,"scroll",this.onScroll.bind(this))};((function(){d.implement(this,g),this.onScroll=function(){this._emit("scroll",{data:this.element.scrollTop})},this.getWidth=function(){return this.width},this.setHeight=function(a){this.element.style.height=a+"px"},this.setInnerHeight=function(a){this.inner.style.height=a+"px"},this.setScrollTop=function(a){this.element.scrollTop=a}})).call(h.prototype),b.ScrollBar=h}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(a,b,c){"use strict";var d=a("./lib/event"),e=function(a,b){this.onRender=a,this.pending=!1,this.changes=0,this.window=b||window};((function(){this.schedule=function(a){this.changes=this.changes|a;if(!this.pending){this.pending=!0;var b=this;d.nextTick(function(){b.pending=!1;var a;while(a=b.changes)b.changes=0,b.onRender(a)},this.window)}}})).call(e.prototype),b.RenderLoop=e}),define("text!ace/css/editor.css",[],"@import url(//fonts.googleapis.com/css?family=Droid+Sans+Mono);\n\n\n.ace_editor {\n position: absolute;\n overflow: hidden;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Courier New', monospace;\n font-size: 12px;\n}\n\n.ace_scroller {\n position: absolute;\n overflow-x: scroll;\n overflow-y: hidden;\n}\n\n.ace_content {\n position: absolute;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n cursor: text;\n}\n\n/* setting pointer-events: auto; on node under the mouse, which changes during scroll,\n will break mouse wheel scrolling in Safari */\n.ace_content * {\n pointer-events: none;\n}\n\n.ace_composition {\n position: absolute;\n background: #555;\n color: #DDD;\n z-index: 4;\n}\n\n.ace_gutter .ace_layer {\n position: relative;\n min-width: 54px;\n text-align: right;\n}\n\n.ace_gutter {\n position: absolute;\n overflow : hidden;\n height: 100%;\n width: auto;\n cursor: default;\n}\n\n.ace_gutter-cell {\n padding-left: 19px;\n padding-right: 6px;\n}\n\n.ace_gutter-cell.ace_error {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_warning {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_info {\n background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_editor .ace_sb {\n position: absolute;\n overflow-x: hidden;\n overflow-y: scroll;\n right: 0;\n}\n\n.ace_editor .ace_sb div {\n position: absolute;\n width: 1px;\n left: 0;\n}\n\n.ace_editor .ace_print_margin_layer {\n z-index: 0;\n position: absolute;\n overflow: hidden;\n margin: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.ace_editor .ace_print_margin {\n position: absolute;\n height: 100%;\n}\n\n.ace_editor textarea {\n position: fixed;\n z-index: 0;\n width: 10px;\n height: 30px;\n opacity: 0;\n background: transparent;\n appearance: none;\n -moz-appearance: none;\n border: none;\n resize: none;\n outline: none;\n overflow: hidden;\n}\n\n.ace_layer {\n z-index: 1;\n position: absolute;\n overflow: hidden;\n white-space: nowrap;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_text-layer {\n color: black;\n}\n\n.ace_cjk {\n display: inline-block;\n text-align: center;\n}\n\n.ace_cursor-layer {\n z-index: 4;\n}\n\n.ace_cursor {\n z-index: 4;\n position: absolute;\n}\n\n.ace_cursor.ace_hidden {\n opacity: 0.2;\n}\n\n.ace_line {\n white-space: nowrap;\n}\n\n.ace_marker-layer .ace_step {\n position: absolute;\n z-index: 3;\n}\n\n.ace_marker-layer .ace_selection {\n position: absolute;\n z-index: 4;\n}\n\n.ace_marker-layer .ace_bracket {\n position: absolute;\n z-index: 5;\n}\n\n.ace_marker-layer .ace_active_line {\n position: absolute;\n z-index: 2;\n}\n\n.ace_marker-layer .ace_selected_word {\n position: absolute;\n z-index: 6;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_line .ace_fold {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n \n display: inline-block;\n height: 11px;\n margin-top: -2px;\n vertical-align: middle;\n\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n color: transparent;\n\n border: 1px solid black;\n -moz-border-radius: 2px;\n -webkit-border-radius: 2px;\n border-radius: 2px;\n \n cursor: pointer;\n pointer-events: auto;\n}\n\n.ace_dark .ace_fold {\n}\n\n.ace_fold:hover{\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n}\n\n.ace_dragging .ace_content {\n cursor: move;\n}\n\n.ace_folding-enabled .ace_gutter-cell {\n padding-right: 13px;\n}\n\n.ace_fold-widget {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n\n margin: 0 -12px 1px 1px;\n display: inline-block;\n height: 14px;\n width: 11px;\n vertical-align: text-bottom;\n \n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat;\n background-position: center 5px;\n\n border-radius: 3px;\n}\n\n.ace_fold-widget.end {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget.closed {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget:hover {\n border: 1px solid rgba(0, 0, 0, 0.3);\n background-color: rgba(255, 255, 255, 0.2);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n background-position: center 4px;\n}\n\n.ace_fold-widget:active {\n border: 1px solid rgba(0, 0, 0, 0.4);\n background-color: rgba(0, 0, 0, 0.05);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n}\n\n.ace_fold-widget.invalid {\n background-color: #FFB4B4;\n border-color: #DE5555;\n}\n"),define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict",b.isDark=!1,b.cssClass="ace-tm",b.cssText=".ace-tm .ace_editor { border: 2px solid rgb(159, 159, 159);}.ace-tm .ace_editor.ace_focus { border: 2px solid #327fbd;}.ace-tm .ace_gutter { background: #e8e8e8; color: #333;}.ace-tm .ace_print_margin { width: 1px; background: #e8e8e8;}.ace-tm .ace_fold { background-color: #0000A2;}.ace-tm .ace_text-layer { cursor: text;}.ace-tm .ace_cursor { border-left: 2px solid black;}.ace-tm .ace_cursor.ace_overwrite { border-left: 0px; border-bottom: 1px solid black;} .ace-tm .ace_line .ace_invisible { color: rgb(191, 191, 191);}.ace-tm .ace_line .ace_keyword { color: blue;}.ace-tm .ace_line .ace_constant.ace_buildin { color: rgb(88, 72, 246);}.ace-tm .ace_line .ace_constant.ace_language { color: rgb(88, 92, 246);}.ace-tm .ace_line .ace_constant.ace_library { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_invalid { background-color: rgb(153, 0, 0); color: white;}.ace-tm .ace_line .ace_support.ace_function { color: rgb(60, 76, 114);}.ace-tm .ace_line .ace_support.ace_constant { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_support.ace_type,.ace-tm .ace_line .ace_support.ace_class { color: rgb(109, 121, 222);}.ace-tm .ace_line .ace_keyword.ace_operator { color: rgb(104, 118, 135);}.ace-tm .ace_line .ace_string { color: rgb(3, 106, 7);}.ace-tm .ace_line .ace_comment { color: rgb(76, 136, 107);}.ace-tm .ace_line .ace_comment.ace_doc { color: rgb(0, 102, 255);}.ace-tm .ace_line .ace_comment.ace_doc.ace_tag { color: rgb(128, 159, 191);}.ace-tm .ace_line .ace_constant.ace_numeric { color: rgb(0, 0, 205);}.ace-tm .ace_line .ace_variable { color: rgb(49, 132, 149);}.ace-tm .ace_line .ace_xml_pe { color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function { color: #0000A2;}.ace-tm .ace_markup.ace_markupine { text-decoration:underline;}.ace-tm .ace_markup.ace_heading { color: rgb(12, 7, 255);}.ace-tm .ace_markup.ace_list { color:rgb(185, 6, 144);}.ace-tm .ace_marker-layer .ace_selection { background: rgb(181, 213, 255);}.ace-tm .ace_marker-layer .ace_step { background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack { background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active_line { background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_marker-layer .ace_selected_word { background: rgb(250, 250, 255); border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_meta.ace_tag { color:rgb(28, 2, 255);}.ace-tm .ace_string.ace_regex { color: rgb(255, 0, 0)}";var d=a("../lib/dom");d.importCssString(b.cssText,b.cssClass)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +(function(){function g(a){var e=function(a,b){return d("",a,b)};e.packaged=!0;var f=b;a&&(b[a]||(b[a]={}),f=b[a]),f.define&&(c.original=f.define),f.define=c,f.require&&(d.original=f.require),f.require=e}var a="",b=function(){return this}();if(typeof requirejs!="undefined")return;var c=function(a,b,d){if(typeof a!="string"){c.original?c.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(d=b),c.modules||(c.modules={}),c.modules[a]=d},d=function(a,b,c){if(Object.prototype.toString.call(b)==="[object Array]"){var e=[];for(var g=0,h=b.length;g1&&h(b,"")>-1&&(i=RegExp(this.source,d.replace.call(g(this),"g","")),d.replace.call(a.slice(b.index),i,function(){for(var a=1;ab.index&&this.lastIndex--}return b},f||(RegExp.prototype.test=function(a){var b=d.exec.call(this,a);return b&&this.global&&!b[0].length&&this.lastIndex>b.index&&this.lastIndex--,!!b})}),define("ace/lib/es5-shim",["require","exports","module"],function(a,b,c){function p(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(b){}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if(typeof b!="function")throw new TypeError;var c=g.call(arguments,1),d=function(){if(this instanceof d){var e=function(){};e.prototype=b.prototype;var f=new e,h=b.apply(f,c.concat(g.call(arguments)));return h!==null&&Object(h)===h?h:f}return b.apply(a,c.concat(g.call(arguments)))};return d});var d=Function.prototype.call,e=Array.prototype,f=Object.prototype,g=e.slice,h=d.bind(f.toString),i=d.bind(f.hasOwnProperty),j,k,l,m,n;if(n=i(f,"__defineGetter__"))j=d.bind(f.__defineGetter__),k=d.bind(f.__defineSetter__),l=d.bind(f.__lookupGetter__),m=d.bind(f.__lookupSetter__);Array.isArray||(Array.isArray=function(a){return h(a)=="[object Array]"}),Array.prototype.forEach||(Array.prototype.forEach=function(a){var b=G(this),c=arguments[1],d=0,e=b.length>>>0;if(h(a)!="[object Function]")throw new TypeError;while(d>>0,d=Array(c),e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=[],e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d=0,e;if(arguments.length>=2)e=arguments[1];else do{if(d in b){e=b[d++];break}if(++d>=c)throw new TypeError}while(!0);for(;d>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d,e=c-1;if(arguments.length>=2)d=arguments[1];else do{if(e in b){d=b[e--];break}if(--e<0)throw new TypeError}while(!0);do e in this&&(d=a.call(void 0,d,b[e],e,b));while(e--);return d}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=G(this),c=b.length>>>0;if(!c)return-1;var d=0;arguments.length>1&&(d=E(arguments[1])),d=d>=0?d:Math.max(0,c+d);for(;d>>0;if(!c)return-1;var d=c-1;arguments.length>1&&(d=Math.min(d,E(arguments[1]))),d=d>=0?d:c-Math.abs(d);for(;d>=0;d--)if(d in b&&a===b[d])return d;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(a){return a.__proto__||(a.constructor?a.constructor.prototype:f)});if(!Object.getOwnPropertyDescriptor){var o="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(a,b){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(o+a);if(!i(a,b))return;var c,d,e;c={enumerable:!0,configurable:!0};if(n){var g=a.__proto__;a.__proto__=f;var d=l(a,b),e=m(a,b);a.__proto__=g;if(d||e)return d&&(c.get=d),e&&(c.set=e),c}return c.value=a[b],c}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(a){return Object.keys(a)}),Object.create||(Object.create=function(a,b){var c;if(a===null)c={"__proto__":null};else{if(typeof a!="object")throw new TypeError("typeof prototype["+typeof a+"] != 'object'");var d=function(){};d.prototype=a,c=new d,c.__proto__=a}return b!==void 0&&Object.defineProperties(c,b),c});if(Object.defineProperty){var q=p({}),r=typeof document=="undefined"||p(document.createElement("div"));if(!q||!r)var s=Object.defineProperty}if(!Object.defineProperty||s){var t="Property description must be an object: ",u="Object.defineProperty called on non-object: ",v="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(a,b,c){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(u+a);if(typeof c!="object"&&typeof c!="function"||c===null)throw new TypeError(t+c);if(s)try{return s.call(Object,a,b,c)}catch(d){}if(i(c,"value"))if(n&&(l(a,b)||m(a,b))){var e=a.__proto__;a.__proto__=f,delete a[b],a[b]=c.value,a.__proto__=e}else a[b]=c.value;else{if(!n)throw new TypeError(v);i(c,"get")&&j(a,b,c.get),i(c,"set")&&k(a,b,c.set)}return a}}Object.defineProperties||(Object.defineProperties=function(a,b){for(var c in b)i(b,c)&&Object.defineProperty(a,c,b[c]);return a}),Object.seal||(Object.seal=function(a){return a}),Object.freeze||(Object.freeze=function(a){return a});try{Object.freeze(function(){})}catch(w){Object.freeze=function(a){return function b(b){return typeof b=="function"?b:a(b)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(a){return a}),Object.isSealed||(Object.isSealed=function(a){return!1}),Object.isFrozen||(Object.isFrozen=function(a){return!1}),Object.isExtensible||(Object.isExtensible=function(a){if(Object(a)===a)throw new TypeError;var b="";while(i(a,b))b+="?";a[b]=!0;var c=i(a,b);return delete a[b],c});if(!Object.keys){var x=!0,y=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],z=y.length;for(var A in{toString:null})x=!1;Object.keys=function bd(a){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.keys called on a non-object");var bd=[];for(var b in a)i(a,b)&&bd.push(b);if(x)for(var c=0,d=z;c9999?"+":"")+("00000"+Math.abs(d)).slice(0<=d&&d<=9999?-4:-6),b=a.length;while(b--)c=a[b],c<10&&(a[b]="0"+c);return d+"-"+a.slice(0,2).join("-")+"T"+a.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};Date.now||(Date.now=function(){return(new Date).getTime()}),Date.prototype.toJSON||(Date.prototype.toJSON=function(a){if(typeof this.toISOString!="function")throw new TypeError;return this.toISOString()}),Date.parse("+275760-09-13T00:00:00.000Z")!==864e13&&(Date=function(a){var b=function e(b,c,d,f,g,h,i){var j=arguments.length;if(this instanceof a){var k=j==1&&String(b)===b?new a(e.parse(b)):j>=7?new a(b,c,d,f,g,h,i):j>=6?new a(b,c,d,f,g,h):j>=5?new a(b,c,d,f,g):j>=4?new a(b,c,d,f):j>=3?new a(b,c,d):j>=2?new a(b,c):j>=1?new a(b):new a;return k.constructor=e,k}return a.apply(this,arguments)},c=new RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$");for(var d in a)b[d]=a[d];return b.now=a.now,b.UTC=a.UTC,b.prototype=a.prototype,b.prototype.constructor=b,b.parse=function f(b){var d=c.exec(b);if(d){d.shift();for(var e=1;e<7;e++)d[e]=+(d[e]||(e<3?1:0)),e==1&&d[e]--;var f=+d.pop(),g=+d.pop(),h=d.pop(),i=0;if(h){if(g>23||f>59)return NaN;i=(g*60+f)*6e4*(h=="+"?-1:1)}var j=+d[0];return 0<=j&&j<=99?(d[0]=j+400,a.UTC.apply(this,d)+i-126227808e5):a.UTC.apply(this,d)+i}return a.parse.apply(this,arguments)},b}(Date));var B="\t\n \f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||B.trim()){B="["+B+"]";var C=new RegExp("^"+B+B+"*"),D=new RegExp(B+B+"*$");String.prototype.trim=function(){return String(this).replace(C,"").replace(D,"")}}var E=function(a){return a=+a,a!==a?a=0:a!==0&&a!==1/0&&a!==-Infinity&&(a=(a>0||-1)*Math.floor(Math.abs(a))),a},F="a"[0]!="a",G=function(a){if(a==null)throw new TypeError;return F&&typeof a=="string"&&a?a.split(""):Object(a)}}),define("ace/lib/dom",["require","exports","module"],function(a,b,c){"use strict";var d="http://www.w3.org/1999/xhtml";b.createElement=function(a,b){return document.createElementNS?document.createElementNS(b||d,a):document.createElement(a)},b.setText=function(a,b){a.innerText!==undefined&&(a.innerText=b),a.textContent!==undefined&&(a.textContent=b)},b.hasCssClass=function(a,b){var c=a.className.split(/\s+/g);return c.indexOf(b)!==-1},b.addCssClass=function(a,c){b.hasCssClass(a,c)||(a.className+=" "+c)},b.removeCssClass=function(a,b){var c=a.className.split(/\s+/g);for(;;){var d=c.indexOf(b);if(d==-1)break;c.splice(d,1)}a.className=c.join(" ")},b.toggleCssClass=function(a,b){var c=a.className.split(/\s+/g),d=!0;for(;;){var e=c.indexOf(b);if(e==-1)break;d=!1,c.splice(e,1)}return d&&c.push(b),a.className=c.join(" "),d},b.setCssClass=function(a,c,d){d?b.addCssClass(a,c):b.removeCssClass(a,c)},b.hasCssString=function(a,b){var c=0,d;b=b||document;if(b.createStyleSheet&&(d=b.styleSheets)){while(cd&&(d=Math.abs(a.wheelDeltaY));if(d>5e3)var b=400;else var b=8;a.wheelDeltaX!==undefined?(a.wheelX=-a.wheelDeltaX/b,a.wheelY=-a.wheelDeltaY/b):(a.wheelX=0,a.wheelY=-a.wheelDelta/b)}else a.axis&&a.axis==a.HORIZONTAL_AXIS?(a.wheelX=(a.detail||0)*5,a.wheelY=0):(a.wheelX=0,a.wheelY=(a.detail||0)*5);c(a)};b.addListener(a,"DOMMouseScroll",e),b.addListener(a,"mousewheel",e)},b.addMultiMouseDownListener=function(a,c,d,f,g){var h=0,i,j,k=function(a){h+=1,h==1&&(i=a.clientX,j=a.clientY,setTimeout(function(){h=0},f||600));var e=b.getButton(a)==c;if(!e||Math.abs(a.clientX-i)>5||Math.abs(a.clientY-j)>5)h=0;h==d&&(h=0,g(a));if(e)return b.preventDefault(a)};b.addListener(a,"mousedown",k),e.isOldIE&&b.addListener(a,"dblclick",k)},b.addCommandKeyListener=function(a,c){var d=b.addListener;if(e.isOldGecko){var f=null;d(a,"keydown",function(a){f=a.keyCode}),d(a,"keypress",function(a){return g(c,a,f)})}else{var h=null;d(a,"keydown",function(a){return h=a.keyIdentifier||a.keyCode,g(c,a,a.keyCode)}),e.isMac&&e.isOpera&&d(a,"keypress",function(a){var b=a.keyIdentifier||a.keyCode;if(h!==b)return g(c,a,h);h=null})}};if(window.postMessage){var h=1;b.nextTick=function(a,c){c=c||window;var d="zero-timeout-message-"+h;b.addListener(c,"message",function e(f){f.data==d&&(b.stopPropagation(f),b.removeListener(c,"message",e),a())}),c.postMessage(d,"*")}}else b.nextTick=function(a,b){b=b||window,window.setTimeout(a,0)}}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(a,b,c){"use strict";var d=a("./oop"),e=function(){var a={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,meta:8,command:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:'"'}};for(var b in a.FUNCTION_KEYS){var c=a.FUNCTION_KEYS[b].toUpperCase();a[c]=parseInt(b,10)}return d.mixin(a,a.MODIFIER_KEYS),d.mixin(a,a.PRINTABLE_KEYS),d.mixin(a,a.FUNCTION_KEYS),a}();d.mixin(b,e),b.keyCodeToString=function(a){return(e[a]||String.fromCharCode(a)).toLowerCase()}}),define("ace/lib/oop",["require","exports","module"],function(a,b,c){"use strict",b.inherits=function(){var a=function(){};return function(b,c){a.prototype=c.prototype,b.super_=c.prototype,b.prototype=new a,b.prototype.constructor=b}}(),b.mixin=function(a,b){for(var c in b)a[c]=b[c]},b.implement=function(a,c){b.mixin(a,c)}}),define("ace/lib/useragent",["require","exports","module"],function(a,b,c){"use strict";var d=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),e=navigator.userAgent;b.isWin=d=="win",b.isMac=d=="mac",b.isLinux=d=="linux",b.isIE=navigator.appName=="Microsoft Internet Explorer"&&parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]),b.isOldIE=b.isIE&&b.isIE<9,b.isGecko=b.isMozilla=window.controllers&&window.navigator.product==="Gecko",b.isOldGecko=b.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,b.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",b.isWebKit=parseFloat(e.split("WebKit/")[1])||undefined,b.isChrome=parseFloat(e.split(" Chrome/")[1])||undefined,b.isAIR=e.indexOf("AdobeAIR")>=0,b.isIPad=e.indexOf("iPad")>=0,b.isTouchPad=e.indexOf("TouchPad")>=0,b.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},b.getOS=function(){return b.isMac?b.OS.MAC:b.isLinux?b.OS.LINUX:b.OS.WINDOWS}}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands"],function(a,b,c){"use strict",a("./lib/fixoldbrowsers");var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/useragent"),g=a("./keyboard/textinput").TextInput,h=a("./mouse/mouse_handler").MouseHandler,i=a("./mouse/fold_handler").FoldHandler,j=a("./keyboard/keybinding").KeyBinding,k=a("./edit_session").EditSession,l=a("./search").Search,m=a("./range").Range,n=a("./lib/event_emitter").EventEmitter,o=a("./commands/command_manager").CommandManager,p=a("./commands/default_commands").commands,q=function(a,b){var c=a.getContainerElement();this.container=c,this.renderer=a,this.textInput=new g(a.getTextAreaContainer(),this),this.keyBinding=new j(this),f.isIPad||(this.$mouseHandler=new h(this),new i(this)),this.$blockScrolling=0,this.$search=(new l).set({wrap:!0}),this.commands=new o(f.isMac?"mac":"win",p),this.setSession(b||new k(""))};((function(){d.implement(this,n),this.setKeyboardHandler=function(a){this.keyBinding.setKeyboardHandler(a)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(a){if(this.session==a)return;if(this.session){var b=this.session;this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeLeftTop",this.$onScrollLeftChange);var c=this.session.getSelection();c.removeEventListener("changeCursor",this.$onCursorChange),c.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=a,this.$onDocumentChange=this.onDocumentChange.bind(this),a.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(a),this.$onChangeMode=this.onChangeMode.bind(this),a.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),a.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.updateText.bind(this.renderer),a.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),a.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),a.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),a.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=a.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.onCursorChange(),this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull(),this._emit("changeSession",{session:a,oldSession:b})},this.getSession=function(){return this.session},this.getSelection=function(){return this.selection},this.resize=function(){this.renderer.onResize()},this.setTheme=function(a){this.renderer.setTheme(a)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(a){this.renderer.setStyle(a)},this.unsetStyle=function(a){this.renderer.unsetStyle(a)},this.setFontSize=function(a){this.container.style.fontSize=a},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var a=this;this.$highlightPending=!0,setTimeout(function(){a.$highlightPending=!1;var b=a.session.findMatchingBracket(a.getCursorPosition());if(b){var c=new m(b.row,b.column,b.row,b.column+1);a.session.$bracketHighlight=a.session.addMarker(c,"ace_bracket","text")}},10)},this.focus=function(){var a=this;setTimeout(function(){a.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.onDocumentChange=function(a){var b=a.data,c=b.range,d;c.start.row==c.end.row&&b.action!="insertLines"&&b.action!="removeLines"?d=c.end.row:d=Infinity,this.renderer.updateLines(c.start.row,d),this._emit("change",a),this.onCursorChange()},this.onTokenizerUpdate=function(a){var b=a.data;this.renderer.updateLines(b.first,b.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.renderer.updateCursor(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.renderer.moveTextAreaToCursor(this.textInput.getElement()),this.$highlightBrackets(),this.$updateHighlightActiveLine()},this.$updateHighlightActiveLine=function(){var a=this.getSession();a.$highlightLineMarker&&a.removeMarker(a.$highlightLineMarker),a.$highlightLineMarker=null;if(this.getHighlightActiveLine()&&(this.getSelectionStyle()!="line"||!this.selection.isMultiLine())){var b=this.getCursorPosition(),c=this.session.getFoldLine(b.row),d;c?d=new m(c.start.row,0,c.end.row+1,0):d=new m(b.row,0,b.row+1,0),a.$highlightLineMarker=a.addMarker(d,"ace_active_line","background")}},this.onSelectionChange=function(a){var b=this.getSession();b.$selectionMarker&&b.removeMarker(b.$selectionMarker),b.$selectionMarker=null;if(!this.selection.isEmpty()){var c=this.selection.getRange(),d=this.getSelectionStyle();b.$selectionMarker=b.addMarker(c,"ace_selection",d)}else this.$updateHighlightActiveLine();this.$highlightSelectedWord&&this.session.getMode().highlightSelection(this)},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.setBreakpoints(this.session.getBreakpoints())},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(){this.renderer.updateText()},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getCopyText=function(){var a="";return this.selection.isEmpty()||(a=this.session.getTextRange(this.getSelectionRange())),this._emit("copy",a),a},this.onCut=function(){if(this.$readOnly)return;var a=this.getSelectionRange();this._emit("cut",a),this.selection.isEmpty()||(this.session.remove(a),this.clearSelection())},this.insert=function(a){var b=this.session,c=b.getMode(),d=this.getCursorPosition();if(this.getBehavioursEnabled()){var e=c.transformAction(b.getState(d.row),"insertion",this,b,a);e&&(a=e.text)}a=a.replace("\t",this.session.getTabString());if(!this.selection.isEmpty())d=this.session.remove(this.getSelectionRange()),this.clearSelection();else if(this.session.getOverwrite()){var f=new m.fromPoints(d,d);f.end.column+=a.length,this.session.remove(f)}this.clearSelection();var g=d.column,h=b.getState(d.row),i=c.checkOutdent(h,b.getLine(d.row),a),j=b.getLine(d.row),k=c.getNextLineIndent(h,j.slice(0,d.column),b.getTabString()),l=b.insert(d,a);e&&e.selection&&(e.selection.length==2?this.selection.setSelectionRange(new m(d.row,g+e.selection[0],d.row,g+e.selection[1])):this.selection.setSelectionRange(new m(d.row+e.selection[0],e.selection[1],d.row+e.selection[2],e.selection[3])));var h=b.getState(d.row);if(b.getDocument().isNewLine(a)){this.moveCursorTo(d.row+1,0);var n=b.getTabSize(),o=Number.MAX_VALUE;for(var p=d.row+1;p<=l.row;++p){var q=0;j=b.getLine(p);for(var r=0;r0;++r)j.charAt(r)=="\t"?s-=n:j.charAt(r)==" "&&(s-=1);b.remove(new m(p,0,p,r))}b.indentRows(d.row+1,l.row,k)}i&&c.autoOutdent(h,b,d.row)},this.onTextInput=function(a,b){b&&this._emit("paste",a),this.keyBinding.onTextInput(a,b)},this.onCommandKey=function(a,b,c){this.keyBinding.onCommandKey(a,b,c)},this.setOverwrite=function(a){this.session.setOverwrite(a)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(a){this.$mouseHandler.setScrollSpeed(a)},this.getScrollSpeed=function(){return this.$mouseHandler.getScrollSpeed()},this.setDragDelay=function(a){this.$mouseHandler.setDragDelay(a)},this.getDragDelay=function(){return this.$mouseHandler.getDragDelay()},this.$selectionStyle="line",this.setSelectionStyle=function(a){if(this.$selectionStyle==a)return;this.$selectionStyle=a,this.onSelectionChange(),this._emit("changeSelectionStyle",{data:a})},this.getSelectionStyle=function(){return this.$selectionStyle},this.$highlightActiveLine=!0,this.setHighlightActiveLine=function(a){if(this.$highlightActiveLine==a)return;this.$highlightActiveLine=a,this.$updateHighlightActiveLine()},this.getHighlightActiveLine=function(){return this.$highlightActiveLine},this.$highlightSelectedWord=!0,this.setHighlightSelectedWord=function(a){if(this.$highlightSelectedWord==a)return;this.$highlightSelectedWord=a,a?this.session.getMode().highlightSelection(this):this.session.getMode().clearSelectionHighlight(this)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setShowInvisibles=function(a){if(this.getShowInvisibles()==a)return;this.renderer.setShowInvisibles(a)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setShowPrintMargin=function(a){this.renderer.setShowPrintMargin(a)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(a){this.renderer.setPrintMarginColumn(a)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.$readOnly=!1,this.setReadOnly=function(a){this.$readOnly=a},this.getReadOnly=function(){return this.$readOnly},this.$modeBehaviours=!0,this.setBehavioursEnabled=function(a){this.$modeBehaviours=a},this.getBehavioursEnabled=function(){return this.$modeBehaviours},this.setShowFoldWidgets=function(a){var b=this.renderer.$gutterLayer;if(b.getShowFoldWidgets()==a)return;this.renderer.$gutterLayer.setShowFoldWidgets(a),this.$showFoldWidgets=a,this.renderer.updateFull()},this.getShowFoldWidgets=function(){return this.renderer.$gutterLayer.getShowFoldWidgets()},this.remove=function(a){this.selection.isEmpty()&&(a=="left"?this.selection.selectLeft():this.selection.selectRight());var b=this.getSelectionRange();if(this.getBehavioursEnabled()){var c=this.session,d=c.getState(b.start.row),e=c.getMode().transformAction(d,"deletion",this,c,b);e&&(b=e)}this.session.remove(b),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var a=this.getSelectionRange();a.start.column==a.end.column&&a.start.row==a.end.row&&(a.end.column=0,a.end.row++),this.session.remove(a),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var a=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(a)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var a=this.getCursorPosition(),b=a.column;if(b===0)return;var c=this.session.getLine(a.row),d,e;b=this.getFirstVisibleRow()&&a<=this.getLastVisibleRow()},this.isRowFullyVisible=function(a){return a>=this.renderer.getFirstFullyVisibleRow()&&a<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$getPageDownRow=function(){return this.renderer.getScrollBottomRow()},this.$getPageUpRow=function(){var a=this.renderer.getScrollTopRow(),b=this.renderer.getScrollBottomRow();return a-(b-a)},this.selectPageDown=function(){var a=this.$getPageDownRow()+Math.floor(this.$getVisibleRowCount()/2);this.scrollPageDown();var b=this.getSelection(),c=this.session.documentToScreenPosition(b.getSelectionLead()),d=this.session.screenToDocumentPosition(a,c.column);b.selectTo(d.row,d.column)},this.selectPageUp=function(){var a=this.renderer.getScrollTopRow()-this.renderer.getScrollBottomRow(),b=this.$getPageUpRow()+Math.round(a/2);this.scrollPageUp();var c=this.getSelection(),d=this.session.documentToScreenPosition(c.getSelectionLead()),e=this.session.screenToDocumentPosition(b,d.column);c.selectTo(e.row,e.column)},this.gotoPageDown=function(){var a=this.$getPageDownRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.gotoPageUp=function(){var a=this.$getPageUpRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.scrollPageDown=function(){this.scrollToRow(this.$getPageDownRow())},this.scrollPageUp=function(){this.renderer.scrollToRow(this.$getPageUpRow())},this.scrollToRow=function(a){this.renderer.scrollToRow(a)},this.scrollToLine=function(a,b){this.renderer.scrollToLine(a,b)},this.centerSelection=function(){var a=this.getSelectionRange(),b=Math.floor(a.start.row+(a.end.row-a.start.row)/2);this.renderer.scrollToLine(b,!0)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(a,b){this.selection.moveCursorTo(a,b)},this.moveCursorToPosition=function(a){this.selection.moveCursorToPosition(a)},this.jumpToMatching=function(){var a=this.getCursorPosition(),b=this.session.findMatchingBracket(a);b||(a.column+=1,b=this.session.findMatchingBracket(a)),b||(a.column-=2,b=this.session.findMatchingBracket(a)),b&&(this.clearSelection(),this.moveCursorTo(b.row,b.column))},this.gotoLine=function(a,b){this.selection.clearSelection(),this.session.unfold({row:a-1,column:b||0}),this.$blockScrolling+=1,this.moveCursorTo(a-1,b||0),this.$blockScrolling-=1,this.isRowFullyVisible(this.getCursorPosition().row)||this.scrollToLine(a,!0)},this.navigateTo=function(a,b){this.clearSelection(),this.moveCursorTo(a,b)},this.navigateUp=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(-a,0)},this.navigateDown=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(a,0)},this.navigateLeft=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().start;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().end;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(a,b){b&&this.$search.set(b);var c=this.$search.find(this.session);if(!c)return;this.$tryReplace(c,a),c!==null&&this.selection.setSelectionRange(c)},this.replaceAll=function(a,b){b&&this.$search.set(b);var c=this.$search.findAll(this.session);if(!c.length)return;var d=this.getSelectionRange();this.clearSelection(),this.selection.moveCursorTo(0,0),this.$blockScrolling+=1;for(var e=c.length-1;e>=0;--e)this.$tryReplace(c[e],a);this.selection.setSelectionRange(d),this.$blockScrolling-=1},this.$tryReplace=function(a,b){var c=this.session.getTextRange(a);return b=this.$search.replace(c,b),b!==null?(a.end=this.session.replace(a,b),a):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(a,b){this.clearSelection(),b=b||{},b.needle=a,this.$search.set(b),this.$find()},this.findNext=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!1),this.$search.set(a),this.$find()},this.findPrevious=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!0),this.$search.set(a),this.$find()},this.$find=function(a){this.selection.isEmpty()||this.$search.set({needle:this.session.getTextRange(this.getSelectionRange())}),typeof a!="undefined"&&this.$search.set({backwards:a});var b=this.$search.find(this.session);b&&(this.session.unfold(b),this.gotoLine(b.end.row+1,b.end.column),this.selection.setSelectionRange(b))},this.undo=function(){this.session.getUndoManager().undo()},this.redo=function(){this.session.getUndoManager().redo()},this.destroy=function(){this.renderer.destroy()}})).call(q.prototype),b.Editor=q}),define("ace/lib/lang",["require","exports","module"],function(a,b,c){"use strict",b.stringReverse=function(a){return a.split("").reverse().join("")},b.stringRepeat=function(a,b){return(new Array(b+1)).join(a)};var d=/^\s\s*/,e=/\s\s*$/;b.stringTrimLeft=function(a){return a.replace(d,"")},b.stringTrimRight=function(a){return a.replace(e,"")},b.copyObject=function(a){var b={};for(var c in a)b[c]=a[c];return b},b.copyArray=function(a){var b=[];for(var c=0,d=a.length;c128)return;setTimeout(function(){h||m()},0)},p=function(a){h=!0,b.onCompositionStart(),e.isGecko||setTimeout(q,0)},q=function(){if(!h)return;b.onCompositionUpdate(c.value)},r=function(a){h=!1,b.onCompositionEnd()},s=function(a){i=!0;var d=b.getCopyText();d?c.value=d:a.preventDefault(),l(),setTimeout(function(){m()},0)},t=function(a){i=!0;var d=b.getCopyText();d?(c.value=d,b.onCut()):a.preventDefault(),l(),setTimeout(function(){m()},0)};d.addCommandKeyListener(c,b.onCommandKey.bind(b));if(e.isOldIE){var u={13:1,27:1};d.addListener(c,"keyup",function(a){h&&(!c.value||u[a.keyCode])&&setTimeout(r,0);if((c.value.charCodeAt(0)|0)<129)return;h?q():p()})}"onpropertychange"in c&&!("oninput"in c)?d.addListener(c,"propertychange",o):d.addListener(c,"input",n),d.addListener(c,"paste",function(a){j=!0,a.clipboardData&&a.clipboardData.getData?(m(a.clipboardData.getData("text/plain")),a.preventDefault()):o()}),"onbeforecopy"in c&&typeof clipboardData!="undefined"?(d.addListener(c,"beforecopy",function(a){var c=b.getCopyText();c?clipboardData.setData("Text",c):a.preventDefault()}),d.addListener(a,"keydown",function(a){if(a.ctrlKey&&a.keyCode==88){var c=b.getCopyText();c&&(clipboardData.setData("Text",c),b.onCut()),d.preventDefault(a)}})):(d.addListener(c,"copy",s),d.addListener(c,"cut",t)),d.addListener(c,"compositionstart",p),e.isGecko&&d.addListener(c,"text",q),e.isWebKit&&d.addListener(c,"keyup",q),d.addListener(c,"compositionend",r),d.addListener(c,"blur",function(){b.onBlur()}),d.addListener(c,"focus",function(){b.onFocus(),l()}),this.focus=function(){b.onFocus(),l(),c.focus()},this.blur=function(){c.blur()},this.isFocused=v,this.getElement=function(){return c},this.onContextMenu=function(a,b){a&&(k||(k=c.style.cssText),c.style.cssText="position:fixed; z-index:1000;left:"+(a.x-2)+"px; top:"+(a.y-2)+"px;"),b&&(c.value="")},this.onContextMenuClose=function(){setTimeout(function(){k&&(c.style.cssText=k,k=""),m()},0)}};b.TextInput=g}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event"],function(a,b,c){"use strict";var d=a("../lib/event"),e=a("./default_handlers").DefaultHandlers,f=a("./default_gutter_handler").GutterHandler,g=a("./mouse_event").MouseEvent,h=function(a){this.editor=a,new e(a),new f(a),d.addListener(a.container,"mousedown",function(b){return a.focus(),d.preventDefault(b)}),d.addListener(a.container,"selectstart",function(a){return d.preventDefault(a)});var b=a.renderer.getMouseEventTarget();d.addListener(b,"mousedown",this.onMouseEvent.bind(this,"mousedown")),d.addListener(b,"click",this.onMouseEvent.bind(this,"click")),d.addListener(b,"mousemove",this.onMouseMove.bind(this,"mousemove")),d.addMultiMouseDownListener(b,0,2,500,this.onMouseEvent.bind(this,"dblclick")),d.addMultiMouseDownListener(b,0,3,600,this.onMouseEvent.bind(this,"tripleclick")),d.addMultiMouseDownListener(b,0,4,600,this.onMouseEvent.bind(this,"quadclick")),d.addMouseWheelListener(a.container,this.onMouseWheel.bind(this,"mousewheel"));var c=a.renderer.$gutter;d.addListener(c,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),d.addListener(c,"click",this.onMouseEvent.bind(this,"gutterclick")),d.addListener(c,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),d.addListener(c,"mousemove",this.onMouseMove.bind(this,"gutter"))};((function(){this.$scrollSpeed=1,this.setScrollSpeed=function(a){this.$scrollSpeed=a},this.getScrollSpeed=function(){return this.$scrollSpeed},this.onMouseEvent=function(a,b){this.editor._emit(a,new g(b,this.editor))},this.$dragDelay=250,this.setDragDelay=function(a){this.$dragDelay=a},this.getDragDelay=function(){return this.$dragDelay},this.onMouseMove=function(a,b){var c=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!c||!c.length)return;this.editor._emit(a,new g(b,this.editor))},this.onMouseWheel=function(a,b){var c=new g(b,this.editor);c.speed=this.$scrollSpeed*2,c.wheelX=b.wheelX,c.wheelY=b.wheelY,this.editor._emit(a,c)}})).call(h.prototype),b.MouseHandler=h}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/event","ace/lib/dom","ace/lib/browser_focus"],function(a,b,c){function k(a){this.editor=a,this.$clickSelection=null,this.browserFocus=new f,a.setDefaultHandler("mousedown",this.onMouseDown.bind(this)),a.setDefaultHandler("dblclick",this.onDoubleClick.bind(this)),a.setDefaultHandler("tripleclick",this.onTripleClick.bind(this)),a.setDefaultHandler("quadclick",this.onQuadClick.bind(this)),a.setDefaultHandler("mousewheel",this.onScroll.bind(this))}function l(a,b,c,d){return Math.sqrt(Math.pow(c-a,2)+Math.pow(d-b,2))}"use strict";var d=a("../lib/event"),e=a("../lib/dom"),f=a("../lib/browser_focus").BrowserFocus,g=0,h=1,i=2,j=5;((function(){this.onMouseDown=function(a){function C(b){a.getShiftKey()?m.selection.selectToPosition(b):n.$clickSelection||(m.moveCursorToPosition(b),m.selection.clearSelection(b.row,b.column)),q=h}var b=a.inSelection(),c=a.pageX,f=a.pageY,k=a.getDocumentPosition(),m=this.editor,n=this,o=m.getSelectionRange(),p=o.isEmpty(),q=g;if(b&&(!this.browserFocus.isFocused()||(new Date).getTime()-this.browserFocus.lastFocus<20||!m.isFocused())){m.focus();return}var r=a.getButton();if(r!==0){p&&m.moveCursorToPosition(k),r==2&&(m.textInput.onContextMenu({x:a.clientX,y:a.clientY},p),d.capture(m.container,function(){},m.textInput.onContextMenuClose));return}b||C(k);var s=c,t=f,u=(new Date).getTime(),v,w,x,y=function(a){s=d.getDocumentX(a),t=d.getDocumentY(a)},z=function(a){clearInterval(F),q==g?C(k):q==i&&A(a),n.$clickSelection=null,q=g},A=function(a){e.removeCssClass(m.container,"ace_dragging"),m.session.removeMarker(x),m.$mouseHandler.$clickSelection||v||(m.moveCursorToPosition(k),m.selection.clearSelection(k.row,k.column));if(!v)return;if(w.contains(v.row,v.column)){v=null;return}m.clearSelection();if(a&&(a.ctrlKey||a.altKey))var b=m.session,c=b.insert(v,b.getTextRange(w));else var c=m.moveText(w,v);if(!c){v=null;return}m.selection.setSelectionRange(c)},B=function(){if(q==g){var a=l(c,f,s,t),b=(new Date).getTime();if(a>j){q=h;var d=m.renderer.screenToTextCoordinates(s,t);d.row=Math.max(0,Math.min(d.row,m.session.getLength()-1)),C(d)}else if(b-u>m.getDragDelay()){q=i,w=m.getSelectionRange();var k=m.getSelectionStyle();x=m.session.addMarker(w,"ace_selection",k),m.clearSelection(),e.addCssClass(m.container,"ace_dragging")}}q==i?E():q==h&&D()},D=function(){var a,b=m.renderer.screenToTextCoordinates(s,t);b.row=Math.max(0,Math.min(b.row,m.session.getLength()-1)),n.$clickSelection?n.$clickSelection.contains(b.row,b.column)?m.selection.setSelectionRange(n.$clickSelection):(n.$clickSelection.compare(b.row,b.column)==-1?a=n.$clickSelection.end:a=n.$clickSelection.start,m.selection.setSelectionAnchor(a.row,a.column),m.selection.selectToPosition(b)):m.selection.selectToPosition(b),m.renderer.scrollCursorIntoView()},E=function(){v=m.renderer.screenToTextCoordinates(s,t),v.row=Math.max(0,Math.min(v.row,m.session.getLength()-1)),m.moveCursorToPosition(v)};d.capture(m.container,y,z);var F=setInterval(B,20);return a.preventDefault()},this.onDoubleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectWord(),this.$clickSelection=c.getSelectionRange()},this.onTripleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectLine(),this.$clickSelection=c.getSelectionRange()},this.onQuadClick=function(a){var b=this.editor;b.selectAll(),this.$clickSelection=b.getSelectionRange()},this.onScroll=function(a){var b=this.editor;b.renderer.scrollBy(a.wheelX*a.speed,a.wheelY*a.speed);if(b.renderer.isScrollableBy(a.wheelX*a.speed,a.wheelY*a.speed))return a.preventDefault()}})).call(k.prototype),b.DefaultHandlers=k}),define("ace/lib/browser_focus",["require","exports","module","ace/lib/oop","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./oop"),e=a("./event"),f=a("./event_emitter").EventEmitter,g=function(a){a=a||window,this.lastFocus=(new Date).getTime(),this._isFocused=!0;var b=this;"onfocusin"in a.document?(e.addListener(a.document,"focusin",function(a){b._setFocused(!0)}),e.addListener(a.document,"focusout",function(a){b._setFocused(!!a.toElement)})):(e.addListener(a,"blur",function(a){b._setFocused(!1)}),e.addListener(a,"focus",function(a){b._setFocused(!0)}))};((function(){d.implement(this,f),this.isFocused=function(){return this._isFocused},this._setFocused=function(a){if(this._isFocused==a)return;a&&(this.lastFocus=(new Date).getTime()),this._isFocused=a,this._emit("changeFocus")}})).call(g.prototype),b.BrowserFocus=g}),define("ace/lib/event_emitter",["require","exports","module"],function(a,b,c){"use strict";var d={};d._emit=d._dispatchEvent=function(a,b){this._eventRegistry=this._eventRegistry||{},this._defaultHandlers=this._defaultHandlers||{};var c=this._eventRegistry[a]||[],d=this._defaultHandlers[a];if(!c.length&&!d)return;b=b||{},b.type=a,b.stopPropagation||(b.stopPropagation=function(){this.propagationStopped=!0}),b.preventDefault||(b.preventDefault=function(){this.defaultPrevented=!0});for(var e=0;e=4352&&a<=4447||a>=4515&&a<=4519||a>=4602&&a<=4607||a>=9001&&a<=9002||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12283||a>=12288&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12589||a>=12593&&a<=12686||a>=12688&&a<=12730||a>=12736&&a<=12771||a>=12784&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=13054||a>=13056&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=55216&&a<=55238||a>=55243&&a<=55291||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=65281&&a<=65376||a>=65504&&a<=65510}d.implement(this,f),this.setDocument=function(a){if(this.doc)throw new Error("Document is already set");this.doc=a,a.on("change",this.onChange.bind(this)),this.on("changeFold",this.onChangeFold.bind(this)),this.bgTokenizer&&(this.bgTokenizer.setDocument(this.getDocument()),this.bgTokenizer.start(0))},this.getDocument=function(){return this.doc},this.$resetRowCache=function(a){if(a==0){this.$rowCache=[];return}var b=this.$rowCache;for(var c=0;c=a){b.splice(c,b.length);return}},this.onChangeFold=function(a){var b=a.data;this.$resetRowCache(b.start.row)},this.onChange=function(a){var b=a.data;this.$modified=!0,this.$resetRowCache(b.range.start.row);var c=this.$updateInternalDataOnChange(a);!this.$fromUndo&&this.$undoManager&&!b.ignore&&(this.$deltasDoc.push(b),c&&c.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:c}),this.$informUndoManager.schedule()),this.bgTokenizer.start(b.range.start.row),this._emit("change",a)},this.setValue=function(a){this.doc.setValue(a),this.selection.moveCursorTo(0,0),this.selection.clearSelection(),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(a){return this.bgTokenizer.getState(a)},this.getTokens=function(a,b){return this.bgTokenizer.getTokens(a,b)},this.getTokenAt=function(a,b){var c=this.bgTokenizer.getTokens(a,a)[0].tokens,d,e=0;if(b==null)f=c.length-1,e=this.getLine(a).length;else for(var f=0;f=b)break}return d=c[f],d?(d.index=f,d.start=e-d.value.length,d):null},this.setUndoManager=function(a){this.$undoManager=a,this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(a){var b=this;this.$syncInformUndoManager=function(){b.$informUndoManager.cancel(),b.$deltasFold.length&&(b.$deltas.push({group:"fold",deltas:b.$deltasFold}),b.$deltasFold=[]),b.$deltasDoc.length&&(b.$deltas.push({group:"doc",deltas:b.$deltasDoc}),b.$deltasDoc=[]),b.$deltas.length>0&&a.execute({action:"aceupdate",args:[b.$deltas,b]}),b.$deltas=[]},this.$informUndoManager=e.deferredCall(this.$syncInformUndoManager)}},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?e.stringRepeat(" ",this.getTabSize()):"\t"},this.$useSoftTabs=!0,this.setUseSoftTabs=function(a){if(this.$useSoftTabs===a)return;this.$useSoftTabs=a},this.getUseSoftTabs=function(){return this.$useSoftTabs},this.$tabSize=4,this.setTabSize=function(a){if(isNaN(a)||this.$tabSize===a)return;this.$modified=!0,this.$tabSize=a,this._emit("changeTabSize")},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(a){return this.$useSoftTabs&&a.column%this.$tabSize==0},this.$overwrite=!1,this.setOverwrite=function(a){if(this.$overwrite==a)return;this.$overwrite=a,this._emit("changeOverwrite")},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(a){this.$breakpoints=[];for(var b=0;b0&&(d=!!c.charAt(b-1).match(this.tokenRe)),d||(d=!!c.charAt(b).match(this.tokenRe));var e=d?this.tokenRe:this.nonTokenRe,f=b;if(f>0){do f--;while(f>=0&&c.charAt(f).match(e));f++}var g=b;while(g=this.doc.getLength()-1)return 0;var c=this.doc.removeLines(a,b);return this.doc.insertLines(a+1,c),1},this.duplicateLines=function(a,b){var a=this.$clipRowToDocument(a),b=this.$clipRowToDocument(b),c=this.getLines(a,b);this.doc.insertLines(a,c);var d=b-a+1;return d},this.$clipRowToDocument=function(a){return Math.max(0,Math.min(a,this.doc.getLength()-1))},this.$clipColumnToRow=function(a,b){return b<0?0:Math.min(this.doc.getLine(a).length,b)},this.$clipPositionToDocument=function(a,b){b=Math.max(0,b);if(a<0)a=0,b=0;else{var c=this.doc.getLength();a>=c?(a=c-1,b=this.doc.getLine(c-1).length):b=Math.min(this.doc.getLine(a).length,b)}return{row:a,column:b}},this.$clipRangeToDocument=function(a){a.start.row<0?(a.start.row=0,a.start.column=0):a.start.column=this.$clipColumnToRow(a.start.row,a.start.column);var b=this.doc.getLength()-1;return a.end.row>b?(a.end.row=b,a.end.column=this.doc.getLine(b).length):a.end.column=this.$clipColumnToRow(a.end.row,a.end.column),a},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(a){if(a!=this.$useWrapMode){this.$useWrapMode=a,this.$modified=!0,this.$resetRowCache(0);if(a){var b=this.getLength();this.$wrapData=[];for(var c=0;c0?(this.$wrapLimit=b,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._emit("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(a){var b=this.$wrapLimitRange.min;b&&(a=Math.max(b,a));var c=this.$wrapLimitRange.max;return c&&(a=Math.min(c,a)),Math.max(1,a)},this.getWrapLimit=function(){return this.$wrapLimit},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(a){var b=this.$useWrapMode,c,d=a.data.action,e=a.data.range.start.row,f=a.data.range.end.row,g=a.data.range.start,h=a.data.range.end,i=null;d.indexOf("Lines")!=-1?(d=="insertLines"?f=e+a.data.lines.length:f=e,c=a.data.lines?a.data.lines.length:f-e):c=f-e;if(c!=0)if(d.indexOf("remove")!=-1){b&&this.$wrapData.splice(e,c);var j=this.$foldData;i=this.getFoldsInRange(a.data.range),this.removeFolds(i);var k=this.getFoldLine(h.row),l=0;if(k){k.addRemoveChars(h.row,h.column,g.column-h.column),k.shiftRow(-c);var m=this.getFoldLine(e);m&&m!==k&&(m.merge(k),k=m),l=j.indexOf(k)+1}for(l;l=h.row&&k.shiftRow(-c)}f=e}else{var n;if(b){n=[e,0];for(var o=0;o=e&&k.shiftRow(c)}}else{c=Math.abs(a.data.range.start.column-a.data.range.end.column),d.indexOf("remove")!=-1&&(i=this.getFoldsInRange(a.data.range),this.removeFolds(i),c=-c);var k=this.getFoldLine(e);k&&k.addRemoveChars(e,g.column,c)}return b&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),b&&this.$updateWrapData(e,f),i},this.$updateWrapData=function(a,b){var c=this.doc.getAllLines(),d=this.getTabSize(),f=this.$wrapData,i=this.$wrapLimit,j,k,m=a;b=Math.min(b,c.length-1);while(m<=b){k=this.getFoldLine(m,k);if(!k)j=this.$getDisplayTokens(e.stringTrimRight(c[m])),f[m]=this.$computeWrapSplits(j,i,d),m++;else{j=[],k.walk(function(a,b,d,e){var f;if(a){f=this.$getDisplayTokens(a,j.length),f[0]=g;for(var i=1;i=l)j.pop();f[k.start.row]=this.$computeWrapSplits(j,i,d),m=k.end.row+1}}};var b=1,c=2,g=3,h=4,j=9,l=10,m=11,n=12;this.$computeWrapSplits=function(a,b){function i(b){var d=a.slice(e,b),g=d.length;d.join("").replace(/12/g,function(){g-=1}).replace(/2/g,function(){g-=1}),f+=g,c.push(f),e=b}if(a.length==0)return[];var c=[],d=a.length,e=0,f=0;while(d-e>b){var k=e+b;if(a[k]>=l){while(a[k]>=l)k++;i(k);continue}if(a[k]==g||a[k]==h){for(k;k!=e-1;k--)if(a[k]==g)break;if(k>e){i(k);continue}k=e+b;for(k;km&&a[k]m&&a[k]==j)k--;if(k>m){i(++k);continue}k=e+b,i(k)}return c},this.$getDisplayTokens=function(a,d){var e=[],f;d=d||0;for(var g=0;g39&&h<48||h>57&&h<64?e.push(j):h>=4352&&o(h)?e.push(b,c):e.push(b)}return e},this.$getStringScreenWidth=function(a,b,c){if(b==0)return[0,0];b==null&&(b=c+a.length*Math.max(this.getTabSize(),2)),c=c||0;var d,e;for(e=0;e=4352&&o(d)?c+=2:c+=1;if(c>b)break}return[c,e]},this.getRowLength=function(a){return!this.$useWrapMode||!this.$wrapData[a]?1:this.$wrapData[a].length+1},this.getRowHeight=function(a,b){return this.getRowLength(b)*a.lineHeight},this.getScreenLastRowColumn=function(a){return this.documentToScreenColumn(a,this.doc.getLine(a).length)},this.getDocumentLastRowColumn=function(a,b){var c=this.documentToScreenRow(a,b);return this.getScreenLastRowColumn(c)},this.getDocumentLastRowColumnPosition=function(a,b){var c=this.documentToScreenRow(a,b);return this.screenToDocumentPosition(c,Number.MAX_VALUE/10)},this.getRowSplitData=function(a){return this.$useWrapMode?this.$wrapData[a]:undefined},this.getScreenTabSize=function(a){return this.$tabSize-a%this.$tabSize},this.screenToDocumentRow=function(a,b){return this.screenToDocumentPosition(a,b).row},this.screenToDocumentColumn=function(a,b){return this.screenToDocumentPosition(a,b).column},this.screenToDocumentPosition=function(a,b){if(a<0)return{row:0,column:0};var c,d=0,e=0,f,g=0,h=0,i=this.$rowCache;for(var j=0;j=a||d>=l)break;g+=h,d++,d>n&&(d=m.end.row+1,m=this.getNextFoldLine(d,m),n=m?m.start.row:Infinity),k&&i.push({docRow:d,screenRow:g})}if(m&&m.start.row<=d)c=this.getFoldDisplayLine(m),d=m.start.row;else{if(g+h<=a||d>l)return{row:l,column:this.getLine(l).length};c=this.getLine(d),m=null}if(this.$useWrapMode){var o=this.$wrapData[d];o&&(f=o[a-g],a>g&&o.length&&(e=o[a-g-1]||o[o.length-1],c=c.substring(e)))}return e+=this.$getStringScreenWidth(c,b)[1],this.$useWrapMode?e>=f&&(e=f-1):e=Math.min(e,c.length),m?m.idxToPosition(e):{row:d,column:e}},this.documentToScreenPosition=function(a,b){if(typeof b=="undefined")var c=this.$clipPositionToDocument(a.row,a.column);else c=this.$clipPositionToDocument(a,b);a=c.row,b=c.column;var d;if(this.$useWrapMode){d=this.$wrapData;if(a>d.length-1)return{row:this.getScreenLength(),column:d.length==0?0:d[d.length-1].length-1}}var e=0,f=null,g=null;g=this.getFoldAt(a,b,1),g&&(a=g.start.row,b=g.start.column);var h,i=0,j=this.$rowCache;for(var k=0;k=n){h=m.end.row+1;if(h>a)break;m=this.getNextFoldLine(h,m),n=m?m.start.row:Infinity}else h=i+1;e+=this.getRowLength(i),i=h,l&&j.push({docRow:i,screenRow:e})}var o="";m&&i>=n?(o=this.getFoldDisplayLine(m,a,b),f=m.start.row):(o=this.getLine(a).substring(0,b),f=a);if(this.$useWrapMode){var p=d[f],q=0;while(o.length>=p[q])e++,q++;o=o.substring(p[q-1]||0,o.length)}return{row:e,column:this.$getStringScreenWidth(o)[0]}},this.documentToScreenColumn=function(a,b){return this.documentToScreenPosition(a,b).column},this.documentToScreenRow=function(a,b){return this.documentToScreenPosition(a,b).row},this.getScreenLength=function(){var a=0,b=null;if(!this.$useWrapMode){a=this.getLength();var c=this.$foldData;for(var d=0;dg&&(f=b.end.row+1,b=this.$foldData[d++],g=b?b.start.row:Infinity)}return a}})).call(l.prototype),a("./edit_session/folding").Folding.call(l.prototype),a("./edit_session/bracket_match").BracketMatch.call(l.prototype),b.EditSession=l}),define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/event_emitter").EventEmitter,g=a("./range").Range,h=function(a){this.session=a,this.doc=a.getDocument(),this.clearSelection(),this.selectionLead=this.doc.createAnchor(0,0),this.selectionAnchor=this.doc.createAnchor(0,0);var b=this;this.selectionLead.on("change",function(a){b._emit("changeCursor"),b.$isEmpty||b._emit("changeSelection"),!b.$preventUpdateDesiredColumnOnChange&&a.old.column!=a.value.column&&b.$updateDesiredColumn()}),this.selectionAnchor.on("change",function(){b.$isEmpty||b._emit("changeSelection")})};((function(){d.implement(this,f),this.isEmpty=function(){return this.$isEmpty||this.selectionAnchor.row==this.selectionLead.row&&this.selectionAnchor.column==this.selectionLead.column},this.isMultiLine=function(){return this.isEmpty()?!1:this.getRange().isMultiLine()},this.getCursor=function(){return this.selectionLead.getPosition()},this.setSelectionAnchor=function(a,b){this.selectionAnchor.setPosition(a,b),this.$isEmpty&&(this.$isEmpty=!1,this._emit("changeSelection"))},this.getSelectionAnchor=function(){return this.$isEmpty?this.getSelectionLead():this.selectionAnchor.getPosition()},this.getSelectionLead=function(){return this.selectionLead.getPosition()},this.shiftSelection=function(a){if(this.$isEmpty){this.moveCursorTo(this.selectionLead.row,this.selectionLead.column+a);return}var b=this.getSelectionAnchor(),c=this.getSelectionLead(),d=this.isBackwards();(!d||b.column!==0)&&this.setSelectionAnchor(b.row,b.column+a),(d||c.column!==0)&&this.$moveSelection(function(){this.moveCursorTo(c.row,c.column+a)})},this.isBackwards=function(){var a=this.selectionAnchor,b=this.selectionLead;return a.row>b.row||a.row==b.row&&a.column>b.column},this.getRange=function(){var a=this.selectionAnchor,b=this.selectionLead;return this.isEmpty()?g.fromPoints(b,b):this.isBackwards()?g.fromPoints(b,a):g.fromPoints(a,b)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var a=this.doc.getLength()-1;this.setSelectionAnchor(a,this.doc.getLine(a).length),this.moveCursorTo(0,0)},this.setSelectionRange=function(a,b){b?(this.setSelectionAnchor(a.end.row,a.end.column),this.selectTo(a.start.row,a.start.column)):(this.setSelectionAnchor(a.start.row,a.start.column),this.selectTo(a.end.row,a.end.column)),this.$updateDesiredColumn()},this.$updateDesiredColumn=function(){var a=this.getCursor();this.$desiredColumn=this.session.documentToScreenColumn(a.row,a.column)},this.$moveSelection=function(a){var b=this.selectionLead;this.$isEmpty&&this.setSelectionAnchor(b.row,b.column),a.call(this)},this.selectTo=function(a,b){this.$moveSelection(function(){this.moveCursorTo(a,b)})},this.selectToPosition=function(a){this.$moveSelection(function(){this.moveCursorToPosition(a)})},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.selectWord=function(){var a=this.getCursor(),b=this.session.getWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectAWord=function(){var a=this.getCursor(),b=this.session.getAWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectLine=function(){var a=this.selectionLead.row,b,c=this.session.getFoldLine(a);c?(a=c.start.row,b=c.end.row):b=a,this.setSelectionAnchor(a,0),this.$moveSelection(function(){this.moveCursorTo(b+1,0)})},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,-1))this.moveCursorTo(b.start.row,b.start.column);else if(a.column==0)a.row>0&&this.moveCursorTo(a.row-1,this.doc.getLine(a.row-1).length);else{var c=this.session.getTabSize();this.session.isTabStop(a)&&this.doc.getLine(a.row).slice(a.column-c,a.column).split(" ").length-1==c?this.moveCursorBy(0,-c):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,1))this.moveCursorTo(b.end.row,b.end.column);else if(this.selectionLead.column==this.doc.getLine(this.selectionLead.row).length)this.selectionLead.row=c.length){this.moveCursorTo(a,c.length),this.moveCursorRight(),a0&&this.moveCursorWordLeft();return}if(g=this.session.tokenRe.exec(f))b-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(a,b)},this.moveCursorBy=function(a,b){var c=this.session.documentToScreenPosition(this.selectionLead.row,this.selectionLead.column),d=b===0&&this.$desiredColumn||c.column,e=this.session.screenToDocumentPosition(c.row+a,d);this.moveCursorTo(e.row,e.column+b,b===0)},this.moveCursorToPosition=function(a){this.moveCursorTo(a.row,a.column)},this.moveCursorTo=function(a,b,c){var d=this.session.getFoldAt(a,b,1);d&&(a=d.start.row,b=d.start.column),this.$preventUpdateDesiredColumnOnChange=!0,this.selectionLead.setPosition(a,b),this.$preventUpdateDesiredColumnOnChange=!1,c||this.$updateDesiredColumn(this.selectionLead.column)},this.moveCursorToScreen=function(a,b,c){var d=this.session.screenToDocumentPosition(a,b);a=d.row,b=d.column,this.moveCursorTo(a,b,c)}})).call(h.prototype),b.Selection=h}),define("ace/range",["require","exports","module"],function(a,b,c){"use strict";var d=function(a,b,c,d){this.start={row:a,column:b},this.end={row:c,column:d}};((function(){this.isEequal=function(a){return this.start.row==a.start.row&&this.end.row==a.end.row&&this.start.column==a.start.column&&this.end.column==a.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(a,b){return this.compare(a,b)==0},this.compareRange=function(a){var b,c=a.end,d=a.start;return b=this.compare(c.row,c.column),b==1?(b=this.compare(d.row,d.column),b==1?2:b==0?1:0):b==-1?-2:(b=this.compare(d.row,d.column),b==-1?-1:b==1?42:0)},this.comparePoint=function(a){return this.compare(a.row,a.column)},this.containsRange=function(a){return this.comparePoint(a.start)==0&&this.comparePoint(a.end)==0},this.isEnd=function(a,b){return this.end.row==a&&this.end.column==b},this.isStart=function(a,b){return this.start.row==a&&this.start.column==b},this.setStart=function(a,b){typeof a=="object"?(this.start.column=a.column,this.start.row=a.row):(this.start.row=a,this.start.column=b)},this.setEnd=function(a,b){typeof a=="object"?(this.end.column=a.column,this.end.row=a.row):(this.end.row=a,this.end.column=b)},this.inside=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)||this.isStart(a,b)?!1:!0:!1},this.insideStart=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)?!1:!0:!1},this.insideEnd=function(a,b){return this.compare(a,b)==0?this.isStart(a,b)?!1:!0:!1},this.compare=function(a,b){return!this.isMultiLine()&&a===this.start.row?bthis.end.column?1:0:athis.end.row?1:this.start.row===a?b>=this.start.column?0:-1:this.end.row===a?b<=this.end.column?0:1:0},this.compareStart=function(a,b){return this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.compareEnd=function(a,b){return this.end.row==a&&this.end.column==b?1:this.compare(a,b)},this.compareInside=function(a,b){return this.end.row==a&&this.end.column==b?1:this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.clipRows=function(a,b){if(this.end.row>b)var c={row:b+1,column:0};if(this.start.row>b)var e={row:b+1,column:0};if(this.start.row=0&&/^[\w\d]/.test(h)||e<=g&&/[\w\d]$/.test(h))return;h=f.substring(c.start.column,c.end.column);if(!/^[\w\d]+$/.test(h))return;var i=a.getCursorPosition(),j={wrap:!0,wholeWord:!0,caseSensitive:!0,needle:h},k=a.$search.getOptions();a.$search.set(j);var l=a.$search.findAll(b);l.forEach(function(a){if(!a.contains(i.row,i.column)){var c=b.addMarker(a,"ace_selected_word","text");b.$selectionOccurrences.push(c)}}),a.$search.set(k)},this.clearSelectionHighlight=function(a){if(!a.session.$selectionOccurrences)return;a.session.$selectionOccurrences.forEach(function(b){a.session.removeMarker(b)}),a.session.$selectionOccurrences=[]},this.createModeDelegates=function(a){if(!this.$embeds)return;this.$modes={};for(var b=0;b1&&(m=g.slice(n+2,n+1+e[n].len)),typeof l.token=="function"?k=l.token.apply(this,m):k=l.token;var o=l.next;o&&o!==c&&(c=o,d=this.rules[c],e=this.matchMappings[c],i=f.lastIndex,f=this.regExps[c],f.lastIndex=i);break}if(m[0]){typeof k=="string"&&(m=[m.join("")],k=[k]);for(var n=0;n=b&&(a.row=Math.max(0,b-1),a.column=this.getLine(b-1).length),a},this.insert=function(a,b){if(b.length==0)return a;a=this.$clipPosition(a),this.getLength()<=1&&this.$detectNewLine(b);var c=this.$split(b),d=c.splice(0,1)[0],e=c.length==0?null:c.splice(c.length-1,1)[0];return a=this.insertInLine(a,d),e!==null&&(a=this.insertNewLine(a),a=this.insertLines(a.row,c),a=this.insertInLine(a,e||"")),a},this.insertLines=function(a,b){if(b.length==0)return{row:a,column:0};var c=[a,0];c.push.apply(c,b),this.$lines.splice.apply(this.$lines,c);var d=new f(a,0,a+b.length,0),e={action:"insertLines",range:d,lines:b};return this._emit("change",{data:e}),d.end},this.insertNewLine=function(a){a=this.$clipPosition(a);var b=this.$lines[a.row]||"";this.$lines[a.row]=b.substring(0,a.column),this.$lines.splice(a.row+1,0,b.substring(a.column,b.length));var c={row:a.row+1,column:0},d={action:"insertText",range:f.fromPoints(a,c),text:this.getNewLineCharacter()};return this._emit("change",{data:d}),c},this.insertInLine=function(a,b){if(b.length==0)return a;var c=this.$lines[a.row]||"";this.$lines[a.row]=c.substring(0,a.column)+b+c.substring(a.column);var d={row:a.row,column:a.column+b.length},e={action:"insertText",range:f.fromPoints(a,d),text:b};return this._emit("change",{data:e}),d},this.remove=function(a){a.start=this.$clipPosition(a.start),a.end=this.$clipPosition(a.end);if(a.isEmpty())return a.start;var b=a.start.row,c=a.end.row;if(a.isMultiLine()){var d=a.start.column==0?b:b+1,e=c-1;a.end.column>0&&this.removeInLine(c,0,a.end.column),e>=d&&this.removeLines(d,e),d!=b&&(this.removeInLine(b,a.start.column,this.getLine(b).length),this.removeNewLine(a.start.row))}else this.removeInLine(b,a.start.column,a.end.column);return a.start},this.removeInLine=function(a,b,c){if(b==c)return;var d=new f(a,b,a,c),e=this.getLine(a),g=e.substring(b,c),h=e.substring(0,b)+e.substring(c,e.length);this.$lines.splice(a,1,h);var i={action:"removeText",range:d,text:g};return this._emit("change",{data:i}),d.start},this.removeLines=function(a,b){var c=new f(a,0,b+1,0),d=this.$lines.splice(a,b-a+1),e={action:"removeLines",range:c,nl:this.getNewLineCharacter(),lines:d};return this._emit("change",{data:e}),d},this.removeNewLine=function(a){var b=this.getLine(a),c=this.getLine(a+1),d=new f(a,b.length,a+1,0),e=b+c;this.$lines.splice(a,2,e);var g={action:"removeText",range:d,text:this.getNewLineCharacter()};this._emit("change",{data:g})},this.replace=function(a,b){if(b.length==0&&a.isEmpty())return a.start;if(b==this.getTextRange(a))return a.end;this.remove(a);if(b)var c=this.insert(a.start,b);else c=a.start;return c},this.applyDeltas=function(a){for(var b=0;b=0;b--){var c=a[b],d=f.fromPoints(c.range.start,c.range.end);c.action=="insertLines"?this.removeLines(d.start.row,d.end.row-1):c.action=="insertText"?this.remove(d):c.action=="removeLines"?this.insertLines(d.start.row,c.lines):c.action=="removeText"&&this.insert(d.start,c.text)}}})).call(h.prototype),b.Document=h}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=b.Anchor=function(a,b,c){this.document=a,typeof c=="undefined"?this.setPosition(b.row,b.column):this.setPosition(b,c),this.$onChange=this.onChange.bind(this),a.on("change",this.$onChange)};((function(){d.implement(this,e),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.onChange=function(a){var b=a.data,c=b.range;if(c.start.row==c.end.row&&c.start.row!=this.row)return;if(c.start.row>this.row)return;if(c.start.row==this.row&&c.start.column>this.column)return;var d=this.row,e=this.column;b.action==="insertText"?c.start.row===d&&c.start.column<=e?c.start.row===c.end.row?e+=c.end.column-c.start.column:(e-=c.start.column,d+=c.end.row-c.start.row):c.start.row!==c.end.row&&c.start.row=e?e=c.start.column:e=Math.max(0,e-(c.end.column-c.start.column)):c.start.row!==c.end.row&&c.start.row=this.document.getLength()?(c.row=Math.max(0,this.document.getLength()-1),c.column=this.document.getLine(c.row).length):a<0?(c.row=0,c.column=0):(c.row=a,c.column=Math.min(this.document.getLine(c.row).length,Math.max(0,b))),b<0&&(c.column=0),c}})).call(f.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=function(a,b){this.running=!1,this.lines=[],this.currentLine=0,this.tokenizer=a;var c=this;this.$worker=function(){if(!c.running)return;var a=new Date,b=c.currentLine,d=c.doc,e=0,f=d.getLength();while(c.currentLine20){c.fireUpdateEvent(b,c.currentLine-1),c.running=setTimeout(c.$worker,20);return}}c.running=!1,c.fireUpdateEvent(b,f-1)}};((function(){d.implement(this,e),this.setTokenizer=function(a){this.tokenizer=a,this.lines=[],this.start(0)},this.setDocument=function(a){this.doc=a,this.lines=[],this.stop()},this.fireUpdateEvent=function(a,b){var c={first:a,last:b};this._emit("update",{data:c})},this.start=function(a){this.currentLine=Math.min(a||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(a,b){return this.$tokenizeRows(a,b)},this.getState=function(a){return this.$tokenizeRows(a,a)[0].state},this.$tokenizeRows=function(a,b){if(!this.doc||isNaN(a)||isNaN(b))return[{state:"start",tokens:[]}];var c=[],d="start",e=!1;a>0&&this.lines[a-1]?(d=this.lines[a-1].state,e=!0):a==0?(d="start",e=!0):this.lines.length>0&&(d=this.lines[this.lines.length-1].state);var f=this.doc.getLines(a,b);for(var g=a;g<=b;g++)if(!this.lines[g]){var h=this.tokenizer.getLineTokens(f[g-a]||"",d),d=h.state;c.push(h),e&&(this.lines[g]=h)}else{var h=this.lines[g];d=h.state,c.push(h)}return c}})).call(f.prototype),b.BackgroundTokenizer=f}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(a,b,c){function h(){this.getFoldAt=function(a,b,c){var d=this.getFoldLine(a);if(!d)return null;var e=d.folds;for(var f=0;f=a)return e;if(e.end.row>a)return null}return null},this.getNextFoldLine=function(a,b){var c=this.$foldData,d=0;b&&(d=c.indexOf(b)),d==-1&&(d=0);for(d;d=a)return e}return null},this.getFoldedRowCount=function(a,b){var c=this.$foldData,d=b-a+1;for(var e=0;e=b){h=a?d-=b-h:d=0);break}g>=a&&(h>=a?d-=g-h:d-=g-a+1)}return d},this.$addFoldLine=function(a){return this.$foldData.push(a),this.$foldData.sort(function(a,b){return a.start.row-b.start.row}),a},this.addFold=function(a,b){var c=this.$foldData,d=!1,g;a instanceof f?g=a:g=new f(b,a),this.$clipRangeToDocument(g.range);var h=g.start.row,i=g.start.column,j=g.end.row,k=g.end.column;if(g.placeholder.length<2)throw"Placeholder has to be at least 2 characters";if(h==j&&k-i<2)throw"The range has to be at least 2 characters width";var l=this.getFoldAt(h,i,1),m=this.getFoldAt(j,k,-1);if(l&&m==l)return l.addSubFold(g);if(l&&!l.range.isStart(h,i)||m&&!m.range.isEnd(j,k))throw"A fold can't intersect already existing fold"+g.range+l.range;var n=this.getFoldsInRange(g.range);n.length>0&&(this.removeFolds(n),g.subFolds=n);for(var o=0;othis.endRow)throw"Can't add a fold to this FoldLine as it has no connection";this.folds.push(a),this.folds.sort(function(a,b){return-a.range.compareEnd(b.start.row,b.start.column)}),this.range.compareEnd(a.start.row,a.start.column)>0?(this.end.row=a.end.row,this.end.column=a.end.column):this.range.compareStart(a.end.row,a.end.column)<0&&(this.start.row=a.start.row,this.start.column=a.start.column)}else if(a.start.row==this.end.row)this.folds.push(a),this.end.row=a.end.row,this.end.column=a.end.column;else if(a.end.row==this.start.row)this.folds.unshift(a),this.start.row=a.start.row,this.start.column=a.start.column;else throw"Trying to add fold to FoldRow that doesn't have a matching row";a.foldLine=this},this.containsRow=function(a){return a>=this.start.row&&a<=this.end.row},this.walk=function(a,b,c){var d=0,e=this.folds,f,g,h,i=!0;b==null&&(b=this.end.row,c=this.end.column);for(var j=0;j=this.$rowTokens.length){this.$row+=1;if(this.$row>=a)return this.$row=a-1,null;this.$rowTokens=this.$session.getTokens(this.$row,this.$row)[0].tokens,this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var a=this.$rowTokens,b=this.$tokenIndex,c=a[b].start;if(c!==undefined)return c;c=0;while(b>0)b-=1,c+=a[b].value.length;return c}})).call(d.prototype),b.TokenIterator=d}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator"],function(a,b,c){function e(){this.findMatchingBracket=function(a){if(a.column==0)return null;var b=this.getLine(a.row).charAt(a.column-1);if(b=="")return null;var c=b.match(/([\(\[\{])|([\)\]\}])/);return c?c[1]?this.$findClosingBracket(c[1],a):this.$findOpeningBracket(c[2],a):null},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("rparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn()-2,j=g.value;for(;;){while(i>=0){var k=j.charAt(i);if(k==c){e-=1;if(e==0)return{row:f.getCurrentTokenRow(),column:i+f.getCurrentTokenColumn()}}else k==a&&(e+=1);i-=1}do g=f.stepBackward();while(g&&!h.test(g.type));if(g==null)break;j=g.value,i=j.length-1}return null},this.$findClosingBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("lparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn();for(;;){var j=g.value,k=j.length;while(i=0;h--){var i=g[h],j=c.$rangeFromMatch(f,i.offset,i.str.length);if(d(j))return!0}})}}},this.$rangeFromMatch=function(a,b,c){return new f(a,b,a,b+c)},this.$assembleRegExp=function(){if(this.$options.regExp)var a=this.$options.needle;else a=d.escapeRegExp(this.$options.needle);this.$options.wholeWord&&(a="\\b"+a+"\\b");var b="g";this.$options.caseSensitive||(b+="i");var c=new RegExp(a,b);return c},this.$forwardLineIterator=function(a){function k(e){var f=a.getLine(e);return b&&e==c.end.row&&(f=f.substring(0,c.end.column)),j&&e==d.row&&(f=f.substring(0,d.column)),f}var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"start":"end"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap,j=!1;return{forEach:function(a){var b=d.row,c=k(b),g=d.column,l=!1;j=!1;while(!a(c,g,b)){if(l)return;b++,g=0;if(b>h)if(i)b=e,g=f,j=!0;else return;b==d.row&&(l=!0),c=k(b)}}}},this.$backwardLineIterator=function(a){var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"end":"start"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap;return{forEach:function(g){var j=d.row,k=a.getLine(j).substring(0,d.column),l=0,m=!1,n=!1;while(!g(k,l,j)){if(m)return;j--,l=0;if(j0},this.hasRedo=function(){return this.$redoStack.length>0}})).call(d.prototype),b.UndoManager=d}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/lib/event_emitter","text!ace/css/editor.css"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/useragent"),h=a("./layer/gutter").Gutter,i=a("./layer/marker").Marker,j=a("./layer/text").Text,k=a("./layer/cursor").Cursor,l=a("./scrollbar").ScrollBar,m=a("./renderloop").RenderLoop,n=a("./lib/event_emitter").EventEmitter,o=a("text!./css/editor.css");e.importCssString(o,"ace_editor");var p=function(a,b){var c=this;this.container=a,e.addCssClass(a,"ace_editor"),this.setTheme(b),this.$gutter=e.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=e.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=e.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new h(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onResize.bind(this,!0)),this.$markerBack=new i(this.content);var d=this.$textLayer=new j(this.content);this.canvas=d.element,this.$markerFront=new i(this.content),this.characterWidth=d.getCharacterWidth(),this.lineHeight=d.getLineHeight(),this.$cursorLayer=new k(this.content),this.$cursorPadding=8,this.$horizScroll=!0,this.$horizScrollAlwaysVisible=!0,this.scrollBar=new l(a),this.scrollBar.addEventListener("scroll",function(a){c.session.setScrollTop(a.data)}),this.scrollTop=0,this.scrollLeft=0,f.addListener(this.scroller,"scroll",function(){c.session.setScrollLeft(c.scroller.scrollLeft)}),this.cursorPos={row:0,column:0},this.$textLayer.addEventListener("changeCharaterSize",function(){c.characterWidth=d.getCharacterWidth(),c.lineHeight=d.getLineHeight(),c.$updatePrintMargin(),c.onResize(!0),c.$loop.schedule(c.CHANGE_FULL)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:1,characterWidth:1,minHeight:1,maxHeight:1,offset:0,height:1},this.$loop=new m(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.setPadding(4),this.$updatePrintMargin()};((function(){this.showGutter=!0,this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,d.implement(this,n),this.setSession=function(a){this.session=a,this.$cursorLayer.setSession(a),this.$markerBack.setSession(a),this.$markerFront.setSession(a),this.$gutterLayer.setSession(a),this.$textLayer.setSession(a),this.$loop.schedule(this.CHANGE_FULL)},this.updateLines=function(a,b){b===undefined&&(b=Infinity),this.$changedLines?(this.$changedLines.firstRow>a&&(this.$changedLines.firstRow=a),this.$changedLines.lastRowc.lastRow+1)return;if(bc&&this.session.setScrollTop(c),this.scrollTop+this.$size.scrollerHeightb&&(bthis.layerConfig.width+2*this.$padding?this.$desiredScrollLeft=b:this.scrollToX(Math.round(b+this.characterWidth-this.$size.scrollerWidth)))},this.getScrollTop=function(){return this.session.getScrollTop()},this.getScrollLeft=function(){return this.session.getScrollTop()},this.getScrollTopRow=function(){return this.scrollTop/this.lineHeight},this.getScrollBottomRow=function(){return Math.max(0,Math.floor((this.scrollTop+this.$size.scrollerHeight)/this.lineHeight)-1)},this.scrollToRow=function(a){this.session.setScrollTop(a*this.lineHeight)},this.scrollToLine=function(a,b){var c={lineHeight:this.lineHeight},d=0;for(var e=1;e0)return!0;if(b>0&&this.session.getScrollTop()+this.$size.scrollerHeighth&&(e=g.end.row+1,g=this.session.getNextFoldLine(e,g),h=g?g.start.row:Infinity);if(e>f)break;var j=this.$annotations[e]||b;c.push("
    ",e+1);if(i){var k=i[e];k==null&&(k=i[e]=this.session.getFoldWidget(e)),k&&c.push("")}var l=this.session.getRowLength(e)-1;while(l--)c.push("
    ¦");c.push("
    "),e++}this.element=d.setInnerHtml(this.element,c.join("")),this.element.style.height=a.minHeight+"px";var m=this.element.offsetWidth;m!==this.gutterWidth&&(this.gutterWidth=m,this._emit("changeGutterWidth",m))},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(a){a?d.addCssClass(this.element,"ace_folding-enabled"):d.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=a},this.getShowFoldWidgets=function(){return this.$showFoldWidgets}})).call(g.prototype),b.Gutter=g}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../range").Range,e=a("../lib/dom"),f=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_marker-layer",a.appendChild(this.element)};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.setMarkers=function(a){this.markers=a},this.update=function(a){var a=a||this.config;if(!a)return;this.config=a;var b=[];for(var c in this.markers){var d=this.markers[c],f=d.range.clipRows(a.firstRow,a.lastRow);if(f.isEmpty())continue;f=f.toScreenRange(this.session);if(d.renderer){var g=this.$getTop(f.start.row,a),h=Math.round(this.$padding+f.start.column*a.characterWidth);d.renderer(b,f,h,g,a)}else f.isMultiLine()?d.type=="text"?this.drawTextMarker(b,f,d.clazz,a):this.drawMultiLineMarker(b,f,d.clazz,a,d.type):this.drawSingleLineMarker(b,f,d.clazz,a,null,d.type)}this.element=e.setInnerHtml(this.element,b.join(""))},this.$getTop=function(a,b){return(a-b.firstRowScreen)*b.lineHeight},this.drawTextMarker=function(a,b,c,e){var f=b.start.row,g=new d(f,b.start.column,f,this.session.getScreenLastRowColumn(f));this.drawSingleLineMarker(a,g,c,e,1,"text"),f=b.end.row,g=new d(f,0,f,b.end.column),this.drawSingleLineMarker(a,g,c,e,0,"text");for(f=b.start.row+1;f"),j=this.$getTop(b.end.row,d),i=Math.round(b.end.column*d.characterWidth),a.push("
    "),h=(b.end.row-b.start.row-1)*d.lineHeight;if(h<0)return;j=this.$getTop(b.start.row+1,d),a.push("
    ")},this.drawSingleLineMarker=function(a,b,c,d,e,f){var g=f==="background"?0:this.$padding,h=d.lineHeight;if(f==="background")var i=d.width;else i=Math.round((b.end.column+(e||0)-b.start.column)*d.characterWidth);var j=this.$getTop(b.start.row,d),k=Math.round(g+b.start.column*d.characterWidth);a.push("
    ")}})).call(f.prototype),b.Marker=f}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/dom"),f=a("../lib/lang"),g=a("../lib/useragent"),h=a("../lib/event_emitter").EventEmitter,i=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_text-layer",a.appendChild(this.element),this.$characterSize=this.$measureSizes()||{width:0,height:0},this.$pollSizeChanges()};((function(){d.implement(this,h),this.EOF_CHAR="¶",this.EOL_CHAR="¬",this.TAB_CHAR="→",this.SPACE_CHAR="·",this.$padding=0,this.setPadding=function(a){this.$padding=a,this.element.style.padding="0 "+a+"px"},this.getLineHeight=function(){return this.$characterSize.height||1},this.getCharacterWidth=function(){return this.$characterSize.width||1},this.checkForSizeChanges=function(){var a=this.$measureSizes();a&&(this.$characterSize.width!==a.width||this.$characterSize.height!==a.height)&&(this.$characterSize=a,this._emit("changeCharaterSize",{data:a}))},this.$pollSizeChanges=function(){var a=this;this.$pollSizeChangesTimer=setInterval(function(){a.checkForSizeChanges()},500)},this.$fontStyles={fontFamily:1,fontSize:1,fontWeight:1,fontStyle:1,lineHeight:1},this.$measureSizes=function(){var a=1e3;if(!this.$measureNode){var b=this.$measureNode=e.createElement("div"),c=b.style;c.width=c.height="auto",c.left=c.top=-a*40+"px",c.visibility="hidden",c.position="absolute",c.overflow="visible",c.whiteSpace="nowrap",b.innerHTML=f.stringRepeat("Xy",a);if(this.element.ownerDocument.body)this.element.ownerDocument.body.appendChild(b);else{var d=this.element.parentNode;while(!e.hasCssClass(d,"ace_editor"))d=d.parentNode;d.appendChild(b)}}var c=this.$measureNode.style,g=e.computedStyle(this.element);for(var h in this.$fontStyles)c[h]=g[h];var i={height:this.$measureNode.offsetHeight,width:this.$measureNode.offsetWidth/(a*2)};return i.width==0&&i.height==0?null:i},this.setSession=function(a){this.session=a},this.showInvisibles=!1,this.setShowInvisibles=function(a){return this.showInvisibles==a?!1:(this.showInvisibles=a,!0)},this.$tabStrings=[],this.$computeTabString=function(){var a=this.session.getTabSize(),b=this.$tabStrings=[0];for(var c=1;c"+this.TAB_CHAR+(new Array(c)).join(" ")+""):b.push((new Array(c+1)).join(" "))},this.updateLines=function(a,b,c){this.$computeTabString(),(this.config.lastRow!=a.lastRow||this.config.firstRow!=a.firstRow)&&this.scrollLines(a),this.config=a;var d=Math.max(b,a.firstRow),f=Math.min(c,a.lastRow),g=this.element.childNodes,h=0;for(var i=a.firstRow;i0;d--)c.removeChild(c.firstChild);if(b.lastRow>a.lastRow)for(var d=this.session.getFoldedRowCount(a.lastRow+1,b.lastRow);d>0;d--)c.removeChild(c.lastChild);if(a.firstRowb.lastRow){var e=this.$renderLinesFragment(a,b.lastRow+1,a.lastRow);c.appendChild(e)}},this.$renderLinesFragment=function(a,b,c){var d=this.element.ownerDocument.createDocumentFragment(),f=b,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>c)break;var i=e.createElement("div"),j=[],k=this.session.getTokens(f,f);k.length==1&&this.$renderLine(j,f,k[0].tokens,!1),i.innerHTML=j.join("");if(this.$useLineGroups())i.className="ace_line_group",d.appendChild(i);else{var l=i.childNodes;while(l.length)d.appendChild(l[0])}f++}return d},this.update=function(a){this.$computeTabString(),this.config=a;var b=[],c=a.firstRow,d=a.lastRow,f=c,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>d)break;this.$useLineGroups()&&b.push("
    ");var i=this.session.getTokens(f,f);i.length==1&&this.$renderLine(b,f,i[0].tokens,!1),this.$useLineGroups()&&b.push("
    "),f++}this.element=e.setInnerHtml(this.element,b.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(a,b,c,d){var e=this,f=/\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g,h=function(a,c,d,f,h){if(a.charCodeAt(0)==32)return(new Array(a.length+1)).join(" ");if(a=="\t"){var i=e.session.getScreenTabSize(b+f);return b+=i-1,e.$tabStrings[i]}if(a=="&")return g.isOldGecko?"&":"&";if(a=="<")return"<";if(a==" "){var j=e.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",k=e.showInvisibles?e.SPACE_CHAR:"";return b+=1,""+k+""}if(a.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)){if(e.showInvisibles){var k=(new Array(a.length+1)).join(e.SPACE_CHAR);return""+k+""}return" "}return b+=1,""+a+""},i=d.replace(f,h);if(!this.$textToken[c.type]){var j="ace_"+c.type.replace(/\./g," ace_"),k="";c.type=="fold"&&(k=" style='width:"+c.value.length*this.config.characterWidth+"px;' "),a.push("",i,"")}else a.push(i);return b+d.length},this.$renderLineCore=function(a,b,c,d,e){var f=0,g=0,h,i=0,j=this;!d||d.length==0?h=Number.MAX_VALUE:h=d[0],e||a.push("
    ");for(var k=0;k=h)i=j.$renderToken(a,i,l,m.substring(0,h-f)),m=m.substring(h-f),f=h,e||a.push("
    ","
    "),g++,i=0,h=d[g]||Number.MAX_VALUE;m.length!=0&&(f+=m.length,i=j.$renderToken(a,i,l,m))}}this.showInvisibles&&(b!==this.session.getLength()-1?a.push(""+this.EOL_CHAR+""):a.push(""+this.EOF_CHAR+"")),e||a.push("
    ")},this.$renderLine=function(a,b,c,d){if(!this.session.isRowFolded(b)){var e=this.session.getRowSplitData(b);this.$renderLineCore(a,b,c,e,d)}else this.$renderFoldLine(a,b,c,d)},this.$renderFoldLine=function(a,b,c,d){function h(a,b,c){var d=0,e=0;while(e+a[d].value.lengthc-b&&(f=f.substring(0,c-b)),g.push({type:a[d].type,value:f}),e=b+f.length,d+=1}while(ec&&(f=f.substring(0,c-e)),g.push({type:a[d].type,value:f}),e+=f.length,d+=1}}var e=this.session,f=e.getFoldLine(b),g=[];f.walk(function(a,b,d,e,f){a?g.push({type:"fold",value:a}):(f&&(c=this.session.getTokens(b,b)[0].tokens),c.length!=0&&h(c,e,d))}.bind(this),f.end.row,this.session.getLine(f.end.row).length);var i=this.session.$useWrapMode?this.session.$wrapData[b]:null;this.$renderLineCore(a,b,g,i,d)},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}})).call(i.prototype),b.Text=i}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../lib/dom"),e=function(a){this.element=d.createElement("div"),this.element.className="ace_layer ace_cursor-layer",a.appendChild(this.element),this.cursor=d.createElement("div"),this.cursor.className="ace_cursor ace_hidden",this.element.appendChild(this.cursor),this.isVisible=!1};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.hideCursor=function(){this.isVisible=!1,d.addCssClass(this.cursor,"ace_hidden"),clearInterval(this.blinkId)},this.showCursor=function(){this.isVisible=!0,d.removeCssClass(this.cursor,"ace_hidden"),this.cursor.style.visibility="visible",this.restartTimer()},this.restartTimer=function(){clearInterval(this.blinkId);if(!this.isVisible)return;var a=this.cursor;this.blinkId=setInterval(function(){a.style.visibility="hidden",setTimeout(function(){a.style.visibility="visible"},400)},1e3)},this.getPixelPosition=function(a){if(!this.config||!this.session)return{left:0,top:0};var b=this.session.selection.getCursor(),c=this.session.documentToScreenPosition(b),d=Math.round(this.$padding+c.column*this.config.characterWidth),e=(c.row-(a?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:d,top:e}},this.update=function(a){this.config=a,this.pixelPos=this.getPixelPosition(!0),this.cursor.style.left=this.pixelPos.left+"px",this.cursor.style.top=this.pixelPos.top+"px",this.cursor.style.width=a.characterWidth+"px",this.cursor.style.height=a.lineHeight+"px";var b=this.session.getOverwrite();b!=this.overwrite&&(this.overwrite=b,b?d.addCssClass(this.cursor,"ace_overwrite"):d.removeCssClass(this.cursor,"ace_overwrite")),this.restartTimer()},this.destroy=function(){clearInterval(this.blinkId)}})).call(e.prototype),b.Cursor=e}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/event_emitter").EventEmitter,h=function(a){this.element=e.createElement("div"),this.element.className="ace_sb",this.inner=e.createElement("div"),this.element.appendChild(this.inner),a.appendChild(this.element),this.width=e.scrollbarWidth(a.ownerDocument),this.element.style.width=(this.width||15)+5+"px",f.addListener(this.element,"scroll",this.onScroll.bind(this))};((function(){d.implement(this,g),this.onScroll=function(){this._emit("scroll",{data:this.element.scrollTop})},this.getWidth=function(){return this.width},this.setHeight=function(a){this.element.style.height=a+"px"},this.setInnerHeight=function(a){this.inner.style.height=a+"px"},this.setScrollTop=function(a){this.element.scrollTop=a}})).call(h.prototype),b.ScrollBar=h}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(a,b,c){"use strict";var d=a("./lib/event"),e=function(a,b){this.onRender=a,this.pending=!1,this.changes=0,this.window=b||window};((function(){this.schedule=function(a){this.changes=this.changes|a;if(!this.pending){this.pending=!0;var b=this;d.nextTick(function(){b.pending=!1;var a;while(a=b.changes)b.changes=0,b.onRender(a)},this.window)}}})).call(e.prototype),b.RenderLoop=e}),define("text!ace/css/editor.css",[],"\n\n\n.ace_editor {\n position: absolute;\n overflow: hidden;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Courier New', monospace;\n font-size: 12px;\n}\n\n.ace_scroller {\n position: absolute;\n overflow-x: scroll;\n overflow-y: hidden;\n}\n\n.ace_content {\n position: absolute;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n cursor: text;\n}\n\n/* setting pointer-events: auto; on node under the mouse, which changes during scroll,\n will break mouse wheel scrolling in Safari */\n.ace_content * {\n pointer-events: none;\n}\n\n.ace_composition {\n position: absolute;\n background: #555;\n color: #DDD;\n z-index: 4;\n}\n\n.ace_gutter .ace_layer {\n position: relative;\n min-width: 54px;\n text-align: right;\n}\n\n.ace_gutter {\n position: absolute;\n overflow : hidden;\n height: 100%;\n width: auto;\n cursor: default;\n}\n\n.ace_gutter-cell {\n padding-left: 19px;\n padding-right: 6px;\n}\n\n.ace_gutter-cell.ace_error {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_warning {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_info {\n background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_editor .ace_sb {\n position: absolute;\n overflow-x: hidden;\n overflow-y: scroll;\n right: 0;\n}\n\n.ace_editor .ace_sb div {\n position: absolute;\n width: 1px;\n left: 0;\n}\n\n.ace_editor .ace_print_margin_layer {\n z-index: 0;\n position: absolute;\n overflow: hidden;\n margin: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.ace_editor .ace_print_margin {\n position: absolute;\n height: 100%;\n}\n\n.ace_editor textarea {\n position: fixed;\n z-index: 0;\n width: 10px;\n height: 30px;\n opacity: 0;\n background: transparent;\n appearance: none;\n -moz-appearance: none;\n border: none;\n resize: none;\n outline: none;\n overflow: hidden;\n}\n\n.ace_layer {\n z-index: 1;\n position: absolute;\n overflow: hidden;\n white-space: nowrap;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_text-layer {\n color: black;\n}\n\n.ace_cjk {\n display: inline-block;\n text-align: center;\n}\n\n.ace_cursor-layer {\n z-index: 4;\n}\n\n.ace_cursor {\n z-index: 4;\n position: absolute;\n}\n\n.ace_cursor.ace_hidden {\n opacity: 0.2;\n}\n\n.ace_line {\n white-space: nowrap;\n}\n\n.ace_marker-layer .ace_step {\n position: absolute;\n z-index: 3;\n}\n\n.ace_marker-layer .ace_selection {\n position: absolute;\n z-index: 4;\n}\n\n.ace_marker-layer .ace_bracket {\n position: absolute;\n z-index: 5;\n}\n\n.ace_marker-layer .ace_active_line {\n position: absolute;\n z-index: 2;\n}\n\n.ace_marker-layer .ace_selected_word {\n position: absolute;\n z-index: 6;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_line .ace_fold {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n \n display: inline-block;\n height: 11px;\n margin-top: -2px;\n vertical-align: middle;\n\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n color: transparent;\n\n border: 1px solid black;\n -moz-border-radius: 2px;\n -webkit-border-radius: 2px;\n border-radius: 2px;\n \n cursor: pointer;\n pointer-events: auto;\n}\n\n.ace_dark .ace_fold {\n}\n\n.ace_fold:hover{\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n}\n\n.ace_dragging .ace_content {\n cursor: move;\n}\n\n.ace_folding-enabled .ace_gutter-cell {\n padding-right: 13px;\n}\n\n.ace_fold-widget {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n\n margin: 0 -12px 1px 1px;\n display: inline-block;\n height: 14px;\n width: 11px;\n vertical-align: text-bottom;\n \n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat;\n background-position: center 5px;\n\n border-radius: 3px;\n}\n\n.ace_fold-widget.end {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget.closed {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget:hover {\n border: 1px solid rgba(0, 0, 0, 0.3);\n background-color: rgba(255, 255, 255, 0.2);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n background-position: center 4px;\n}\n\n.ace_fold-widget:active {\n border: 1px solid rgba(0, 0, 0, 0.4);\n background-color: rgba(0, 0, 0, 0.05);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n}\n\n.ace_fold-widget.invalid {\n background-color: #FFB4B4;\n border-color: #DE5555;\n}\n"),define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict",b.isDark=!1,b.cssClass="ace-tm",b.cssText=".ace-tm .ace_editor { border: 2px solid rgb(159, 159, 159);}.ace-tm .ace_editor.ace_focus { border: 2px solid #327fbd;}.ace-tm .ace_gutter { background: #e8e8e8; color: #333;}.ace-tm .ace_print_margin { width: 1px; background: #e8e8e8;}.ace-tm .ace_fold { background-color: #0000A2;}.ace-tm .ace_text-layer { cursor: text;}.ace-tm .ace_cursor { border-left: 2px solid black;}.ace-tm .ace_cursor.ace_overwrite { border-left: 0px; border-bottom: 1px solid black;} .ace-tm .ace_line .ace_invisible { color: rgb(191, 191, 191);}.ace-tm .ace_line .ace_keyword { color: blue;}.ace-tm .ace_line .ace_constant.ace_buildin { color: rgb(88, 72, 246);}.ace-tm .ace_line .ace_constant.ace_language { color: rgb(88, 92, 246);}.ace-tm .ace_line .ace_constant.ace_library { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_invalid { background-color: rgb(153, 0, 0); color: white;}.ace-tm .ace_line .ace_support.ace_function { color: rgb(60, 76, 114);}.ace-tm .ace_line .ace_support.ace_constant { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_support.ace_type,.ace-tm .ace_line .ace_support.ace_class { color: rgb(109, 121, 222);}.ace-tm .ace_line .ace_keyword.ace_operator { color: rgb(104, 118, 135);}.ace-tm .ace_line .ace_string { color: rgb(3, 106, 7);}.ace-tm .ace_line .ace_comment { color: rgb(76, 136, 107);}.ace-tm .ace_line .ace_comment.ace_doc { color: rgb(0, 102, 255);}.ace-tm .ace_line .ace_comment.ace_doc.ace_tag { color: rgb(128, 159, 191);}.ace-tm .ace_line .ace_constant.ace_numeric { color: rgb(0, 0, 205);}.ace-tm .ace_line .ace_variable { color: rgb(49, 132, 149);}.ace-tm .ace_line .ace_xml_pe { color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function { color: #0000A2;}.ace-tm .ace_markup.ace_markupine { text-decoration:underline;}.ace-tm .ace_markup.ace_heading { color: rgb(12, 7, 255);}.ace-tm .ace_markup.ace_list { color:rgb(185, 6, 144);}.ace-tm .ace_marker-layer .ace_selection { background: rgb(181, 213, 255);}.ace-tm .ace_marker-layer .ace_step { background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack { background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active_line { background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_marker-layer .ace_selected_word { background: rgb(250, 250, 255); border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_meta.ace_tag { color:rgb(28, 2, 255);}.ace-tm .ace_string.ace_regex { color: rgb(255, 0, 0)}";var d=a("../lib/dom");d.importCssString(b.cssText,b.cssClass)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file -- GitLab From dae34edf4f1f48f5d74f3704939a0e846bcb6267 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Sun, 15 Apr 2012 16:04:21 +0200 Subject: [PATCH 141/430] fix filecache rename hook --- lib/filecache.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/filecache.php b/lib/filecache.php index 24984c2ccff..e62fb2189f4 100644 --- a/lib/filecache.php +++ b/lib/filecache.php @@ -475,7 +475,7 @@ class OC_FileCache{ }else{ return; } - $size=OC_Filesystem::filesize($oldPath); + $size=OC_Filesystem::filesize($newPath); self::increaseSize(dirname($fullOldPath),-$oldSize); self::increaseSize(dirname($fullNewPath),$oldSize); self::move($oldPath,$newPath); -- GitLab From c0bdad58932a29a1f21909e959416369a790fa8d Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Sun, 15 Apr 2012 16:06:16 +0200 Subject: [PATCH 142/430] dont allow draging files to the current directory --- files/js/files.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/files/js/files.js b/files/js/files.js index 1c0a40c2368..2d943d85cd4 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -13,9 +13,11 @@ $(document).ready(function() { //drag/drop of files $('#fileList tr td.filename').draggable(dragOptions); $('#fileList tr[data-type="dir"][data-write="true"] td.filename').droppable(folderDropOptions); - $('div.crumb').droppable(crumbDropOptions); + $('div.crumb:not(.last)').droppable(crumbDropOptions); $('ul#apps>li:first-child').data('dir',''); - $('ul#apps>li:first-child').droppable(crumbDropOptions); + if($('div.crumb').length){ + $('ul#apps>li:first-child').droppable(crumbDropOptions); + } // Triggers invisible file input $('.file_upload_button_wrapper').live('click', function() { @@ -412,7 +414,7 @@ var dragOptions={ }; var folderDropOptions={ drop: function( event, ui ) { - var file=ui.draggable.text().trim(); + var file=ui.draggable.parent().data('file'); var target=$(this).text().trim(); var dir=$('#dir').val(); $.ajax({ @@ -438,7 +440,7 @@ var crumbDropOptions={ if(dir.substr(-1,1)!='/'){ dir=dir+'/'; } - if(target==dir){ + if(target==dir || target+'/'==dir){ return; } $.ajax({ -- GitLab From 9ac65c51f5bcc06c400e64ff7db53adc5be80c84 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Sun, 15 Apr 2012 16:26:08 +0200 Subject: [PATCH 143/430] dont try to view psd files --- apps/files_imageviewer/js/lightbox.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/files_imageviewer/js/lightbox.js b/apps/files_imageviewer/js/lightbox.js index 94743aa85e0..6c97466e6d6 100644 --- a/apps/files_imageviewer/js/lightbox.js +++ b/apps/files_imageviewer/js/lightbox.js @@ -18,6 +18,9 @@ $(document).ready(function() { }); function viewImage(dir, file) { + if(file.indexOf('.psd')){//can't view those + return; + } var location=OC.filePath('files','ajax','download.php')+'?files='+file+'&dir='+dir; $.fancybox({ "href": location, -- GitLab From 8e27b725ba2aa26cb9037b44b18ff800649017b1 Mon Sep 17 00:00:00 2001 From: Simon Birnbach Date: Sun, 15 Apr 2012 16:47:53 +0200 Subject: [PATCH 144/430] Fixed cancelling upload of same file to folder and subfolder --- files/css/files.css | 1 + files/js/files.js | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/files/css/files.css b/files/css/files.css index 4d2b749bf8c..544b323bb29 100644 --- a/files/css/files.css +++ b/files/css/files.css @@ -62,6 +62,7 @@ table tr[data-type="dir"] td.filename a.name {font-weight:bold; } table td.filename a.name input, table td.filename a.name form { width:100%; cursor:text; } table td.filename a, table td.login, table td.logout, table td.download, table td.upload, table td.create, table td.delete { padding:.2em .5em .5em 0; } table td.filename .nametext, .uploadtext, .modified { float:left; padding:.3em 0; } +// TODO fix usability bug (accidental file/folder selection) //table td.filename .nametext { width:60%; } table td.filename .uploadtext { font-weight:normal; margin-left:.5em; } table td.filename form { float:left; font-size:.85em; } diff --git a/files/js/files.js b/files/js/files.js index 89101ce4b8f..a7a4d3077c1 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -172,6 +172,7 @@ $(document).ready(function() { }); // drag&drop support using jquery.fileupload + // TODO use OC.dialogs $(document).bind('drop dragover', function (e) { e.preventDefault(); // prevent browser from doing anything, if file isn't dropped in dropZone }); @@ -242,6 +243,7 @@ $(document).ready(function() { $('#notification').fadeIn(); } }); + uploadingFiles[dirName+"/"+files[i].name] = jqXHR; } else { var jqXHR = $('.file_upload_start').fileupload('send', {files: files[i]}) .success(function(result, textStatus, jqXHR) { @@ -270,8 +272,8 @@ $(document).ready(function() { $('#notification').fadeIn(); } }); + uploadingFiles[files[i].name] = jqXHR; } - uploadingFiles[files[i].name] = jqXHR; } }else{ data.submit().success(function(data, status) { -- GitLab From 9b1d6246a91cf896b3f37920098ea4d0f6c6098a Mon Sep 17 00:00:00 2001 From: Jakob Sack Date: Sat, 14 Apr 2012 12:52:17 +0200 Subject: [PATCH 145/430] Remove useless, unmaintained dav.php --- apps/calendar/appinfo/app.php | 3 +- apps/calendar/lib/hooks.php | 13 ------ apps/contacts/appinfo/app.php | 1 - apps/contacts/lib/hooks.php | 13 ------ dav.php | 77 ----------------------------------- 5 files changed, 1 insertion(+), 106 deletions(-) delete mode 100644 dav.php diff --git a/apps/calendar/appinfo/app.php b/apps/calendar/appinfo/app.php index 1fece8077ac..ea743674fe8 100644 --- a/apps/calendar/appinfo/app.php +++ b/apps/calendar/appinfo/app.php @@ -7,7 +7,6 @@ OC::$CLASSPATH['OC_Calendar_Hooks'] = 'apps/calendar/lib/hooks.php'; OC::$CLASSPATH['OC_Connector_Sabre_CalDAV'] = 'apps/calendar/lib/connector_sabre.php'; OC::$CLASSPATH['OC_Search_Provider_Calendar'] = 'apps/calendar/lib/search.php'; OC_HOOK::connect('OC_User', 'post_deleteUser', 'OC_Calendar_Hooks', 'deleteUser'); -OC_Hook::connect('OC_DAV', 'initialize', 'OC_Calendar_Hooks', 'initializeCalDAV'); OC_Util::addScript('calendar','loader'); OC_App::register( array( 'order' => 10, @@ -20,4 +19,4 @@ OC_App::addNavigationEntry( array( 'icon' => OC_Helper::imagePath( 'calendar', 'icon.svg' ), 'name' => $l->t('Calendar'))); OC_App::registerPersonal('calendar', 'settings'); -OC_Search::registerProvider('OC_Search_Provider_Calendar'); \ No newline at end of file +OC_Search::registerProvider('OC_Search_Provider_Calendar'); diff --git a/apps/calendar/lib/hooks.php b/apps/calendar/lib/hooks.php index 54f1680a36e..22e8d8e20f2 100644 --- a/apps/calendar/lib/hooks.php +++ b/apps/calendar/lib/hooks.php @@ -24,17 +24,4 @@ class OC_Calendar_Hooks{ return true; } - - /** - * @brief Adds the CardDAV resource to the DAV server - * @param paramters parameters from initialize-Hook - * @return array - */ - public static function initializeCalDAV($parameters){ - // We need a backend, the root node and the caldav plugin - $parameters['backends']['caldav'] = new OC_Connector_Sabre_CalDAV(); - $parameters['nodes'][] = new Sabre_CalDAV_CalendarRootNode($parameters['backends']['principal'], $parameters['backends']['caldav']); - $parameters['plugins'][] = new Sabre_CalDAV_Plugin(); - return true; - } } diff --git a/apps/contacts/appinfo/app.php b/apps/contacts/appinfo/app.php index 0ff8fd29ef3..7e44219ce99 100644 --- a/apps/contacts/appinfo/app.php +++ b/apps/contacts/appinfo/app.php @@ -8,7 +8,6 @@ OC::$CLASSPATH['OC_Search_Provider_Contacts'] = 'apps/contacts/lib/search.php'; OC_HOOK::connect('OC_User', 'post_deleteUser', 'OC_Contacts_Hooks', 'deleteUser'); OC_HOOK::connect('OC_Calendar', 'getEvents', 'OC_Contacts_Hooks', 'getBirthdayEvents'); OC_HOOK::connect('OC_Calendar', 'getSources', 'OC_Contacts_Hooks', 'getCalenderSources'); -OC_Hook::connect('OC_DAV', 'initialize', 'OC_Contacts_Hooks', 'initializeCardDAV'); OC_App::register( array( 'order' => 10, diff --git a/apps/contacts/lib/hooks.php b/apps/contacts/lib/hooks.php index e09da20be86..b858c4a5a48 100644 --- a/apps/contacts/lib/hooks.php +++ b/apps/contacts/lib/hooks.php @@ -39,19 +39,6 @@ class OC_Contacts_Hooks{ return true; } - /** - * @brief Adds the CardDAV resource to the DAV server - * @param paramters parameters from initialize-Hook - * @return array - */ - static public function initializeCardDAV($parameters){ - // We need a backend, the root node and the carddav plugin - $parameters['backends']['carddav'] = new OC_Connector_Sabre_CardDAV(); - $parameters['nodes'][] = new Sabre_CardDAV_AddressBookRoot($parameters['backends']['principal'], $parameters['backends']['carddav']); - $parameters['plugins'][] = new Sabre_CardDAV_Plugin(); - return true; - } - static public function getCalenderSources($parameters) { $base_url = OC_Helper::linkTo('calendar', 'ajax/events.php').'?calendar_id='; foreach(OC_Contacts_Addressbook::all(OC_User::getUser()) as $addressbook) { diff --git a/dav.php b/dav.php deleted file mode 100644 index 78e2711aec8..00000000000 --- a/dav.php +++ /dev/null @@ -1,77 +0,0 @@ -. -* -*/ - -require_once('lib/base.php'); - -// Backends we always need (auth, principal and files) -$backends = array( - 'auth' => new OC_Connector_Sabre_Auth(), - 'principal' => new OC_Connector_Sabre_Principal() -); - -// Root nodes -$nodes = array( - new Sabre_CalDAV_Principal_Collection($backends['principal']) -); - -// Plugins -$plugins = array( - new Sabre_DAV_Auth_Plugin($backends['auth'],'ownCloud'), - new Sabre_DAVACL_Plugin(), - new Sabre_DAV_Browser_Plugin(false) // Show something in the Browser, but no upload -); - -// Load the plugins etc we need for usual file sharing -$backends['lock'] = new OC_Connector_Sabre_Locks(); -$plugins[] = new Sabre_DAV_Locks_Plugin($backends['lock']); -// Add a RESTful user directory -// /files/$username/ -if( OC_User::isLoggedIn()){ - $currentuser = OC_User::getUser(); - $files = new Sabre_DAV_SimpleCollection('files'); - foreach( OC_User::getUsers() as $username ){ - if( $username == $currentuser ){ - $public = new OC_Connector_Sabre_Directory('.'); - $files->addChild( new Sabre_DAV_SimpleCollection( $username, $public->getChildren())); - } - else{ - $files->addChild(new Sabre_DAV_SimpleCollection( $username )); - } - } - $nodes[] = $files; -} - -// Get the other plugins and nodes -OC_Hook::emit( 'OC_DAV', 'initialize', array( 'backends' => &$backends, 'nodes' => &$nodes, 'plugins' => &$plugins )); - -// Fire up server -$server = new Sabre_DAV_Server($nodes); -$server->setBaseUri(OC::$WEBROOT.'/dav.php'); - -// Load additional plugins -foreach( $plugins as &$plugin ){ - $server->addPlugin( $plugin ); -} unset( $plugin ); // Always do this after foreach with references! - -// And off we go! -$server->exec(); -- GitLab From 0b426b5e64eec4b255c1e767edb07e01160eb074 Mon Sep 17 00:00:00 2001 From: Jakob Sack Date: Sun, 15 Apr 2012 16:48:25 +0200 Subject: [PATCH 146/430] Display correct URL in caldav and carddav paths --- apps/calendar/templates/part.choosecalendar.rowfields.php | 2 +- apps/contacts/ajax/chooseaddressbook.php | 1 - apps/contacts/templates/part.chooseaddressbook.rowfields.php | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.php b/apps/calendar/templates/part.choosecalendar.rowfields.php index a789be45a43..d3bf6c0501c 100644 --- a/apps/calendar/templates/part.choosecalendar.rowfields.php +++ b/apps/calendar/templates/part.choosecalendar.rowfields.php @@ -1,4 +1,4 @@ "; echo "
    "; - echo ""; + echo ""; diff --git a/apps/contacts/ajax/chooseaddressbook.php b/apps/contacts/ajax/chooseaddressbook.php index 8298c16b041..d6080791299 100644 --- a/apps/contacts/ajax/chooseaddressbook.php +++ b/apps/contacts/ajax/chooseaddressbook.php @@ -12,4 +12,3 @@ OC_JSON::checkAppEnabled('contacts'); $output = new OC_TEMPLATE("contacts", "part.chooseaddressbook"); $output -> printpage(); -?> diff --git a/apps/contacts/templates/part.chooseaddressbook.rowfields.php b/apps/contacts/templates/part.chooseaddressbook.rowfields.php index 95a4b2362aa..8518c1acd13 100644 --- a/apps/contacts/templates/part.chooseaddressbook.rowfields.php +++ b/apps/contacts/templates/part.chooseaddressbook.rowfields.php @@ -2,4 +2,4 @@ // FIXME: Make this readable. echo ""; echo ""; - echo ""; + echo ""; -- GitLab From a0d917fe98efbb11905f7ddd12169e3675690555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= Date: Sun, 15 Apr 2012 16:59:39 +0200 Subject: [PATCH 147/430] fixing oc-375 - a number is appended tp the filename --- files/ajax/upload.php | 3 ++- lib/helper.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/files/ajax/upload.php b/files/ajax/upload.php index af7a7acf702..76ea65fe933 100644 --- a/files/ajax/upload.php +++ b/files/ajax/upload.php @@ -47,7 +47,8 @@ $result=array(); if(strpos($dir,'..') === false){ $fileCount=count($files['name']); for($i=0;$i<$fileCount;$i++){ - $target=stripslashes($dir) . $files['name'][$i]; + // $target=stripslashes($dir) . $files['name'][$i]; + $target = OC_Helper::buildNotExistingFileName(stripslashes($dir), $files['name'][$i]); if(is_uploaded_file($files['tmp_name'][$i]) and OC_Filesystem::fromTmpFile($files['tmp_name'][$i],$target)){ $meta=OC_FileCache::getCached($target); $result[]=array( "status" => "success", 'mime'=>$meta['mimetype'],'size'=>$meta['size'],'name'=>$files['name'][$i]); diff --git a/lib/helper.php b/lib/helper.php index c33db5f10fe..412f0e6b764 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -492,4 +492,32 @@ class OC_Helper { } } } + + /** + * Adds a suffix to the name in case the file exists + * + * @param $path + * @param $filename + * @return string + */ + public static function buildNotExistingFileName($path, $filename) + { + if ($pos = strrpos($filename, '.')) { + $name = substr($filename, 0, $pos); + $ext = substr($filename, $pos); + } else { + $name = $filename; + } + + $newpath = $path . '/' . $filename; + $newname = $filename; + $counter = 2; + while (OC_Filesystem::file_exists($newpath)) { + $newname = $name . ' (' . $counter . ')' . $ext; + $newpath = $path . '/' . $newname; + $counter++; + } + + return $newname; + } } -- GitLab From 712e25bb02518f353edddc5e9acbb56b80e2affb Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 15 Apr 2012 15:09:37 +0000 Subject: [PATCH 148/430] Update ace --- .../js/aceeditor/ace-compat-uncompressed.js | 10 - .../js/aceeditor/ace-compat.js | 2 +- .../js/aceeditor/ace-uncompressed.js | 3300 ++++++-- apps/files_texteditor/js/aceeditor/ace.js | 11 +- .../keybinding-emacs-uncompressed.js | 265 - .../js/aceeditor/keybinding-emacs.js | 2 +- .../aceeditor/keybinding-vim-uncompressed.js | 265 - .../js/aceeditor/keybinding-vim.js | 2 +- .../js/aceeditor/mode-c_cpp-uncompressed.js | 48 +- .../js/aceeditor/mode-c_cpp.js | 2 +- .../js/aceeditor/mode-clojure-uncompressed.js | 26 +- .../js/aceeditor/mode-clojure.js | 2 +- .../js/aceeditor/mode-coffee-uncompressed.js | 199 - .../js/aceeditor/mode-coffee.js | 2 +- .../aceeditor/mode-coldfusion-uncompressed.js | 542 +- .../js/aceeditor/mode-coldfusion.js | 2 +- .../js/aceeditor/mode-csharp-uncompressed.js | 48 +- .../js/aceeditor/mode-csharp.js | 2 +- .../js/aceeditor/mode-css-uncompressed.js | 277 +- .../files_texteditor/js/aceeditor/mode-css.js | 2 +- .../js/aceeditor/mode-groovy-uncompressed.js | 438 +- .../js/aceeditor/mode-groovy.js | 2 +- .../js/aceeditor/mode-haxe-uncompressed.js | 48 +- .../js/aceeditor/mode-haxe.js | 2 +- .../js/aceeditor/mode-html-uncompressed.js | 543 +- .../js/aceeditor/mode-html.js | 2 +- .../js/aceeditor/mode-java-uncompressed.js | 438 +- .../js/aceeditor/mode-java.js | 2 +- .../aceeditor/mode-javascript-uncompressed.js | 438 +- .../js/aceeditor/mode-javascript.js | 2 +- .../js/aceeditor/mode-json-uncompressed.js | 69 +- .../js/aceeditor/mode-json.js | 2 +- .../js/aceeditor/mode-latex-uncompressed.js | 10 - .../js/aceeditor/mode-latex.js | 2 +- .../js/aceeditor/mode-less-uncompressed.js | 654 ++ .../js/aceeditor/mode-less.js | 1 + .../js/aceeditor/mode-liquid-uncompressed.js | 1332 ++++ .../js/aceeditor/mode-liquid.js | 1 + .../js/aceeditor/mode-lua-uncompressed.js | 10 - .../files_texteditor/js/aceeditor/mode-lua.js | 2 +- .../aceeditor/mode-markdown-uncompressed.js | 557 +- .../js/aceeditor/mode-markdown.js | 2 +- .../js/aceeditor/mode-ocaml-uncompressed.js | 10 - .../js/aceeditor/mode-ocaml.js | 2 +- .../js/aceeditor/mode-perl-uncompressed.js | 10 - .../js/aceeditor/mode-perl.js | 2 +- .../js/aceeditor/mode-pgsql-uncompressed.js | 1107 +++ .../js/aceeditor/mode-pgsql.js | 1 + .../js/aceeditor/mode-php-uncompressed.js | 66 +- .../files_texteditor/js/aceeditor/mode-php.js | 2 +- .../aceeditor/mode-powershell-uncompressed.js | 48 +- .../js/aceeditor/mode-powershell.js | 2 +- .../js/aceeditor/mode-python-uncompressed.js | 10 - .../js/aceeditor/mode-python.js | 2 +- .../js/aceeditor/mode-ruby-uncompressed.js | 10 - .../js/aceeditor/mode-ruby.js | 2 +- .../js/aceeditor/mode-scad-uncompressed.js | 48 +- .../js/aceeditor/mode-scad.js | 2 +- .../js/aceeditor/mode-scala-uncompressed.js | 438 +- .../js/aceeditor/mode-scala.js | 2 +- .../js/aceeditor/mode-scss-uncompressed.js | 10 - .../js/aceeditor/mode-scss.js | 2 +- .../js/aceeditor/mode-sh-uncompressed.js | 281 + apps/files_texteditor/js/aceeditor/mode-sh.js | 1 + .../js/aceeditor/mode-sql-uncompressed.js | 10 - .../files_texteditor/js/aceeditor/mode-sql.js | 2 +- .../js/aceeditor/mode-svg-uncompressed.js | 461 +- .../files_texteditor/js/aceeditor/mode-svg.js | 2 +- .../js/aceeditor/mode-text-uncompressed.js | 0 .../js/aceeditor/mode-text.js | 0 .../js/aceeditor/mode-textile-uncompressed.js | 10 - .../js/aceeditor/mode-textile.js | 2 +- .../js/aceeditor/mode-xml-uncompressed.js | 70 +- .../files_texteditor/js/aceeditor/mode-xml.js | 2 +- .../js/aceeditor/mode-xquery-uncompressed.js | 540 ++ .../js/aceeditor/mode-xquery.js | 1 + .../js/aceeditor/theme-clouds-uncompressed.js | 29 +- .../js/aceeditor/theme-clouds.js | 2 +- .../js/aceeditor/worker-coffee.js | 3221 ++++---- .../js/aceeditor/worker-css.js | 3356 +++++++-- .../js/aceeditor/worker-javascript.js | 6682 ++++++++++------- .../js/aceeditor/worker-json.js | 3083 ++++++++ apps/files_texteditor/js/editor.js | 2 + 83 files changed, 20049 insertions(+), 9050 deletions(-) create mode 100755 apps/files_texteditor/js/aceeditor/mode-less-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-less.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-liquid-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-liquid.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-pgsql-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-pgsql.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-sh-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-sh.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-text-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-text.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-xquery-uncompressed.js create mode 100755 apps/files_texteditor/js/aceeditor/mode-xquery.js create mode 100755 apps/files_texteditor/js/aceeditor/worker-json.js diff --git a/apps/files_texteditor/js/aceeditor/ace-compat-uncompressed.js b/apps/files_texteditor/js/aceeditor/ace-compat-uncompressed.js index 7fa232a335f..50efbe1443c 100755 --- a/apps/files_texteditor/js/aceeditor/ace-compat-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/ace-compat-uncompressed.js @@ -478,13 +478,3 @@ define('pilot/canon', ['require', 'exports', 'module' ], function(require, expor console.trace(); } }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/ace-compat.js b/apps/files_texteditor/js/aceeditor/ace-compat.js index 5dcbb1cc38a..18d2ed78d0f 100755 --- a/apps/files_texteditor/js/aceeditor/ace-compat.js +++ b/apps/files_texteditor/js/aceeditor/ace-compat.js @@ -1 +1 @@ -define("pilot/index",["require","exports","module","pilot/browser_focus","pilot/dom","pilot/event","pilot/event_emitter","pilot/fixoldbrowsers","pilot/keys","pilot/lang","pilot/oop","pilot/useragent","pilot/canon"],function(a,b,c){a("pilot/browser_focus"),a("pilot/dom"),a("pilot/event"),a("pilot/event_emitter"),a("pilot/fixoldbrowsers"),a("pilot/keys"),a("pilot/lang"),a("pilot/oop"),a("pilot/useragent"),a("pilot/canon")}),define("pilot/browser_focus",["require","exports","module","ace/lib/browser_focus"],function(a,b,c){console.warn("DEPRECATED: 'pilot/browser_focus' is deprecated. Use 'ace/lib/browser_focus' instead"),c.exports=a("ace/lib/browser_focus")}),define("pilot/dom",["require","exports","module","ace/lib/dom"],function(a,b,c){console.warn("DEPRECATED: 'pilot/dom' is deprecated. Use 'ace/lib/dom' instead"),c.exports=a("ace/lib/dom")}),define("pilot/event",["require","exports","module","ace/lib/event"],function(a,b,c){console.warn("DEPRECATED: 'pilot/event' is deprecated. Use 'ace/lib/event' instead"),c.exports=a("ace/lib/event")}),define("pilot/event_emitter",["require","exports","module","ace/lib/event_emitter"],function(a,b,c){console.warn("DEPRECATED: 'pilot/event_emitter' is deprecated. Use 'ace/lib/event_emitter' instead"),c.exports=a("ace/lib/event_emitter")}),define("pilot/fixoldbrowsers",["require","exports","module","ace/lib/fixoldbrowsers"],function(a,b,c){console.warn("DEPRECATED: 'pilot/fixoldbrowsers' is deprecated. Use 'ace/lib/fixoldbrowsers' instead"),c.exports=a("ace/lib/fixoldbrowsers")}),define("pilot/keys",["require","exports","module","ace/lib/keys"],function(a,b,c){console.warn("DEPRECATED: 'pilot/keys' is deprecated. Use 'ace/lib/keys' instead"),c.exports=a("ace/lib/keys")}),define("pilot/lang",["require","exports","module","ace/lib/lang"],function(a,b,c){console.warn("DEPRECATED: 'pilot/lang' is deprecated. Use 'ace/lib/lang' instead"),c.exports=a("ace/lib/lang")}),define("pilot/oop",["require","exports","module","ace/lib/oop"],function(a,b,c){console.warn("DEPRECATED: 'pilot/oop' is deprecated. Use 'ace/lib/oop' instead"),c.exports=a("ace/lib/oop")}),define("pilot/useragent",["require","exports","module","ace/lib/useragent"],function(a,b,c){console.warn("DEPRECATED: 'pilot/useragent' is deprecated. Use 'ace/lib/useragent' instead"),c.exports=a("ace/lib/useragent")}),define("pilot/canon",["require","exports","module"],function(a,b,c){console.warn("DEPRECATED: 'pilot/canon' is deprecated."),b.addCommand=function(){console.warn("DEPRECATED: 'canon.addCommand()' is deprecated. Use 'editor.commands.addCommand(command)' instead."),console.trace()},b.removeCommand=function(){console.warn("DEPRECATED: 'canon.removeCommand()' is deprecated. Use 'editor.commands.removeCommand(command)' instead."),console.trace()}}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("pilot/index",["require","exports","module","pilot/browser_focus","pilot/dom","pilot/event","pilot/event_emitter","pilot/fixoldbrowsers","pilot/keys","pilot/lang","pilot/oop","pilot/useragent","pilot/canon"],function(a,b,c){a("pilot/browser_focus"),a("pilot/dom"),a("pilot/event"),a("pilot/event_emitter"),a("pilot/fixoldbrowsers"),a("pilot/keys"),a("pilot/lang"),a("pilot/oop"),a("pilot/useragent"),a("pilot/canon")}),define("pilot/browser_focus",["require","exports","module","ace/lib/browser_focus"],function(a,b,c){console.warn("DEPRECATED: 'pilot/browser_focus' is deprecated. Use 'ace/lib/browser_focus' instead"),c.exports=a("ace/lib/browser_focus")}),define("pilot/dom",["require","exports","module","ace/lib/dom"],function(a,b,c){console.warn("DEPRECATED: 'pilot/dom' is deprecated. Use 'ace/lib/dom' instead"),c.exports=a("ace/lib/dom")}),define("pilot/event",["require","exports","module","ace/lib/event"],function(a,b,c){console.warn("DEPRECATED: 'pilot/event' is deprecated. Use 'ace/lib/event' instead"),c.exports=a("ace/lib/event")}),define("pilot/event_emitter",["require","exports","module","ace/lib/event_emitter"],function(a,b,c){console.warn("DEPRECATED: 'pilot/event_emitter' is deprecated. Use 'ace/lib/event_emitter' instead"),c.exports=a("ace/lib/event_emitter")}),define("pilot/fixoldbrowsers",["require","exports","module","ace/lib/fixoldbrowsers"],function(a,b,c){console.warn("DEPRECATED: 'pilot/fixoldbrowsers' is deprecated. Use 'ace/lib/fixoldbrowsers' instead"),c.exports=a("ace/lib/fixoldbrowsers")}),define("pilot/keys",["require","exports","module","ace/lib/keys"],function(a,b,c){console.warn("DEPRECATED: 'pilot/keys' is deprecated. Use 'ace/lib/keys' instead"),c.exports=a("ace/lib/keys")}),define("pilot/lang",["require","exports","module","ace/lib/lang"],function(a,b,c){console.warn("DEPRECATED: 'pilot/lang' is deprecated. Use 'ace/lib/lang' instead"),c.exports=a("ace/lib/lang")}),define("pilot/oop",["require","exports","module","ace/lib/oop"],function(a,b,c){console.warn("DEPRECATED: 'pilot/oop' is deprecated. Use 'ace/lib/oop' instead"),c.exports=a("ace/lib/oop")}),define("pilot/useragent",["require","exports","module","ace/lib/useragent"],function(a,b,c){console.warn("DEPRECATED: 'pilot/useragent' is deprecated. Use 'ace/lib/useragent' instead"),c.exports=a("ace/lib/useragent")}),define("pilot/canon",["require","exports","module"],function(a,b,c){console.warn("DEPRECATED: 'pilot/canon' is deprecated."),b.addCommand=function(){console.warn("DEPRECATED: 'canon.addCommand()' is deprecated. Use 'editor.commands.addCommand(command)' instead."),console.trace()},b.removeCommand=function(){console.warn("DEPRECATED: 'canon.removeCommand()' is deprecated. Use 'editor.commands.removeCommand(command)' instead."),console.trace()}}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/ace-uncompressed.js b/apps/files_texteditor/js/aceeditor/ace-uncompressed.js index 619baf49016..74bb44b16d8 100755 --- a/apps/files_texteditor/js/aceeditor/ace-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/ace-uncompressed.js @@ -40,7 +40,7 @@ * @param module a name for the payload * @param payload a function to call with (require, exports, module) params */ - + (function() { var ACE_NAMESPACE = ""; @@ -49,9 +49,6 @@ var global = (function() { return this; })(); -if (typeof requirejs !== "undefined") - return; - var _define = function(module, deps, payload) { if (typeof module !== 'string') { if (_define.original) @@ -68,7 +65,7 @@ var _define = function(module, deps, payload) { if (!_define.modules) _define.modules = {}; - + _define.modules[module] = payload; }; @@ -92,11 +89,11 @@ var _require = function(parentId, module, callback) { var payload = lookup(parentId, module); if (!payload && _require.original) return _require.original.apply(window, arguments); - + if (callback) { callback(); } - + return payload; } else { @@ -115,13 +112,13 @@ var normalizeModule = function(parentId, moduleName) { if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = base + "/" + moduleName; - + while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } - + return moduleName; }; @@ -141,19 +138,19 @@ var lookup = function(parentId, moduleName) { if (typeof module === 'function') { var exports = {}; var mod = { - id: moduleName, + id: moduleName, uri: '', exports: exports, packaged: true }; - + var req = function(module, callback) { return _require(moduleName, module, callback); }; - + var returnValue = module(req, exports, mod); exports = returnValue || mod.exports; - + // cache the resulting module object for next time _define.modules[moduleName] = exports; return exports; @@ -163,26 +160,45 @@ var lookup = function(parentId, moduleName) { }; function exportAce(ns) { + + if (typeof requirejs !== "undefined") { + + var define = global.define; + global.define = function(id, deps, callback) { + if (typeof callback !== "function") + return define.apply(this, arguments); + + return define(id, deps, function(require, exports, module) { + if (deps[2] == "module") + module.packaged = true; + return callback.apply(this, arguments); + }); + }; + global.define.packaged = true; + + return; + } + var require = function(module, callback) { return _require("", module, callback); }; require.packaged = true; - + var root = global; if (ns) { if (!global[ns]) global[ns] = {}; root = global[ns]; } - + if (root.define) _define.original = root.define; - + root.define = _define; if (root.require) _require.original = root.require; - + root.require = require; } @@ -225,7 +241,7 @@ exportAce(ACE_NAMESPACE); * * ***** END LICENSE BLOCK ***** */ -define('ace/ace', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/dom', 'ace/lib/event', 'ace/editor', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/theme/textmate'], function(require, exports, module) { +define('ace/ace', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/dom', 'ace/lib/event', 'ace/editor', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/multi_select', 'ace/worker/worker_client', 'ace/keyboard/hash_handler', 'ace/keyboard/state_handler', 'ace/placeholder', 'ace/config', 'ace/theme/textmate'], function(require, exports, module) { "use strict"; require("./lib/fixoldbrowsers"); @@ -237,6 +253,14 @@ var Editor = require("./editor").Editor; var EditSession = require("./edit_session").EditSession; var UndoManager = require("./undomanager").UndoManager; var Renderer = require("./virtual_renderer").VirtualRenderer; +var MultiSelect = require("./multi_select").MultiSelect; + +// The following require()s are for inclusion in the built ace file +require("./worker/worker_client"); +require("./keyboard/hash_handler"); +require("./keyboard/state_handler"); +require("./placeholder"); +require("./config").init(); exports.edit = function(el) { if (typeof(el) == "string") { @@ -248,6 +272,7 @@ exports.edit = function(el) { el.innerHTML = ''; var editor = new Editor(new Renderer(el, require("./theme/textmate"))); + new MultiSelect(editor); editor.setSession(doc); var env = {}; @@ -326,7 +351,7 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; - if (match) { + if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { @@ -391,7 +416,8 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex return -1; }; -});// vim: ts=4 sts=4 sw=4 expandtab +}); +// vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA @@ -1573,7 +1599,7 @@ exports.hasCssString = function(id, doc) { if (doc.createStyleSheet && (sheets = doc.styleSheets)) { while (index < sheets.length) - if (sheets[index++].title === id) return true; + if (sheets[index++].owningElement.id === id) return true; } else if ((sheets = doc.getElementsByTagName("style"))) { while (index < sheets.length) if (sheets[index++].id === id) return true; @@ -1594,7 +1620,7 @@ exports.importCssString = function importCssString(cssText, id, doc) { style = doc.createStyleSheet(); style.cssText = cssText; if (id) - style.title = id; + style.owningElement.id = id; } else { style = doc.createElementNS ? doc.createElementNS(XHTML_NS, "style") @@ -1740,8 +1766,7 @@ exports.getParentWindow = function(document) { return document.defaultView || document.parentWindow; }; -}); -/* ***** BEGIN LICENSE BLOCK ***** +});/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version @@ -1917,20 +1942,9 @@ else { } exports.addMouseWheelListener = function(el, callback) { - var max = 0; + var factor = 8; var listener = function(e) { if (e.wheelDelta !== undefined) { - - // some versions of Safari (e.g. 5.0.5) report insanely high - // scroll values. These browsers require a higher factor - if (Math.abs(e.wheelDeltaY) > max) - max = Math.abs(e.wheelDeltaY); - - if (max > 5000) - var factor = 400; - else - var factor = 8; - if (e.wheelDeltaX !== undefined) { e.wheelX = -e.wheelDeltaX / factor; e.wheelY = -e.wheelDeltaY / factor; @@ -2029,7 +2043,7 @@ function normalizeCommandKeys(callback, e, keyCode) { exports.addCommandKeyListener = function(el, callback) { var addListener = exports.addListener; - if (useragent.isOldGecko) { + if (useragent.isOldGecko || useragent.isOpera) { // Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown // event if the user pressed the key for a longer time. Instead, the // keydown event was fired once and later on only the keypress event. @@ -2050,18 +2064,6 @@ exports.addCommandKeyListener = function(el, callback) { lastDown = e.keyIdentifier || e.keyCode; return normalizeCommandKeys(callback, e, e.keyCode); }); - - // repeated keys are fired as keypress and not keydown events - if (useragent.isMac && useragent.isOpera) { - addListener(el, "keypress", function(e) { - var keyId = e.keyIdentifier || e.keyCode; - if (lastDown !== keyId) { - return normalizeCommandKeys(callback, e, lastDown); - } else { - lastDown = null; - } - }); - } } }; @@ -2446,7 +2448,7 @@ var Editor = function(renderer, session) { var container = renderer.getContainerElement(); this.container = container; this.renderer = renderer; - + this.textInput = new TextInput(renderer.getTextAreaContainer(), this); this.keyBinding = new KeyBinding(this); @@ -2558,7 +2560,10 @@ var Editor = function(renderer, session) { this.onChangeMode(); + this.$blockScrolling += 1; this.onCursorChange(); + this.$blockScrolling -= 1; + this.onScrollTopChange(); this.onScrollLeftChange(); this.onSelectionChange(); @@ -2605,6 +2610,7 @@ var Editor = function(renderer, session) { this.setFontSize = function(size) { this.container.style.fontSize = size; + this.renderer.updateFontSize(); }; this.$highlightBrackets = function() { @@ -2710,21 +2716,29 @@ var Editor = function(renderer, session) { this.$updateHighlightActiveLine = function() { var session = this.getSession(); - if (session.$highlightLineMarker) { + if (session.$highlightLineMarker) session.removeMarker(session.$highlightLineMarker); - } + if (typeof this.$lastrow == "number") + this.renderer.removeGutterDecoration(this.$lastrow, "ace_gutter_active_line"); + session.$highlightLineMarker = null; + this.$lastrow = null; - if (this.getHighlightActiveLine() && (this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) { + if (this.getHighlightActiveLine()) { var cursor = this.getCursorPosition(), foldLine = this.session.getFoldLine(cursor.row); - var range; - if (foldLine) { - range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0); - } else { - range = new Range(cursor.row, 0, cursor.row+1, 0); + + if ((this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) { + var range; + if (foldLine) { + range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0); + } else { + range = new Range(cursor.row, 0, cursor.row+1, 0); + } + session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background"); } - session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background"); + + this.renderer.addGutterDecoration(this.$lastrow = cursor.row, "ace_gutter_active_line"); } }; @@ -2794,16 +2808,7 @@ var Editor = function(renderer, session) { }; this.onCut = function() { - if (this.$readOnly) - return; - - var range = this.getSelectionRange(); - this._emit("cut", range); - - if (!this.selection.isEmpty()) { - this.session.remove(range); - this.clearSelection(); - } + this.commands.exec("cut", this); }; this.insert = function(text) { @@ -2978,6 +2983,14 @@ var Editor = function(renderer, session) { return this.$highlightSelectedWord; }; + this.setAnimatedScroll = function(shouldAnimate){ + this.renderer.setAnimatedScroll(shouldAnimate); + }; + + this.getAnimatedScroll = function(){ + return this.renderer.getAnimatedScroll(); + }; + this.setShowInvisibles = function(showInvisibles) { if (this.getShowInvisibles() == showInvisibles) return; @@ -3032,7 +3045,7 @@ var Editor = function(renderer, session) { this.$showFoldWidgets = show; this.renderer.updateFull(); }; - + this.getShowFoldWidgets = function() { return this.renderer.$gutterLayer.getShowFoldWidgets(); }; @@ -3249,7 +3262,7 @@ var Editor = function(renderer, session) { range.start.row += linesMoved; range.end.row += linesMoved; selection.setSelectionRange(range, reverse); - } + } else { selection.setSelectionAnchor(rows.last+linesMoved+1, 0); selection.$moveSelection(function() { @@ -3413,13 +3426,13 @@ var Editor = function(renderer, session) { cursor.column -= 2; pos = this.session.findMatchingBracket(cursor); } - + if (pos) { this.clearSelection(); this.moveCursorTo(pos.row, pos.column); } }; - + this.gotoLine = function(lineNumber, column) { this.selection.clearSelection(); this.session.unfold({row: lineNumber - 1, column: column || 0}); @@ -3511,12 +3524,19 @@ var Editor = function(renderer, session) { this.$search.set(options); var range = this.$search.find(this.session); + var replaced = 0; if (!range) - return; + return replaced; - this.$tryReplace(range, replacement); - if (range !== null) + if (this.$tryReplace(range, replacement)) { + replaced = 1; + } + if (range !== null) { this.selection.setSelectionRange(range); + this.renderer.scrollSelectionIntoView(range.start, range.end); + } + + return replaced; }; this.replaceAll = function(replacement, options) { @@ -3525,19 +3545,25 @@ var Editor = function(renderer, session) { } var ranges = this.$search.findAll(this.session); + var replaced = 0; if (!ranges.length) - return; + return replaced; var selection = this.getSelectionRange(); this.clearSelection(); this.selection.moveCursorTo(0, 0); this.$blockScrolling += 1; - for (var i = ranges.length - 1; i >= 0; --i) - this.$tryReplace(ranges[i], replacement); + for (var i = ranges.length - 1; i >= 0; --i) { + if(this.$tryReplace(ranges[i], replacement)) { + replaced++; + } + } this.selection.setSelectionRange(selection); this.$blockScrolling -= 1; + + return replaced; }; this.$tryReplace = function(range, replacement) { @@ -3589,8 +3615,23 @@ var Editor = function(renderer, session) { var range = this.$search.find(this.session); if (range) { this.session.unfold(range); - this.gotoLine(range.end.row+1, range.end.column); + + this.$blockScrolling += 1; this.selection.setSelectionRange(range); + this.$blockScrolling -= 1; + + if (this.getAnimatedScroll()) { + var cursor = this.getCursorPosition(); + if (!this.isRowFullyVisible(cursor.row)) + this.scrollToLine(cursor.row, true); + + //@todo scroll X + //if (!this.isColumnFullyVisible(cursor.column)) + //this.scrollToRow(cursor.column); + } + else { + this.renderer.scrollSelectionIntoView(range.start, range.end); + } } }; @@ -4298,7 +4339,7 @@ function DefaultHandlers(editor) { if (!editor.$mouseHandler.$clickSelection) { if (!dragCursor) { editor.moveCursorToPosition(pos); - editor.selection.clearSelection(pos.row, pos.column); + editor.selection.clearSelection(); } } @@ -4333,7 +4374,6 @@ function DefaultHandlers(editor) { if (distance > DRAG_OFFSET) { state = STATE_SELECT; var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY); - cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1)); onStartSelect(cursor); } else if ((time - mousedownTime) > editor.getDragDelay()) { @@ -4360,7 +4400,7 @@ function DefaultHandlers(editor) { else { if (!_self.$clickSelection) { editor.moveCursorToPosition(pos); - editor.selection.clearSelection(pos.row, pos.column); + editor.selection.clearSelection(); } } state = STATE_SELECT; @@ -4369,7 +4409,6 @@ function DefaultHandlers(editor) { var onUpdateSelectionInterval = function() { var anchor; var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY); - cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1)); if (_self.$clickSelection) { if (_self.$clickSelection.contains(cursor.row, cursor.column)) { @@ -4395,8 +4434,6 @@ function DefaultHandlers(editor) { var onDragSelectionInterval = function() { dragCursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY); - dragCursor.row = Math.max(0, Math.min(dragCursor.row, editor.session.getLength() - 1)); - editor.moveCursorToPosition(dragCursor); }; @@ -4818,7 +4855,6 @@ var MouseEvent = exports.MouseEvent = function(domEvent, editor) { var pageX = event.getDocumentX(this.domEvent); var pageY = event.getDocumentY(this.domEvent); this.$pos = this.editor.renderer.screenToTextCoordinates(pageX, pageY); - this.$pos.row = Math.max(0, Math.min(this.$pos.row, this.editor.session.getLength()-1)); return this.$pos; }; @@ -4918,7 +4954,7 @@ function FoldHandler(editor) { var position = e.getDocumentPosition(); var session = editor.session; - // If the user dclicked on a fold, then expand it. + // If the user clicked on a fold, then expand it. var fold = session.getFoldAt(position.row, position.column, 1); if (fold) { if (e.getAccelKey()) @@ -5198,91 +5234,109 @@ exports.commands = [{ name: "selectup", bindKey: bindKey("Shift-Up", "Shift-Up"), exec: function(editor) { editor.getSelection().selectUp(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "golineup", bindKey: bindKey("Up", "Up|Ctrl-P"), exec: function(editor, args) { editor.navigateUp(args.times); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selecttoend", bindKey: bindKey("Ctrl-Shift-End|Alt-Shift-Down", "Command-Shift-Down"), exec: function(editor) { editor.getSelection().selectFileEnd(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotoend", bindKey: bindKey("Ctrl-End|Ctrl-Down", "Command-End|Command-Down"), exec: function(editor) { editor.navigateFileEnd(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectdown", bindKey: bindKey("Shift-Down", "Shift-Down"), exec: function(editor) { editor.getSelection().selectDown(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "golinedown", bindKey: bindKey("Down", "Down|Ctrl-N"), exec: function(editor, args) { editor.navigateDown(args.times); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectwordleft", bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), exec: function(editor) { editor.getSelection().selectWordLeft(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotowordleft", bindKey: bindKey("Ctrl-Left", "Option-Left"), exec: function(editor) { editor.navigateWordLeft(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selecttolinestart", bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"), exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotolinestart", bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), exec: function(editor) { editor.navigateLineStart(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectleft", bindKey: bindKey("Shift-Left", "Shift-Left"), exec: function(editor) { editor.getSelection().selectLeft(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotoleft", bindKey: bindKey("Left", "Left|Ctrl-B"), exec: function(editor, args) { editor.navigateLeft(args.times); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectwordright", bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), exec: function(editor) { editor.getSelection().selectWordRight(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotowordright", bindKey: bindKey("Ctrl-Right", "Option-Right"), exec: function(editor) { editor.navigateWordRight(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selecttolineend", bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotolineend", bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), exec: function(editor) { editor.navigateLineEnd(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectright", bindKey: bindKey("Shift-Right", "Shift-Right"), exec: function(editor) { editor.getSelection().selectRight(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "gotoright", bindKey: bindKey("Right", "Right|Ctrl-F"), exec: function(editor, args) { editor.navigateRight(args.times); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectpagedown", @@ -5318,11 +5372,13 @@ exports.commands = [{ name: "selectlinestart", bindKey: bindKey("Shift-Home", "Shift-Home"), exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "selectlineend", bindKey: bindKey("Shift-End", "Shift-End"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", readOnly: true }, { name: "togglerecording", @@ -5334,17 +5390,37 @@ exports.commands = [{ bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"), exec: function(editor) { editor.commands.replay(editor); }, readOnly: true +}, { + name: "jumptomatching", + bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), + exec: function(editor) { editor.jumpToMatching(); }, + multiSelectAction: "forEach", + readOnly: true }, // commands disabled in readOnly mode { + name: "cut", + exec: function(editor) { + var range = editor.getSelectionRange(); + editor._emit("cut", range); + + if (!editor.selection.isEmpty()) { + editor.session.remove(range); + editor.clearSelection(); + } + }, + multiSelectAction: "forEach" +}, { name: "removeline", bindKey: bindKey("Ctrl-D", "Command-D"), - exec: function(editor) { editor.removeLines(); } + exec: function(editor) { editor.removeLines(); }, + multiSelectAction: "forEach" }, { name: "togglecomment", bindKey: bindKey("Ctrl-7", "Command-7"), - exec: function(editor) { editor.toggleCommentLines(); } + exec: function(editor) { editor.toggleCommentLines(); }, + multiSelectAction: "forEach" }, { name: "replace", bindKey: bindKey("Ctrl-R", "Command-Option-F"), @@ -5396,66 +5472,76 @@ exports.commands = [{ }, { name: "del", bindKey: bindKey("Delete", "Delete|Ctrl-D"), - exec: function(editor) { editor.remove("right"); } + exec: function(editor) { editor.remove("right"); }, + multiSelectAction: "forEach" }, { name: "backspace", bindKey: bindKey( - "Ctrl-Backspace|Command-Backspace|Option-Backspace|Shift-Backspace|Backspace", + "Command-Backspace|Option-Backspace|Shift-Backspace|Backspace", "Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H" ), - exec: function(editor) { editor.remove("left"); } + exec: function(editor) { editor.remove("left"); }, + multiSelectAction: "forEach" }, { name: "removetolinestart", - bindKey: bindKey("Alt-Backspace", "Option-Backspace"), - exec: function(editor) { editor.removeToLineStart(); } + bindKey: bindKey("Alt-Backspace", "Command-Backspace"), + exec: function(editor) { editor.removeToLineStart(); }, + multiSelectAction: "forEach" }, { name: "removetolineend", bindKey: bindKey("Alt-Delete", "Ctrl-K"), - exec: function(editor) { editor.removeToLineEnd(); } + exec: function(editor) { editor.removeToLineEnd(); }, + multiSelectAction: "forEach" }, { name: "removewordleft", bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), - exec: function(editor) { editor.removeWordLeft(); } + exec: function(editor) { editor.removeWordLeft(); }, + multiSelectAction: "forEach" }, { name: "removewordright", bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), - exec: function(editor) { editor.removeWordRight(); } + exec: function(editor) { editor.removeWordRight(); }, + multiSelectAction: "forEach" }, { name: "outdent", bindKey: bindKey("Shift-Tab", "Shift-Tab"), - exec: function(editor) { editor.blockOutdent(); } + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEach" }, { name: "indent", bindKey: bindKey("Tab", "Tab"), - exec: function(editor) { editor.indent(); } + exec: function(editor) { editor.indent(); }, + multiSelectAction: "forEach" }, { name: "insertstring", - exec: function(editor, str) { editor.insert(str); } + exec: function(editor, str) { editor.insert(str); }, + multiSelectAction: "forEach" }, { name: "inserttext", exec: function(editor, args) { editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); - } + }, + multiSelectAction: "forEach" }, { name: "splitline", bindKey: bindKey(null, "Ctrl-O"), - exec: function(editor) { editor.splitLine(); } + exec: function(editor) { editor.splitLine(); }, + multiSelectAction: "forEach" }, { name: "transposeletters", bindKey: bindKey("Ctrl-T", "Ctrl-T"), - exec: function(editor) { editor.transposeLetters(); } + exec: function(editor) { editor.transposeLetters(); }, + multiSelectAction: function(editor) {editor.transposeSelections(1); } }, { name: "touppercase", bindKey: bindKey("Ctrl-U", "Ctrl-U"), - exec: function(editor) { editor.toUpperCase(); } + exec: function(editor) { editor.toUpperCase(); }, + multiSelectAction: "forEach" }, { name: "tolowercase", bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), - exec: function(editor) { editor.toLowerCase(); } -}, { - name: "jumptomatching", - bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), - exec: function(editor) { editor.jumpToMatching(); } + exec: function(editor) { editor.toLowerCase(); }, + multiSelectAction: "forEach" }]; }); @@ -5499,11 +5585,13 @@ exports.commands = [{ * * ***** END LICENSE BLOCK ***** */ -define('ace/edit_session', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/event_emitter', 'ace/selection', 'ace/mode/text', 'ace/range', 'ace/document', 'ace/background_tokenizer', 'ace/edit_session/folding', 'ace/edit_session/bracket_match'], function(require, exports, module) { +define('ace/edit_session', ['require', 'exports', 'module' , 'ace/config', 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/net', 'ace/lib/event_emitter', 'ace/selection', 'ace/mode/text', 'ace/range', 'ace/document', 'ace/background_tokenizer', 'ace/edit_session/folding', 'ace/edit_session/bracket_match'], function(require, exports, module) { "use strict"; +var config = require("./config"); var oop = require("./lib/oop"); var lang = require("./lib/lang"); +var net = require("./lib/net"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Selection = require("./selection").Selection; var TextMode = require("./mode/text").Mode; @@ -5945,10 +6033,65 @@ var EditSession = function(text, mode) { this._emit("tokenizerUpdate", e); }; + this.$modes = {}; + this._loadMode = function(mode, callback) { + if (this.$modes[mode]) + return callback(this.$modes[mode]); + + var _self = this; + var module; + try { + module = require(mode); + } catch (e) {}; + if (module) + return done(module); + + fetch(function() { + require([mode], done); + }); + + function done(module) { + if (_self.$modes[mode]) + return callback(_self.$modes[mode]); + + _self.$modes[mode] = new module.Mode(); + _self._emit("loadmode", { + name: mode, + mode: _self.$modes[mode] + }); + callback(_self.$modes[mode]); + } + + function fetch(callback) { + if (!config.get("packaged")) + return callback(); + + var base = mode.split("/").pop(); + var filename = config.get("modePath") + "/mode-" + base + config.get("suffix"); + net.loadScript(filename, callback); + } + }; + this.$mode = null; + this.$origMode = null; this.setMode = function(mode) { + this.$origMode = mode; + + // load on demand + if (typeof mode === "string") { + var _self = this; + this._loadMode(mode, function(module) { + if (_self.$origMode !== mode) + return; + + _self.setMode(module); + }); + return; + } + if (this.$mode === mode) return; this.$mode = mode; + this.$stopWorker(); @@ -6847,8 +6990,8 @@ var EditSession = function(text, mode) { } this.getScreenLastRowColumn = function(screenRow) { - //return this.screenToDocumentColumn(screenRow, Number.MAX_VALUE / 10) - return this.documentToScreenColumn(screenRow, this.doc.getLine(screenRow).length); + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE) + return this.documentToScreenColumn(pos.row, pos.column); }; this.getDocumentLastRowColumn = function(docRow, docColumn) { @@ -6963,16 +7106,10 @@ var EditSession = function(text, mode) { docColumn += this.$getStringScreenWidth(line, screenColumn)[1]; - // Need to do some clamping action here. - if (this.$useWrapMode) { - if (docColumn >= column) { - // We remove one character at the end such that the docColumn - // position returned is not associated to the next row on the - // screen. - docColumn = column - 1; - } - } else { - docColumn = Math.min(docColumn, line.length); + // We remove one character at the end so that the docColumn + // position returned is not associated to the next row on the screen. + if (this.$useWrapMode && docColumn >= column) { + docColumn = column - 1; } if (foldLine) { @@ -7174,7 +7311,195 @@ require("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype) exports.EditSession = EditSession; }); -/* ***** BEGIN LICENSE BLOCK ***** +/* vim:ts=4:sts=4:sw=4: + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/config', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { +"no use strict"; + +var lang = require("./lib/lang"); + +var global = (function() { + return this; +})(); + +var options = { + packaged: false, + workerPath: "", + modePath: "", + themePath: "", + suffix: ".js" +}; + +exports.get = function(key) { + if (!options.hasOwnProperty(key)) + throw new Error("Unknown confik key: " + key); + + return options[key]; +}; + +exports.set = function(key, value) { + if (!options.hasOwnProperty(key)) + throw new Error("Unknown confik key: " + key); + + options[key] = value; +}; + +exports.all = function() { + return lang.copyObject(options); +}; + +exports.init = function() { + options.packaged = require.packaged || module.packaged || (global.define && define.packaged); + + if (!global.document) + return ""; + + var scriptOptions = {}; + var scriptUrl = ""; + var suffix; + + var scripts = document.getElementsByTagName("script"); + for (var i=0; i= line.length) { this.moveCursorTo(row, line.length); @@ -7584,7 +7904,7 @@ var Selection = function(session) { this.moveCursorWordRight(); return; } - + // advance to the end of the next token if (match = this.session.tokenRe.exec(rightOfCursor)) { column += this.session.tokenRe.lastIndex; @@ -7609,19 +7929,19 @@ var Selection = function(session) { if (str == null) { str = this.doc.getLine(row).substring(0, column) } - + var leftOfCursor = lang.stringReverse(str); var match; this.session.nonTokenRe.lastIndex = 0; this.session.tokenRe.lastIndex = 0; - + // skip whitespace if (match = this.session.nonTokenRe.exec(leftOfCursor)) { column -= this.session.nonTokenRe.lastIndex; leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex); this.session.nonTokenRe.lastIndex = 0; } - + // if at begin of the line proceed in line above if (column <= 0) { this.moveCursorTo(row, 0); @@ -7646,8 +7966,14 @@ var Selection = function(session) { this.selectionLead.column ); - var screenCol = (chars === 0 && this.$desiredColumn) || screenPos.column; - var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenCol); + if (chars === 0) { + if (this.$desiredColumn) + screenPos.column = this.$desiredColumn; + else + this.$desiredColumn = screenPos.column; + } + + var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column); // move the cursor and update the desired column this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0); @@ -7657,7 +7983,7 @@ var Selection = function(session) { this.moveCursorTo(position.row, position.column); }; - this.moveCursorTo = function(row, column, preventUpdateDesiredColumn) { + this.moveCursorTo = function(row, column, keepDesiredColumn) { // Ensure the row/column is not inside of a fold. var fold = this.session.getFoldAt(row, column, 1); if (fold) { @@ -7665,21 +7991,47 @@ var Selection = function(session) { column = fold.start.column; } - this.$preventUpdateDesiredColumnOnChange = true; + this.$keepDesiredColumnOnChange = true; this.selectionLead.setPosition(row, column); - this.$preventUpdateDesiredColumnOnChange = false; + this.$keepDesiredColumnOnChange = false; - if (!preventUpdateDesiredColumn) - this.$updateDesiredColumn(this.selectionLead.column); + if (!keepDesiredColumn) + this.$desiredColumn = null; }; - this.moveCursorToScreen = function(row, column, preventUpdateDesiredColumn) { + this.moveCursorToScreen = function(row, column, keepDesiredColumn) { var pos = this.session.screenToDocumentPosition(row, column); - row = pos.row; - column = pos.column; - this.moveCursorTo(row, column, preventUpdateDesiredColumn); + this.moveCursorTo(pos.row, pos.column, keepDesiredColumn); }; + // remove listeners from document + this.detach = function() { + this.selectionLead.detach(); + this.selectionAnchor.detach(); + this.session = this.doc = null; + } + + this.fromOrientedRange = function(range) { + this.setSelectionRange(range, range.cursor == range.start); + this.$desiredColumn = range.desiredColumn || this.$desiredColumn; + } + + this.toOrientedRange = function(range) { + var r = this.getRange(); + if (range) { + range.start.column = r.start.column; + range.start.row = r.start.row; + range.end.column = r.end.column; + range.end.row = r.end.row; + } else { + range = r; + } + + range.cursor = this.isBackwards() ? range.start : range.end; + range.desiredColumn = this.$desiredColumn; + return range; + } + }).call(Selection.prototype); exports.Selection = Selection; @@ -7737,7 +8089,7 @@ var Range = function(startRow, startColumn, endRow, endColumn) { }; (function() { - this.isEequal = function(range) { + this.isEqual = function(range) { return this.start.row == range.start.row && this.end.row == range.end.row && this.start.column == range.start.column && @@ -7803,6 +8155,11 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } + this.intersectsRange = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + } + this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } @@ -7962,6 +8319,21 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return Range.fromPoints(start || this.start, end || this.end); }; + this.fixOrientation = function() { + if ( + this.start.row < this.end.row + || (this.start.row == this.end.row && this.start.column < this.end.column) + ) { + return false; + } + + var temp = this.start; + this.end = this.start; + this.start = temp; + return true; + }; + + this.isEmpty = function() { return (this.start.row == this.end.row && this.start.column == this.end.column); }; @@ -8275,23 +8647,30 @@ var Tokenizer = function(rules, flag) { var ruleRegExps = []; var matchTotal = 0; var mapping = this.matchMappings[key] = {}; - + for ( var i = 0; i < state.length; i++) { + + if (state[i].regex instanceof RegExp) + state[i].regex = state[i].regex.toString().slice(1, -1); + // Count number of matching groups. 2 extra groups from the full match // And the catch-all on the end (used to force a match); var matchcount = new RegExp("(?:(" + state[i].regex + ")|(.))").exec("a").length - 2; - + // Replace any backreferences and offset appropriately. var adjustedregex = state[i].regex.replace(/\\([0-9]+)/g, function (match, digit) { return "\\" + (parseInt(digit, 10) + matchTotal + 1); }); - + + if (matchcount > 1 && state[i].token.length !== matchcount-1) + throw new Error("Matching groups and length of the token array don't match in rule #" + i + " of state " + key); + mapping[matchTotal] = { rule: i, len: matchcount }; matchTotal += matchcount; - + ruleRegExps.push(adjustedregex); } @@ -8307,47 +8686,47 @@ var Tokenizer = function(rules, flag) { var mapping = this.matchMappings[currentState]; var re = this.regExps[currentState]; re.lastIndex = 0; - + var match, tokens = []; - + var lastIndex = 0; - + var token = { type: null, value: "" }; - + while (match = re.exec(line)) { var type = "text"; var rule = null; var value = [match[0]]; for (var i = 0; i < match.length-2; i++) { - if (match[i + 1] !== undefined) { - rule = state[mapping[i].rule]; - - if (mapping[i].len > 1) { - value = match.slice(i+2, i+1+mapping[i].len); - } - - // compute token type - if (typeof rule.token == "function") - type = rule.token.apply(this, value); - else - type = rule.token; + if (match[i + 1] === undefined) + continue; - var next = rule.next; - if (next && next !== currentState) { - currentState = next; - state = this.rules[currentState]; - mapping = this.matchMappings[currentState]; - lastIndex = re.lastIndex; + rule = state[mapping[i].rule]; - re = this.regExps[currentState]; - re.lastIndex = lastIndex; - } - break; + if (mapping[i].len > 1) + value = match.slice(i+2, i+1+mapping[i].len); + + // compute token type + if (typeof rule.token == "function") + type = rule.token.apply(this, value); + else + type = rule.token; + + var next = rule.next; + if (next && next !== currentState) { + currentState = next; + state = this.rules[currentState]; + mapping = this.matchMappings[currentState]; + lastIndex = re.lastIndex; + + re = this.regExps[currentState]; + re.lastIndex = lastIndex; } + break; } if (value[0]) { @@ -8356,13 +8735,15 @@ var Tokenizer = function(rules, flag) { type = [type]; } for (var i = 0; i < value.length; i++) { + if (!value[i]) + continue; + if ((!rule || rule.merge || type[i] === "text") && token.type === type[i]) { token.value += value[i]; } else { - if (token.type) { + if (token.type) tokens.push(token); - } - + token = { type: type[i], value: value[i] @@ -8370,10 +8751,10 @@ var Tokenizer = function(rules, flag) { } } } - + if (lastIndex == line.length) break; - + lastIndex = re.lastIndex; } @@ -8879,11 +9260,12 @@ var Document = function(text) { }; this.insert = function(position, text) { - if (text.length == 0) + if (!text || text.length === 0) return position; position = this.$clipPosition(position); + // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); @@ -10106,7 +10488,7 @@ function Folding() { this.foldAll = function(startRow, endRow) { var foldWidgets = this.foldWidgets; - endRow = endRow || foldWidgets.length; + endRow = endRow || this.getLength(); for (var row = startRow || 0; row < endRow; row++) { if (foldWidgets[row] == null) foldWidgets[row] = this.getFoldWidget(row); @@ -10195,7 +10577,7 @@ function Folding() { // sometimes singleline folds can be missed by the code above if (!range.isMultiLine()) { fold = this.getFoldAt(range.start.row, range.start.column, 1); - if (fold && range.isEequal(fold.range)) { + if (fold && range.isEqual(fold.range)) { this.removeFold(fold); return; } @@ -10586,7 +10968,7 @@ var Fold = exports.Fold = function(range, placeholder) { }; this.addSubFold = function(fold) { - if (this.range.isEequal(fold)) + if (this.range.isEqual(fold)) return this; if (!this.range.containsRange(fold)) @@ -11264,21 +11646,153 @@ Search.SELECTION = 2; exports.Search = Search; }); -define('ace/commands/command_manager', ['require', 'exports', 'module' , 'ace/lib/keys'], function(require, exports, module) { +define('ace/commands/command_manager', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/keyboard/hash_handler', 'ace/lib/event_emitter'], function(require, exports, module) { "use strict"; -var keyUtil = require("../lib/keys"); +var oop = require("../lib/oop"); +var HashHandler = require("../keyboard/hash_handler").HashHandler; +var EventEmitter = require("../lib/event_emitter").EventEmitter; var CommandManager = function(platform, commands) { - if (typeof platform !== "string") - throw new TypeError("'platform' argument must be either 'mac' or 'win'"); + this.platform = platform; + this.commands = {}; + this.commmandKeyBinding = {}; + + this.addCommands(commands); + + this.setDefaultHandler("exec", function(e) { + e.command.exec(e.editor, e.args || {}); + }); +}; + +oop.inherits(CommandManager, HashHandler); + +(function() { + + oop.implement(this, EventEmitter); + + this.exec = function(command, editor, args) { + if (typeof command === 'string') + command = this.commands[command]; + + if (!command) + return false; + + if (editor && editor.$readOnly && !command.readOnly) + return false; + + this._emit("exec", {editor: editor, command: command, args: args}); + return true; + }; + + this.toggleRecording = function() { + if (this.$inReplay) + return; + if (this.recording) { + this.macro.pop(); + this.removeEventListener("exec", this.$addCommandToMacro); + + if (!this.macro.length) + this.macro = this.oldMacro; + + return this.recording = false; + } + if (!this.$addCommandToMacro) { + this.$addCommandToMacro = function(e) { + this.macro.push([e.command, e.args]); + }.bind(this); + } + + this.oldMacro = this.macro; + this.macro = []; + this.on("exec", this.$addCommandToMacro); + return this.recording = true; + }; + + this.replay = function(editor) { + if (this.$inReplay || !this.macro) + return; + + if (this.recording) + return this.toggleRecording(); + + try { + this.$inReplay = true; + this.macro.forEach(function(x) { + if (typeof x == "string") + this.exec(x, editor); + else + this.exec(x[0], editor, x[1]); + }, this); + } finally { + this.$inReplay = false; + } + }; + + this.trimMacro = function(m) { + return m.map(function(x){ + if (typeof x[0] != "string") + x[0] = x[0].name; + if (!x[1]) + x = x[0]; + return x; + }); + }; + +}).call(CommandManager.prototype); + +exports.CommandManager = CommandManager; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Skywriter. + * + * The Initial Developer of the Original Code is + * Mozilla. + * Portions created by the Initial Developer are Copyright (C) 2009 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * Julian Viereck (julian.viereck@gmail.com) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/keyboard/hash_handler', ['require', 'exports', 'module' , 'ace/lib/keys'], function(require, exports, module) { +"use strict"; + +var keyUtil = require("../lib/keys"); +function HashHandler(config, platform) { this.platform = platform; this.commands = {}; this.commmandKeyBinding = {}; - if (commands) - commands.forEach(this.addCommand, this); + this.addCommands(config); }; (function() { @@ -11299,7 +11813,7 @@ var CommandManager = function(platform, commands) { command = this.commands[name]; delete this.commands[name]; - // exaustive search is brute force but since removeCommand is + // exhaustive search is brute force but since removeCommand is // not a performance critical operation this should be OK var ckb = this.commmandKeyBinding; for (var hashId in ckb) { @@ -11311,7 +11825,7 @@ var CommandManager = function(platform, commands) { }; this.addCommands = function(commands) { - Object.keys(commands).forEach(function(name) { + commands && Object.keys(commands).forEach(function(name) { var command = commands[name]; if (typeof command === "string") return this.bindKey(command, name); @@ -11357,14 +11871,14 @@ var CommandManager = function(platform, commands) { var key = typeof binding == "string" ? binding: binding[this.platform]; this.bindKey(key, command); - } + }; function parseKeys(keys, val, ret) { var key; var hashId = 0; - var parts = splitSafe(keys); + var parts = splitSafe(keys.toLowerCase()); - for (var i=0, l = parts.length; i < l; i++) { + for (var i = 0, l = parts.length; i < l; i++) { if (keyUtil.KEY_MODS[parts[i]]) hashId = hashId | keyUtil.KEY_MODS[parts[i]]; else @@ -11374,95 +11888,28 @@ var CommandManager = function(platform, commands) { return { key: key, hashId: hashId - } + }; } - function splitSafe(s, separator) { - return (s.toLowerCase() - .trim() + function splitSafe(s) { + return (s.trim() .split(new RegExp("[\\s ]*\\-[\\s ]*", "g"), 999)); } - this.findKeyCommand = function findKeyCommand(hashId, textOrKey) { - // Convert keyCode to the string representation. - if (typeof textOrKey == "number") { - textOrKey = keyUtil.keyCodeToString(textOrKey); - } - + this.findKeyCommand = function findKeyCommand(hashId, keyString) { var ckbr = this.commmandKeyBinding; - return ckbr[hashId] && ckbr[hashId][textOrKey.toLowerCase()]; + return ckbr[hashId] && ckbr[hashId][keyString.toLowerCase()]; } - this.exec = function(command, editor, args) { - if (typeof command === 'string') - command = this.commands[command]; - - if (!command) - return false; - - if (editor && editor.$readOnly && !command.readOnly) - return false; - - command.exec(editor, args || {}); - return true; - }; - - this.toggleRecording = function() { - if (this.$inReplay) - return; - if (this.recording) { - this.macro.pop(); - this.exec = this.normal_exec; - - if (!this.macro.length) - this.macro = this.oldMacro; - - return this.recording = false; - } - this.oldMacro = this.macro; - this.macro = []; - this.normal_exec = this.exec; - this.exec = function(command, editor, args) { - this.macro.push([command, args]); - return this.normal_exec(command, editor, args); + this.handleKeyboard = function(data, hashId, keyString, keyCode) { + return { + command: this.findKeyCommand(hashId, keyString) }; - return this.recording = true; }; - this.replay = function(editor) { - if (this.$inReplay || !this.macro) - return; - - if (this.recording) - return this.toggleRecording(); - - try { - this.$inReplay = true; - this.macro.forEach(function(x) { - if (typeof x == "string") - this.exec(x, editor); - else - this.exec(x[0], editor, x[1]); - }, this) - } finally { - this.$inReplay = false; - } - }; - - this.trimMacro = function(m) { - return m.map(function(x){ - if (typeof x[0] != "string") - x[0] = x[0].name; - if (!x[1]) - x = x[0]; - return x - }) - } - -}).call(CommandManager.prototype); - -exports.CommandManager = CommandManager; +}).call(HashHandler.prototype) +exports.HashHandler = HashHandler; }); /* vim:ts=4:sts=4:sw=4: * ***** BEGIN LICENSE BLOCK ***** @@ -11598,13 +12045,15 @@ exports.UndoManager = UndoManager; * * ***** END LICENSE BLOCK ***** */ -define('ace/virtual_renderer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/useragent', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'ace/lib/event_emitter', 'text!ace/css/editor.css'], function(require, exports, module) { +define('ace/virtual_renderer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/useragent', 'ace/config', 'ace/lib/net', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'ace/lib/event_emitter', 'text!ace/css/editor.css'], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var dom = require("./lib/dom"); var event = require("./lib/event"); var useragent = require("./lib/useragent"); +var config = require("./config"); +var net = require("./lib/net"); var GutterLayer = require("./layer/gutter").Gutter; var MarkerLayer = require("./layer/marker").Marker; var TextLayer = require("./layer/text").Text; @@ -11618,13 +12067,13 @@ dom.importCssString(editorCss, "ace_editor"); var VirtualRenderer = function(container, theme) { var _self = this; - + this.container = container; // TODO: this breaks rendering in Cloud9 with multiple ace instances // // Imports CSS once per DOM document ('ace_editor' serves as an identifier). // dom.importCssString(editorCss, "ace_editor", container.ownerDocument); - + dom.addCssClass(container, "ace_editor"); this.setTheme(theme); @@ -11642,8 +12091,8 @@ var VirtualRenderer = function(container, theme) { this.scroller.appendChild(this.content); this.$gutterLayer = new GutterLayer(this.$gutter); - this.$gutterLayer.on("changeGutterWidth", this.onResize.bind(this, true)); - + this.$gutterLayer.on("changeGutterWidth", this.onResize.bind(this, true)); + this.$markerBack = new MarkerLayer(this.content); var textLayer = this.$textLayer = new TextLayer(this.content); @@ -11661,6 +12110,8 @@ var VirtualRenderer = function(container, theme) { this.$horizScroll = true; this.$horizScrollAlwaysVisible = true; + this.$animatedScroll = false; + this.scrollBar = new ScrollBar(container); this.scrollBar.addEventListener("scroll", function(e) { _self.session.setScrollTop(e.data); @@ -11668,9 +12119,18 @@ var VirtualRenderer = function(container, theme) { this.scrollTop = 0; this.scrollLeft = 0; - + event.addListener(this.scroller, "scroll", function() { - _self.session.setScrollLeft(_self.scroller.scrollLeft); + var scrollLeft = _self.scroller.scrollLeft; + _self.scrollLeft = scrollLeft; + _self.session.setScrollLeft(scrollLeft); + + if (scrollLeft == 0) { + _self.$gutter.className = "ace_gutter"; + } + else { + _self.$gutter.className = "ace_gutter horscroll"; + } }); this.cursorPos = { @@ -11678,7 +12138,7 @@ var VirtualRenderer = function(container, theme) { column : 0 }; - this.$textLayer.addEventListener("changeCharaterSize", function() { + this.$textLayer.addEventListener("changeCharacterSize", function() { _self.characterWidth = textLayer.getCharacterWidth(); _self.lineHeight = textLayer.getLineHeight(); _self.$updatePrintMargin(); @@ -11731,6 +12191,7 @@ var VirtualRenderer = function(container, theme) { this.CHANGE_MARKER_BACK = 128; this.CHANGE_MARKER_FRONT = 256; this.CHANGE_FULL = 512; + this.CHANGE_H_SCROLL = 1024; oop.implement(this, EventEmitter); @@ -11829,6 +12290,14 @@ var VirtualRenderer = function(container, theme) { return this.session.adjustWrapLimit(limit); }; + this.setAnimatedScroll = function(shouldAnimate){ + this.$animatedScroll = shouldAnimate; + }; + + this.getAnimatedScroll = function() { + return this.$animatedScroll; + }; + this.setShowInvisibles = function(showInvisibles) { if (this.$textLayer.setShowInvisibles(showInvisibles)) this.$loop.schedule(this.CHANGE_TEXT); @@ -11907,7 +12376,7 @@ var VirtualRenderer = function(container, theme) { // this persists in IE9 if (useragent.isIE) return; - + if (this.layerConfig.lastRow === 0) return; @@ -11968,7 +12437,7 @@ var VirtualRenderer = function(container, theme) { }; this.$renderChanges = function(changes) { - if (!changes || !this.session) + if (!changes || !this.session || !this.container.offsetWidth) return; // text, scrolling and resize changes can cause the view port size to change @@ -11980,20 +12449,33 @@ var VirtualRenderer = function(container, theme) { ) this.$computeLayerConfig(); + // horizontal scrolling + if (changes & this.CHANGE_H_SCROLL) { + this.scroller.scrollLeft = this.scrollLeft; + + // read the value after writing it since the value might get clipped + var scrollLeft = this.scroller.scrollLeft; + this.scrollLeft = scrollLeft; + this.session.setScrollLeft(scrollLeft); + } + // full if (changes & this.CHANGE_FULL) { + this.$textLayer.checkForSizeChanges(); + // update scrollbar first to not lose scroll position when gutter calls resize + this.$updateScrollBar(); this.$textLayer.update(this.layerConfig); if (this.showGutter) this.$gutterLayer.update(this.layerConfig); this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); - this.$updateScrollBar(); return; } // scrolling if (changes & this.CHANGE_SCROLL) { + this.$updateScrollBar(); if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) this.$textLayer.update(this.layerConfig); else @@ -12004,7 +12486,6 @@ var VirtualRenderer = function(container, theme) { this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); - this.$updateScrollBar(); return; } @@ -12014,10 +12495,11 @@ var VirtualRenderer = function(container, theme) { this.$gutterLayer.update(this.layerConfig); } else if (changes & this.CHANGE_LINES) { - this.$updateLines(); - this.$updateScrollBar(); - if (this.showGutter) - this.$gutterLayer.update(this.layerConfig); + if (this.$updateLines()) { + this.$updateScrollBar(); + if (this.showGutter) + this.$gutterLayer.update(this.layerConfig); + } } else if (changes & this.CHANGE_GUTTER) { if (this.showGutter) this.$gutterLayer.update(this.layerConfig); @@ -12049,9 +12531,13 @@ var VirtualRenderer = function(container, theme) { var horizScroll = this.$horizScrollAlwaysVisible || this.$size.scrollerWidth - longestLine < 0; var horizScrollChanged = this.$horizScroll !== horizScroll; this.$horizScroll = horizScroll; - if (horizScrollChanged) + if (horizScrollChanged) { this.scroller.style.overflowX = horizScroll ? "scroll" : "hidden"; - + // when we hide scrollbar scroll event isn't emited + // leaving session with wrong scrollLeft value + if (!horizScroll) + this.session.setScrollLeft(0); + } var maxHeight = this.session.getScreenLength() * this.lineHeight; this.session.setScrollTop(Math.max(0, Math.min(this.scrollTop, maxHeight - this.$size.scrollerHeight))); @@ -12102,12 +12588,6 @@ var VirtualRenderer = function(container, theme) { this.content.style.width = longestLine + 2 * this.$padding + "px"; this.content.style.height = minHeight + "px"; - // scroller.scrollWidth was smaller than scrollLeft we needed - if (this.$desiredScrollLeft) { - this.scrollToX(this.$desiredScrollLeft); - this.$desiredScrollLeft = 0; - } - // Horizontal scrollbar visibility may have changed, which changes // the client height of the scroller if (horizScrollChanged) @@ -12138,6 +12618,7 @@ var VirtualRenderer = function(container, theme) { // else update only the changed rows this.$textLayer.updateLines(layerConfig, firstRow, lastRow); + return true; }; this.$getLongestLine = function() { @@ -12190,12 +12671,18 @@ var VirtualRenderer = function(container, theme) { this.$cursorLayer.showCursor(); }; - this.scrollCursorIntoView = function() { + this.scrollSelectionIntoView = function(anchor, lead) { + // first scroll anchor into view then scroll lead into view + this.scrollCursorIntoView(anchor); + this.scrollCursorIntoView(lead); + }; + + this.scrollCursorIntoView = function(cursor) { // the editor is not visible if (this.$size.scrollerHeight === 0) return; - var pos = this.$cursorLayer.getPixelPosition(); + var pos = this.$cursorLayer.getPixelPosition(cursor); var left = pos.left; var top = pos.top; @@ -12213,14 +12700,11 @@ var VirtualRenderer = function(container, theme) { if (scrollLeft > left) { if (left < this.$padding + 2 * this.layerConfig.characterWidth) left = 0; - this.scrollToX(left); + this.session.setScrollLeft(left); } if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { - if (left > this.layerConfig.width + 2 * this.$padding) - this.$desiredScrollLeft = left; - else - this.scrollToX(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); + this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); } }; @@ -12229,7 +12713,7 @@ var VirtualRenderer = function(container, theme) { }; this.getScrollLeft = function() { - return this.session.getScrollTop(); + return this.session.getScrollLeft(); }; this.getScrollTopRow = function() { @@ -12244,17 +12728,46 @@ var VirtualRenderer = function(container, theme) { this.session.setScrollTop(row * this.lineHeight); }; - this.scrollToLine = function(line, center) { - var lineHeight = { lineHeight: this.lineHeight }; - var offset = 0; - for (var l = 1; l < line; l++) { - offset += this.session.getRowHeight(lineHeight, l-1); - } + this.STEPS = 10; + this.$calcSteps = function(fromValue, toValue){ + var i = 0; + var l = this.STEPS; + var steps = []; + + var func = function(t, x_min, dx) { + if ((t /= .5) < 1) + return dx / 2 * Math.pow(t, 3) + x_min; + return dx / 2 * (Math.pow(t - 2, 3) + 2) + x_min; + }; + + for (i = 0; i < l; ++i) + steps.push(func(i / this.STEPS, fromValue, toValue - fromValue)); + steps.push(toValue); + + return steps; + }; - if (center) { + this.scrollToLine = function(line, center) { + var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0}); + var offset = pos.top; + if (center) offset -= this.$size.scrollerHeight / 2; + + if (this.$animatedScroll && Math.abs(offset - this.scrollTop) < 10000) { + var _self = this; + var steps = _self.$calcSteps(this.scrollTop, offset); + + clearInterval(this.$timer); + this.$timer = setInterval(function() { + _self.session.setScrollTop(steps.shift()); + + if (!steps.length) + clearInterval(_self.$timer); + }, 10); + } + else { + this.session.setScrollTop(offset); } - this.session.setScrollTop(offset); }; this.scrollToY = function(scrollTop) { @@ -12270,8 +12783,9 @@ var VirtualRenderer = function(container, theme) { if (scrollLeft <= this.$padding) scrollLeft = 0; - this.scroller.scrollLeft = scrollLeft; - scrollLeft = this.scroller.scrollLeft; + if (this.scrollLeft !== scrollLeft) + this.scrollLeft = scrollLeft; + this.$loop.schedule(this.CHANGE_H_SCROLL); }; this.scrollBy = function(deltaX, deltaY) { @@ -12287,16 +12801,27 @@ var VirtualRenderer = function(container, theme) { // todo: handle horizontal scrolling }; + this.pixelToScreenCoordinates = function(pageX, pageY) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var col = Math.round( + (pageX + this.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft()) / this.characterWidth + ); + var row = Math.floor( + (pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop()) / this.lineHeight + ); + + return {row: row, column: col}; + }; + this.screenToTextCoordinates = function(pageX, pageY) { var canvasPos = this.scroller.getBoundingClientRect(); var col = Math.round( - (pageX + this.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft()) - / this.characterWidth + (pageX + this.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft()) / this.characterWidth ); var row = Math.floor( - (pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop()) - / this.lineHeight + (pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop()) / this.lineHeight ); return this.session.screenToDocumentPosition(row, Math.max(col, 0)); @@ -12356,14 +12881,36 @@ var VirtualRenderer = function(container, theme) { style.left = "-10000px"; }; + this._loadTheme = function(name, callback) { + if (!config.get("packaged")) + return callback(); + + var base = name.split("/").pop(); + var filename = config.get("themePath") + "/theme-" + base + config.get("suffix"); + net.loadScript(filename, callback); + }; + this.setTheme = function(theme) { var _self = this; this.$themeValue = theme; if (!theme || typeof theme == "string") { - theme = theme || "ace/theme/textmate"; - require([theme], function(theme) { - afterLoad(theme); + var moduleName = theme || "ace/theme/textmate"; + + var module; + try { + module = require(moduleName); + } catch (e) {}; + if (module) + return afterLoad(module); + + _self._loadTheme(moduleName, function() { + require([moduleName], function(module) { + if (_self.$themeValue !== theme) + return; + + afterLoad(module); + }); }); } else { afterLoad(theme); @@ -12492,11 +13039,11 @@ var Gutter = function(parentEl) { this.addGutterDecoration = function(row, className){ if (!this.$decorations[row]) this.$decorations[row] = ""; - this.$decorations[row] += " ace_" + className; + this.$decorations[row] += " " + className; }; this.removeGutterDecoration = function(row, className){ - this.$decorations[row] = this.$decorations[row].replace(" ace_" + className, ""); + this.$decorations[row] = this.$decorations[row].replace(" " + className, ""); }; this.setBreakpoints = function(rows) { @@ -12723,7 +13270,7 @@ var Marker = function(parentEl) { }; /** - * Draws a marker, which spans a range of text in a single line + * Draws a marker, which spans a range of text on multiple lines */ this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig) { // selection start @@ -12798,7 +13345,7 @@ var Marker = function(parentEl) { }; /** - * Draws a marker which covers one single full line + * Draws a marker which covers part or whole width of a single screen line */ this.drawSingleLineMarker = function(stringBuilder, range, clazz, layerConfig, extraLength, type) { var padding = type === "background" ? 0 : this.$padding; @@ -12914,7 +13461,7 @@ var Text = function(parentEl) { var size = this.$measureSizes(); if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { this.$characterSize = size; - this._emit("changeCharaterSize", {data: size}); + this._emit("changeCharacterSize", {data: size}); } }; @@ -12933,7 +13480,7 @@ var Text = function(parentEl) { lineHeight : 1 }; - this.$measureSizes = function() { + this.$measureSizes = useragent.isIE || useragent.isOldGecko ? function() { var n = 1000; if (!this.$measureNode) { var measureNode = this.$measureNode = dom.createElement("div"); @@ -12943,7 +13490,7 @@ var Text = function(parentEl) { style.left = style.top = (-n * 40) + "px"; style.visibility = "hidden"; - style.position = "absolute"; + style.position = "fixed"; style.overflow = "visible"; style.whiteSpace = "nowrap"; @@ -12960,8 +13507,12 @@ var Text = function(parentEl) { container = container.parentNode; container.appendChild(measureNode); } - } + + // Size and width can be null if the editor is not visible or + // detached from the document + if (!this.element.offsetWidth) + return null; var style = this.$measureNode.style; var computedStyle = dom.computedStyle(this.element); @@ -12975,7 +13526,46 @@ var Text = function(parentEl) { // Size and width can be null if the editor is not visible or // detached from the document - if (size.width == 0 && size.height == 0) + if (size.width == 0 || size.height == 0) + return null; + + return size; + } + : function() { + if (!this.$measureNode) { + var measureNode = this.$measureNode = dom.createElement("div"); + var style = measureNode.style; + + style.width = style.height = "auto"; + style.left = style.top = -100 + "px"; + + style.visibility = "hidden"; + style.position = "fixed"; + style.overflow = "visible"; + style.whiteSpace = "nowrap"; + + measureNode.innerHTML = "X"; + + var container = this.element.parentNode; + while (container && !dom.hasCssClass(container, "ace_editor")) + container = container.parentNode; + + if (!container) + return this.$measureNode = null; + + container.appendChild(measureNode); + } + + var rect = this.$measureNode.getBoundingClientRect(); + + var size = { + height: rect.height, + width: rect.width + }; + + // Size and width can be null if the editor is not visible or + // detached from the document + if (size.width == 0 || size.height == 0) return null; return size; @@ -13089,16 +13679,16 @@ var Text = function(parentEl) { }; this.$renderLinesFragment = function(config, firstRow, lastRow) { - var fragment = this.element.ownerDocument.createDocumentFragment(), - row = firstRow, - fold = this.session.getNextFoldLine(row), - foldStart = fold ?fold.start.row :Infinity; + var fragment = this.element.ownerDocument.createDocumentFragment(); + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; while (true) { if (row > foldStart) { - row = fold.end.row+1; - fold = this.session.getNextFoldLine(row, fold); - foldStart = fold ?fold.start.row :Infinity; + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; } if (row > lastRow) break; @@ -13137,15 +13727,15 @@ var Text = function(parentEl) { var html = []; var firstRow = config.firstRow, lastRow = config.lastRow; - var row = firstRow, - fold = this.session.getNextFoldLine(row), - foldStart = fold ?fold.start.row :Infinity; + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; while (true) { if (row > foldStart) { - row = fold.end.row+1; - fold = this.session.getNextFoldLine(row, fold); - foldStart = fold ?fold.start.row :Infinity; + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; } if (row > lastRow) break; @@ -13446,11 +14036,10 @@ var Cursor = function(parentEl) { this.element.className = "ace_layer ace_cursor-layer"; parentEl.appendChild(this.element); - this.cursor = dom.createElement("div"); - this.cursor.className = "ace_cursor ace_hidden"; - this.element.appendChild(this.cursor); - this.isVisible = false; + + this.cursors = []; + this.cursor = this.addCursor(); }; (function() { @@ -13464,35 +14053,59 @@ var Cursor = function(parentEl) { this.session = session; }; + this.addCursor = function() { + var el = dom.createElement("div"); + var className = "ace_cursor"; + if (!this.isVisible) + className += " ace_hidden"; + if (this.overwrite) + className += " ace_overwrite"; + + el.className = className; + this.element.appendChild(el); + this.cursors.push(el); + return el; + }; + + this.removeCursor = function() { + if (this.cursors.length > 1) { + var el = this.cursors.pop(); + el.parentNode.removeChild(el); + return el; + } + }; + this.hideCursor = function() { this.isVisible = false; - dom.addCssClass(this.cursor, "ace_hidden"); + for (var i = this.cursors.length; i--; ) + dom.addCssClass(this.cursors[i], "ace_hidden"); clearInterval(this.blinkId); }; this.showCursor = function() { this.isVisible = true; - dom.removeCssClass(this.cursor, "ace_hidden"); - this.cursor.style.visibility = "visible"; + for (var i = this.cursors.length; i--; ) + dom.removeCssClass(this.cursors[i], "ace_hidden"); + + this.element.style.visibility = ""; this.restartTimer(); }; this.restartTimer = function() { clearInterval(this.blinkId); - if (!this.isVisible) { + if (!this.isVisible) return; - } - var cursor = this.cursor; + var element = this.element; this.blinkId = setInterval(function() { - cursor.style.visibility = "hidden"; + element.style.visibility = "hidden"; setTimeout(function() { - cursor.style.visibility = "visible"; + element.style.visibility = "visible"; }, 400); }, 1000); }; - this.getPixelPosition = function(onScreen) { + this.getPixelPosition = function(position, onScreen) { if (!this.config || !this.session) { return { left : 0, @@ -13500,7 +14113,8 @@ var Cursor = function(parentEl) { }; } - var position = this.session.selection.getCursor(); + if (!position) + position = this.session.selection.getCursor(); var pos = this.session.documentToScreenPosition(position); var cursorLeft = Math.round(this.$padding + pos.column * this.config.characterWidth); @@ -13516,25 +14130,53 @@ var Cursor = function(parentEl) { this.update = function(config) { this.config = config; - this.pixelPos = this.getPixelPosition(true); + if (this.session.selectionMarkerCount > 1) { + var selections = this.session.$selectionMarkers; + var i = 0, sel, cursorIndex = 0; - this.cursor.style.left = this.pixelPos.left + "px"; - this.cursor.style.top = this.pixelPos.top + "px"; - this.cursor.style.width = config.characterWidth + "px"; - this.cursor.style.height = config.lineHeight + "px"; + for (var i = selections.length; i--; ) { + sel = selections[i]; + var pixelPos = this.getPixelPosition(sel.cursor, true); - var overwrite = this.session.getOverwrite() - if (overwrite != this.overwrite) { - this.overwrite = overwrite; - if (overwrite) - dom.addCssClass(this.cursor, "ace_overwrite"); - else - dom.removeCssClass(this.cursor, "ace_overwrite"); + var style = (this.cursors[cursorIndex++] || this.addCursor()).style; + + style.left = pixelPos.left + "px"; + style.top = pixelPos.top + "px"; + style.width = config.characterWidth + "px"; + style.height = config.lineHeight + "px"; + } + if (cursorIndex > 1) + while (this.cursors.length > cursorIndex) + this.removeCursor(); + } else { + var pixelPos = this.getPixelPosition(null, true); + var style = this.cursor.style; + style.left = pixelPos.left + "px"; + style.top = pixelPos.top + "px"; + style.width = config.characterWidth + "px"; + style.height = config.lineHeight + "px"; + + while (this.cursors.length > 1) + this.removeCursor(); } + var overwrite = this.session.getOverwrite(); + if (overwrite != this.overwrite) + this.$setOverite(overwrite); + this.restartTimer(); }; + this.$setOverite = function(overwrite) { + this.overwrite = overwrite; + for (var i = this.cursors.length; i--; ) { + if (overwrite) + dom.addCssClass(this.cursors[i], "ace_overwrite"); + else + dom.removeCssClass(this.cursors[i], "ace_overwrite"); + } + }; + this.destroy = function() { clearInterval(this.blinkId); } @@ -13629,6 +14271,8 @@ var ScrollBar = function(parent) { this.inner.style.height = height + "px"; }; + // TODO: on chrome 17+ after for small zoom levels after this function + // this.element.scrollTop != scrollTop which makes page to scroll up. this.setScrollTop = function(scrollTop) { this.element.scrollTop = scrollTop; }; @@ -13712,12 +14356,11 @@ var RenderLoop = function(onRender, win) { exports.RenderLoop = RenderLoop; }); define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?family=Droid+Sans+Mono);\n" + - "\n" + "\n" + ".ace_editor {\n" + " position: absolute;\n" + " overflow: hidden;\n" + - " font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Courier New', monospace;\n" + + " font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Consolas', monospace;\n" + " font-size: 12px;\n" + "}\n" + "\n" + @@ -13735,12 +14378,6 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa " cursor: text;\n" + "}\n" + "\n" + - "/* setting pointer-events: auto; on node under the mouse, which changes during scroll,\n" + - " will break mouse wheel scrolling in Safari */\n" + - ".ace_content * {\n" + - " pointer-events: none;\n" + - "}\n" + - "\n" + ".ace_composition {\n" + " position: absolute;\n" + " background: #555;\n" + @@ -13748,18 +14385,17 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa " z-index: 4;\n" + "}\n" + "\n" + - ".ace_gutter .ace_layer {\n" + - " position: relative;\n" + - " min-width: 54px;\n" + - " text-align: right;\n" + - "}\n" + - "\n" + ".ace_gutter {\n" + " position: absolute;\n" + " overflow : hidden;\n" + " height: 100%;\n" + " width: auto;\n" + " cursor: default;\n" + + " z-index: 1000;\n" + + "}\n" + + "\n" + + ".ace_gutter.horscroll {\n" + + " box-shadow: 0px 0px 20px rgba(0,0,0,0.4);\n" + "}\n" + "\n" + ".ace_gutter-cell {\n" + @@ -13838,6 +14474,16 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + + " /* setting pointer-events: auto; on node under the mouse, which changes\n" + + " during scroll, will break mouse wheel scrolling in Safari */\n" + + " pointer-events: none;\n" + + "}\n" + + "\n" + + ".ace_gutter .ace_layer {\n" + + " position: relative;\n" + + " min-width: 40px;\n" + + " text-align: right;\n" + + " pointer-events: auto;\n" + "}\n" + "\n" + ".ace_text-layer {\n" + @@ -13873,12 +14519,12 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa "\n" + ".ace_marker-layer .ace_selection {\n" + " position: absolute;\n" + - " z-index: 4;\n" + + " z-index: 5;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_bracket {\n" + " position: absolute;\n" + - " z-index: 5;\n" + + " z-index: 6;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_active_line {\n" + @@ -13886,9 +14532,13 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa " z-index: 2;\n" + "}\n" + "\n" + + ".ace_gutter .ace_gutter_active_line{\n" + + " background-color : #dcdcdc;\n" + + "}\n" + + "\n" + ".ace_marker-layer .ace_selected_word {\n" + " position: absolute;\n" + - " z-index: 6;\n" + + " z-index: 4;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + @@ -13935,7 +14585,7 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa " cursor: move;\n" + "}\n" + "\n" + - ".ace_folding-enabled .ace_gutter-cell {\n" + + ".ace_folding-enabled > .ace_gutter-cell {\n" + " padding-right: 13px;\n" + "}\n" + "\n" + @@ -13994,7 +14644,8 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa "}\n" + ""); -/* ***** BEGIN LICENSE BLOCK ***** +/* vim:ts=4:sts=4:sw=4: + * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version @@ -14015,7 +14666,7 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa * the Initial Developer. All Rights Reserved. * * Contributor(s): - * Fabian Jakobs + * Harutyun Amirjanyan * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or @@ -14031,52 +14682,1811 @@ define("text!ace/css/editor.css", [], "@import url(//fonts.googleapis.com/css?fa * * ***** END LICENSE BLOCK ***** */ -define('ace/theme/textmate', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { -"use strict"; +define('ace/multi_select', ['require', 'exports', 'module' , 'ace/range_list', 'ace/range', 'ace/selection', 'ace/mouse/multi_select_handler', 'ace/commands/multi_select_commands', 'ace/search', 'ace/edit_session', 'ace/editor'], function(require, exports, module) { -exports.isDark = false; -exports.cssClass = "ace-tm"; -exports.cssText = ".ace-tm .ace_editor {\ - border: 2px solid rgb(159, 159, 159);\ -}\ -\ -.ace-tm .ace_editor.ace_focus {\ - border: 2px solid #327fbd;\ -}\ -\ -.ace-tm .ace_gutter {\ - background: #e8e8e8;\ - color: #333;\ -}\ -\ -.ace-tm .ace_print_margin {\ - width: 1px;\ - background: #e8e8e8;\ -}\ -\ -.ace-tm .ace_fold {\ - background-color: #0000A2;\ -}\ -\ -.ace-tm .ace_text-layer {\ - cursor: text;\ -}\ -\ -.ace-tm .ace_cursor {\ - border-left: 2px solid black;\ -}\ -\ -.ace-tm .ace_cursor.ace_overwrite {\ - border-left: 0px;\ - border-bottom: 1px solid black;\ -}\ - \ -.ace-tm .ace_line .ace_invisible {\ - color: rgb(191, 191, 191);\ -}\ -\ -.ace-tm .ace_line .ace_keyword {\ - color: blue;\ +var RangeList = require("./range_list").RangeList; +var Range = require("./range").Range; +var Selection = require("./selection").Selection; +var onMouseDown = require("./mouse/multi_select_handler").onMouseDown; +exports.commands = require("./commands/multi_select_commands"); + +// Todo: session.find or editor.findVolatile that returns range +var Search = require("./search").Search; +var search = new Search(); + +function find(session, needle, dir) { + search.$options.wrap = true; + search.$options.needle = needle; + search.$options.backwards = dir == -1; + return search.find(session); +} + +// extend EditSession +var EditSession = require("./edit_session").EditSession; +(function() { + this.getSelectionMarkers = function() { + return this.$selectionMarkers; + }; +}).call(EditSession.prototype); + +// extend Selection +(function() { + // list of ranges in reverse addition order + this.ranges = null; + + // automatically sorted list of ranges + this.rangeList = null; + + /** + * Selection.addRange(Range) -> Void + * + * adds a range to selection entering multiselect mode if necessary + **/ + this.addRange = function(range) { + if (!this.inMultiSelectMode && this.rangeCount == 0) { + var oldRange = this.toOrientedRange(); + if (!range || !range.isEqual(oldRange)) { + this.rangeList.add(oldRange); + this.$onAddRange(oldRange); + } + } + + if (!range) + return; + + if (!range.cursor) + range.cursor = range.end; + + var removed = this.rangeList.add(range); + + this.$onAddRange(range); + + if (removed.length) + this.$onRemoveRange(removed); + + if (this.rangeCount > 0 && !this.inMultiSelectMode) { + this._emit("multiSelect"); + this.inMultiSelectMode = true; + this.session.$undoSelect = false; + this.rangeList.attach(this.session); + } + }; + + this.toSingleRange = function(range) { + range = range || this.ranges[0]; + var removed = this.rangeList.removeAll(); + if (removed.length) + this.$onRemoveRange(removed); + + range && this.fromOrientedRange(range); + }; + + /** + * Selection.addRange(pos) -> Range + * pos: {row, column} + * + * removes range containing pos (if exists) + **/ + this.substractPoint = function(pos) { + var removed = this.rangeList.substractPoint(pos); + if (removed) { + this.$onRemoveRange(removed); + return removed[0]; + } + }; + + /** + * Selection.mergeOverlappingRanges() -> Void + * + * merges overlapping ranges ensuring consistency after changes + **/ + this.mergeOverlappingRanges = function() { + var removed = this.rangeList.merge(); + if (removed.length) + this.$onRemoveRange(removed); + else if(this.ranges[0]) + this.fromOrientedRange(this.ranges[0]); + }; + + this.$onAddRange = function(range) { + this.rangeCount = this.rangeList.ranges.length; + this.ranges.unshift(range); + this.fromOrientedRange(range); + this._emit("addRange", {range: range}); + }; + + this.$onRemoveRange = function(removed) { + this.rangeCount = this.rangeList.ranges.length; + if (this.rangeCount == 1 && this.inMultiSelectMode) { + var lastRange = this.rangeList.ranges.pop(); + removed.push(lastRange); + this.rangeCount = 0; + } + + for (var i = removed.length; i--; ) { + var index = this.ranges.indexOf(removed[i]); + this.ranges.splice(index, 1); + } + + this._emit("removeRange", {ranges: removed}); + + if (this.rangeCount == 0 && this.inMultiSelectMode) { + this.inMultiSelectMode = false; + this._emit("singleSelect"); + this.session.$undoSelect = true; + this.rangeList.detach(this.session); + } + + lastRange = lastRange || this.ranges[0]; + if (lastRange && !lastRange.isEqual(this.getRange())) + this.fromOrientedRange(lastRange); + }; + + // adds multicursor support to selection + this.$initRangeList = function() { + if (this.rangeList) + return; + + this.rangeList = new RangeList(); + this.ranges = []; + this.rangeCount = 0; + }; + + this.getAllRanges = function() { + return this.rangeList.ranges.concat(); + }; + + this.splitIntoLines = function () { + if (this.rangeCount > 1) { + var ranges = this.rangeList.ranges; + var lastRange = ranges[ranges.length - 1]; + var range = Range.fromPoints(ranges[0].start, lastRange.end); + + this.toSingleRange(); + this.setSelectionRange(range, lastRange.cursor == lastRange.start); + } else { + var cursor = this.session.documentToScreenPosition(this.selectionLead); + var anchor = this.session.documentToScreenPosition(this.selectionAnchor); + + var rectSel = this.rectangularRangeBlock(cursor, anchor); + rectSel.forEach(this.addRange, this); + } + }; + + /** + * Selection.rectangularRangeBlock(screenCursor, screenAnchor, includeEmptyLines) -> [Range] + * gets list of ranges composing rectangular block on the screen + * @includeEmptyLines if true includes ranges inside the block which + * are empty becuase of the clipping + */ + this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) { + var rectSel = []; + + var xBackwards = screenCursor.column < screenAnchor.column; + if (xBackwards) { + var startColumn = screenCursor.column; + var endColumn = screenAnchor.column; + } else { + var startColumn = screenAnchor.column; + var endColumn = screenCursor.column; + } + + var yBackwards = screenCursor.row < screenAnchor.row; + if (yBackwards) { + var startRow = screenCursor.row; + var endRow = screenAnchor.row; + } else { + var startRow = screenAnchor.row; + var endRow = screenCursor.row; + } + + if (startColumn < 0) + startColumn = 0; + if (startRow < 0) + startRow = 0; + + if (startRow == endRow) + includeEmptyLines = true; + + for (var row = startRow; row <= endRow; row++) { + var range = Range.fromPoints( + this.session.screenToDocumentPosition(row, startColumn), + this.session.screenToDocumentPosition(row, endColumn) + ); + if (range.isEmpty()) { + if (docEnd && isSamePoint(range.end, docEnd)) + break; + var docEnd = range.end; + } + range.cursor = xBackwards ? range.start : range.end; + rectSel.push(range); + } + + if (yBackwards) + rectSel.reverse(); + + if (!includeEmptyLines) { + var end = rectSel.length - 1; + while (rectSel[end].isEmpty() && end > 0) + end--; + if (end > 0) { + var start = 0; + while (rectSel[start].isEmpty()) + start++; + } + for (var i = end; i >= start; i--) { + if (rectSel[i].isEmpty()) + rectSel.splice(i, 1); + } + } + + return rectSel; + }; +}).call(Selection.prototype); + +// extend Editor +var Editor = require("./editor").Editor; +(function() { + /** + * Editor.updateSelectionMarkers() -> Void + * + * updates cursor and marker layers + **/ + this.updateSelectionMarkers = function() { + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + /** + * Editor.addSelectionMarker(orientedRange) -> Range + * - orientedRange: range with cursor + * + * adds selection and cursor + **/ + this.addSelectionMarker = function(orientedRange) { + if (!orientedRange.cursor) + orientedRange.cursor = orientedRange.end; + + var style = this.getSelectionStyle(); + orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style); + + this.session.$selectionMarkers.push(orientedRange); + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + return orientedRange; + }; + + this.removeSelectionMarkers = function(ranges) { + for (var i = ranges.length; i--; ) { + var range = ranges[i]; + if (!range.marker) + continue; + this.session.removeMarker(range.marker); + var index = this.session.$selectionMarkers.indexOf(range); + if (index != -1) + this.session.$selectionMarkers.splice(index, 1); + } + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + }; + + this.$onAddRange = function(e) { + this.addSelectionMarker(e.range); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onRemoveRange = function(e) { + this.removeSelectionMarkers(e.ranges); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onMultiSelect = function(e) { + if (this.inMultiSelectMode) + return; + this.inMultiSelectMode = true; + + this.setStyle("multiselect"); + this.keyBinding.addKeyboardHandler(exports.commands.keyboardHandler); + this.commands.on("exec", this.$onMultiSelectExec); + + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onSingleSelect = function(e) { + if (this.session.multiSelect.inVirtualMode) + return; + this.inMultiSelectMode = false; + + this.unsetStyle("multiselect"); + this.keyBinding.removeKeyboardHandler(exports.commands.keyboardHandler); + + this.commands.removeEventListener("exec", this.$onMultiSelectExec); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onMultiSelectExec = function(e) { + var command = e.command; + var editor = e.editor; + if (!command.multiSelectAction) { + command.exec(editor, e.args || {}); + editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); + editor.multiSelect.mergeOverlappingRanges(); + } else if (command.multiSelectAction == "forEach") { + editor.forEachSelection(command, e.args); + } else if (command.multiSelectAction == "single") { + editor.exitMultiSelectMode(); + command.exec(editor, e.args || {}); + } else { + command.multiSelectAction(editor, e.args || {}); + } + e.preventDefault(); + }; + + /** + * Editor.forEachSelection(cmd, args) -> Void + * - cmd: command to execute + * - args: arguments to the command + * + * executes command for each selection range + **/ + this.forEachSelection = function(cmd, args) { + if (this.inVirtualSelectionMode) + return; + + var session = this.session; + var selection = this.selection; + var rangeList = selection.rangeList; + + var reg = selection._eventRegistry; + selection._eventRegistry = {}; + + var tmpSel = new Selection(session); + this.inVirtualSelectionMode = true; + for (var i = rangeList.ranges.length; i--;) { + tmpSel.fromOrientedRange(rangeList.ranges[i]); + this.selection = session.selection = tmpSel; + cmd.exec(this, args || {}); + tmpSel.toOrientedRange(rangeList.ranges[i]); + } + tmpSel.detach(); + + this.selection = session.selection = selection; + this.inVirtualSelectionMode = false; + selection._eventRegistry = reg; + selection.mergeOverlappingRanges(); + + this.onCursorChange(); + this.onSelectionChange(); + }; + + /** + * Editor.exitMultiSelectMode() -> Void + * + * removes all selections except the last added one. + **/ + this.exitMultiSelectMode = function() { + if (this.inVirtualSelectionMode) + return; + this.multiSelect.toSingleRange(); + }; + + this.getCopyText = function() { + var text = ""; + if (this.inMultiSelectMode) { + var ranges = this.multiSelect.rangeList.ranges; + text = []; + for (var i = 0; i < ranges.length; i++) { + text.push(this.session.getTextRange(ranges[i])); + } + text = text.join(this.session.getDocument().getNewLineCharacter()); + } else if (!this.selection.isEmpty()) { + text = this.session.getTextRange(this.getSelectionRange()); + } + + return text; + }; + + + // commands + /** + * Editor.selectMoreLines(dir, skip) -> Void + * - dir: -1 up, 1 down + * - skip: remove active selection range if true + * + * adds cursor above or bellow active cursor + **/ + this.selectMoreLines = function(dir, skip) { + var range = this.selection.toOrientedRange(); + var isBackwards = range.cursor == range.end; + + var screenLead = this.session.documentToScreenPosition(range.cursor); + if (this.selection.$desiredColumn) + screenLead.column = this.selection.$desiredColumn; + + var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column); + + if (!range.isEmpty()) { + var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start); + var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column); + } else { + var anchor = lead; + } + + if (isBackwards) { + var newRange = Range.fromPoints(lead, anchor); + newRange.cursor = newRange.start; + } else { + var newRange = Range.fromPoints(anchor, lead); + newRange.cursor = newRange.end; + } + + newRange.desiredColumn = screenLead.column; + if (!this.selection.inMultiSelectMode) { + this.selection.addRange(range); + } else { + if (skip) + var toRemove = range.cursor; + } + + this.selection.addRange(newRange); + if (toRemove) + this.selection.substractPoint(toRemove); + }; + + /** + * Editor.transposeSelections(dir) -> Void + * - dir: direction to rotate selections + * + * contents + * empty ranges are expanded to word + **/ + this.transposeSelections = function(dir) { + var session = this.session; + var sel = session.multiSelect; + var all = sel.ranges; + + for (var i = all.length; i--; ) { + var range = all[i]; + if (range.isEmpty()) { + var tmp = session.getWordRange(range.start.row, range.start.column); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + range.end.row = tmp.end.row; + range.end.column = tmp.end.column; + } + } + sel.mergeOverlappingRanges(); + + var words = []; + for (var i = all.length; i--; ) { + var range = all[i]; + words.unshift(session.getTextRange(range)); + } + + if (dir < 0) + words.unshift(words.pop()); + else + words.push(words.shift()); + + for (var i = all.length; i--; ) { + var range = all[i]; + var tmp = range.clone(); + session.replace(range, words[i]); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + } + } + + /** + * Editor.selectMore(dir, skip) -> Void + * - dir: 1 next, -1 previous + * - skip: remove active selection range if true + * + * finds next occurence of text in active selection + * and adds it to the selections + **/ + this.selectMore = function (dir, skip) { + var session = this.session; + var sel = session.multiSelect; + + var range = sel.toOrientedRange(); + if (range.isEmpty()) { + var range = session.getWordRange(range.start.row, range.start.column); + range.cursor = range.end; + this.multiSelect.addRange(range); + } + var needle = session.getTextRange(range); + + var newRange = find(session, needle, dir); + if (newRange) { + newRange.cursor = dir == -1 ? newRange.start : newRange.end; + this.multiSelect.addRange(newRange); + } + if (skip) + this.multiSelect.substractPoint(range.cursor); + }; +}).call(Editor.prototype); + + +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} + +// patch +// adds multicursor support to a session +exports.onSessionChange = function(e) { + var session = e.session; + if (!session.multiSelect) { + session.$selectionMarkers = []; + session.selection.$initRangeList(); + session.multiSelect = session.selection; + } + this.multiSelect = session.multiSelect; + + var oldSession = e.oldSession; + if (oldSession) { + // todo use events + if (oldSession.multiSelect && oldSession.multiSelect.editor == this) + oldSession.multiSelect.editor = null; + + session.multiSelect.removeEventListener("addRange", this.$onAddRange); + session.multiSelect.removeEventListener("removeRange", this.$onRemoveRange); + session.multiSelect.removeEventListener("multiSelect", this.$onMultiSelect); + session.multiSelect.removeEventListener("singleSelect", this.$onSingleSelect); + } + + session.multiSelect.on("addRange", this.$onAddRange); + session.multiSelect.on("removeRange", this.$onRemoveRange); + session.multiSelect.on("multiSelect", this.$onMultiSelect); + session.multiSelect.on("singleSelect", this.$onSingleSelect); + + // this.$onSelectionChange = this.onSelectionChange.bind(this); + + if (this.inMultiSelectMode != session.selection.inMultiSelectMode) { + if (session.selection.inMultiSelectMode) + this.$onMultiSelect(); + else + this.$onSingleSelect(); + } +}; + +/** + * MultiSelect(editor) -> Void + * + * adds multiple selection support to the editor + * (note: should be called only once for each editor instance) + **/ +function MultiSelect(editor) { + editor.$onAddRange = editor.$onAddRange.bind(editor); + editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); + editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); + editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); + + exports.onSessionChange.call(editor, editor); + editor.on("changeSession", exports.onSessionChange.bind(editor)); + + editor.on("mousedown", onMouseDown); + editor.commands.addCommands(exports.commands.defaultCommands); +} + +exports.MultiSelect = MultiSelect; + +});/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Harutyun Amirjanyan + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/range_list', ['require', 'exports', 'module' ], function(require, exports, module) { +"use strict"; + + +var RangeList = function() { + this.ranges = []; +}; + +(function() { + this.comparePoints = function(p1, p2) { + return p1.row - p2.row || p1.column - p2.column; + }; + + this.pointIndex = function(pos, startIndex) { + var list = this.ranges; + + for (var i = startIndex || 0; i < list.length; i++) { + var range = list[i]; + var cmp = this.comparePoints(pos, range.end); + + if (cmp > 0) + continue; + if (cmp == 0) + return i; + cmp = this.comparePoints(pos, range.start); + if (cmp >= 0) + return i; + + return -i-1; + } + return -i - 1; + }; + + this.add = function(range) { + var startIndex = this.pointIndex(range.start); + if (startIndex < 0) + startIndex = -startIndex - 1; + + var endIndex = this.pointIndex(range.end, startIndex); + + if (endIndex < 0) + endIndex = -endIndex - 1; + else + endIndex++; + + return this.ranges.splice(startIndex, endIndex - startIndex, range); + }; + + this.addList = function(list) { + var removed = []; + for (var i = list.length; i--; ) { + removed.push.call(removed, this.add(list[i])); + } + return removed; + }; + + this.substractPoint = function(pos) { + var i = this.pointIndex(pos); + + if (i >= 0) + return this.ranges.splice(i, 1); + }; + + // merge overlapping ranges + this.merge = function() { + var removed = []; + var list = this.ranges; + var next = list[0], range; + for (var i = 1; i < list.length; i++) { + range = next; + next = list[i]; + var cmp = this.comparePoints(range.end, next.start); + if (cmp < 0) + continue; + + if (cmp == 0 && !(range.isEmpty() || next.isEmpty())) + continue; + + if (this.comparePoints(range.end, next.end) < 0) { + range.end.row = next.end.row; + range.end.column = next.end.column; + } + + list.splice(i, 1); + removed.push(next); + next = range; + i--; + } + + return removed; + }; + + this.contains = function(row, column) { + return this.pointIndex({row: row, column: column}) >= 0; + }; + + this.containsPoint = function(pos) { + return this.pointIndex(pos) >= 0; + }; + + this.rangeAtPoint = function(pos) { + var i = this.pointIndex(pos); + if (i >= 0) + return this.ranges[i]; + }; + + + this.clipRows = function(startRow, endRow) { + var list = this.ranges; + if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow) + return []; + + var startIndex = this.pointIndex({row: startRow, column: 0}); + if (startIndex < 0) + startIndex = -startIndex - 1; + var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex); + if (endIndex < 0) + endIndex = -endIndex - 1; + + var clipped = []; + for (var i = startIndex; i < endIndex; i++) { + clipped.push(list[i]); + } + return clipped; + }; + + this.removeAll = function() { + return this.ranges.splice(0, this.ranges.length); + }; + + this.attach = function(session) { + if (this.session) + this.detach(); + + this.session = session; + this.onChange = this.$onChange.bind(this); + + this.session.on('change', this.onChange); + }; + + this.detach = function() { + if (!this.session) + return; + this.session.removeListener('change', this.onChange); + this.session = null; + }; + + this.$onChange = function(e) { + var changeRange = e.data.range; + if (e.data.action[0] == "i"){ + var start = changeRange.start; + var end = changeRange.end; + } else { + var end = changeRange.start; + var start = changeRange.end; + } + var startRow = start.row; + var endRow = end.row; + var lineDif = endRow - startRow; + + var colDiff = -start.column + end.column; + + var ranges = this.ranges; + + for (var i=0, n = ranges.length; i < n; i++) { + var r = ranges[i]; + if (r.end.row < startRow) + continue; + if (r.start.row > startRow) + break; + + if (r.start.row == startRow && r.start.column >= start.column ) { + r.start.column += colDiff; + r.start.row += lineDif; + } + if (r.end.row == startRow && r.end.column >= start.column) { + r.end.column += colDiff; + r.end.row += lineDif; + } + } + + if (lineDif != 0 && i < n) { + for (; i < n; i++) { + var r = ranges[i]; + r.start.row += lineDif; + r.end.row += lineDif; + } + } + }; + +}).call(RangeList.prototype); + +exports.RangeList = RangeList; +}); +/* vim:ts=4:sts=4:sw=4: + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Harutyun Amirjanyan + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mouse/multi_select_handler', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { + +var event = require("../lib/event"); + + +// mouse +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} + +function onMouseDown(e) { + var ev = e.domEvent; + var alt = ev.altKey; + var shift = ev.shiftKey; + var ctrl = e.getAccelKey(); + var button = e.getButton(); + + if (!ctrl && !alt) { + if (e.editor.inMultiSelectMode) { + if (button == 0) { + e.editor.exitMultiSelectMode(); + } else if (button == 2) { + var editor = e.editor; + var selectionEmpty = editor.selection.isEmpty(); + editor.textInput.onContextMenu({x: e.clientX, y: e.clientY}, selectionEmpty); + event.capture(editor.container, function(){}, editor.textInput.onContextMenuClose); + e.stop(); + } + } + return; + } + + var editor = e.editor; + var selection = editor.selection; + var isMultiSelect = editor.inMultiSelectMode; + var pos = e.getDocumentPosition(); + var cursor = selection.getCursor(); + var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor)); + + + var mouseX = e.pageX, mouseY = e.pageY; + var onMouseSelection = function(e) { + mouseX = event.getDocumentX(e); + mouseY = event.getDocumentY(e); + }; + + var blockSelect = function() { + var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column); + + if (isSamePoint(screenCursor, newCursor) + && isSamePoint(cursor, selection.selectionLead)) + return; + screenCursor = newCursor; + + editor.selection.moveCursorToPosition(cursor); + editor.selection.clearSelection(); + editor.renderer.scrollCursorIntoView(); + + editor.removeSelectionMarkers(rectSel); + rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); + rectSel.forEach(editor.addSelectionMarker, editor); + editor.updateSelectionMarkers(); + }; + + var session = editor.session; + var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var screenCursor = screenAnchor; + + + + if (ctrl && !shift && !alt && button == 0) { + if (!isMultiSelect && inSelection) + return; // dragging + + if (!isMultiSelect) + selection.addRange(selection.toOrientedRange()); + + + var oldRange = selection.rangeList.rangeAtPoint(pos); + + event.capture(editor.container, function(){}, function() { + var tmpSel = selection.toOrientedRange(); + + if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) + selection.substractPoint(tmpSel.cursor); + else + selection.addRange(tmpSel); + }); + + } else if (!shift && alt && button == 0) { + e.stop(); + + if (isMultiSelect && !ctrl) + selection.toSingleRange(); + else if (!isMultiSelect && ctrl) + selection.addRange(); + + selection.moveCursorToPosition(pos); + selection.clearSelection(); + + var rectSel = []; + + var onMouseSelectionEnd = function(e) { + clearInterval(timerId); + editor.removeSelectionMarkers(rectSel); + for (var i = 0; i < rectSel.length; i++) + selection.addRange(rectSel[i]); + }; + + var onSelectionInterval = blockSelect; + + event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); + var timerId = setInterval(function() {onSelectionInterval();}, 20); + + return e.preventDefault(); + } +} + + +exports.onMouseDown = onMouseDown; + +});/* vim:ts=4:sts=4:sw=4: + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Harutyun Amirjanyan + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/commands/multi_select_commands', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler'], function(require, exports, module) { + +// commands to enter multiselect mode +exports.defaultCommands = [{ + name: "addCursorAbove", + exec: function(editor) { editor.selectMoreLines(-1); }, + bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, + readonly: true +}, { + name: "addCursorBelow", + exec: function(editor) { editor.selectMoreLines(1); }, + bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, + readonly: true +}, { + name: "addCursorAboveSkipCurrent", + exec: function(editor) { editor.selectMoreLines(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, + readonly: true +}, { + name: "addCursorBelowSkipCurrent", + exec: function(editor) { editor.selectMoreLines(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, + readonly: true +}, { + name: "selectMoreBefore", + exec: function(editor) { editor.selectMore(-1); }, + bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, + readonly: true +}, { + name: "selectMoreAfter", + exec: function(editor) { editor.selectMore(1); }, + bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, + readonly: true +}, { + name: "selectNextBefore", + exec: function(editor) { editor.selectMore(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, + readonly: true +}, { + name: "selectNextAfter", + exec: function(editor) { editor.selectMore(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, + readonly: true +}, { + name: "splitIntoLines", + exec: function(editor) { editor.multiSelect.splitIntoLines(); }, + bindKey: {win: "Ctrl-Shift-L", mac: "Ctrl-Shift-L"}, + readonly: true +}]; + +// commands active in multiselect mode +exports.multiEditCommands = [{ + name: "singleSelection", + bindKey: "esc", + exec: function(editor) { editor.exitMultiSelectMode(); }, + readonly: true +}]; + +var HashHandler = require("../keyboard/hash_handler").HashHandler; +exports.keyboardHandler = new HashHandler(exports.multiEditCommands); + +});/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/config'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var EventEmitter = require("../lib/event_emitter").EventEmitter; +var config = require("../config"); + +var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { + + this.changeListener = this.changeListener.bind(this); + + if (config.get("packaged")) { + this.$worker = new Worker(config.get("workerPath") + "/" + packagedJs); + } + else { + var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); + this.$worker = new Worker(workerUrl); + + var tlns = {}; + for (var i=0; i + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ +define('ace/placeholder', ['require', 'exports', 'module' , 'ace/range', 'ace/lib/event_emitter', 'ace/lib/oop'], function(require, exports, module) { +"use strict"; + +var Range = require('./range').Range; +var EventEmitter = require("./lib/event_emitter").EventEmitter; +var oop = require("./lib/oop"); + +var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) { + var _self = this; + this.length = length; + this.session = session; + this.doc = session.getDocument(); + this.mainClass = mainClass; + this.othersClass = othersClass; + this.$onUpdate = this.onUpdate.bind(this); + this.doc.on("change", this.$onUpdate); + this.$others = others; + + this.$onCursorChange = function() { + setTimeout(function() { + _self.onCursorChange(); + }); + }; + + this.$pos = pos; + // Used for reset + var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1}; + this.$undoStackDepth = undoStack.length; + this.setup(); + + session.selection.on("changeCursor", this.$onCursorChange); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.setup = function() { + var _self = this; + var doc = this.doc; + var session = this.session; + var pos = this.$pos; + + this.pos = doc.createAnchor(pos.row, pos.column); + this.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); + this.pos.on("change", function(event) { + session.removeMarker(_self.markerId); + _self.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.column+_self.length), _self.mainClass, null, false); + }); + this.others = []; + this.$others.forEach(function(other) { + var anchor = doc.createAnchor(other.row, other.column); + _self.others.push(anchor); + }); + session.setUndoSelect(false); + }; + + this.showOtherMarkers = function() { + if(this.othersActive) return; + var session = this.session; + var _self = this; + this.othersActive = true; + this.others.forEach(function(anchor) { + anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false); + anchor.on("change", function(event) { + session.removeMarker(anchor.markerId); + anchor.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.column+_self.length), _self.othersClass, null, false); + }); + }); + }; + + this.hideOtherMarkers = function() { + if(!this.othersActive) return; + this.othersActive = false; + for (var i = 0; i < this.others.length; i++) { + this.session.removeMarker(this.others[i].markerId); + } + }; + + this.onUpdate = function(event) { + var delta = event.data; + var range = delta.range; + if(range.start.row !== range.end.row) return; + if(range.start.row !== this.pos.row) return; + if (this.$updating) return; + this.$updating = true; + var lengthDiff = delta.action === "insertText" ? range.end.column - range.start.column : range.start.column - range.end.column; + + if(range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1) { + var distanceFromStart = range.start.column - this.pos.column; + this.length += lengthDiff; + if(!this.session.$fromUndo) { + if(delta.action === "insertText") { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + if(otherPos.row === range.start.row && range.start.column < otherPos.column) + newPos.column += lengthDiff; + this.doc.insert(newPos, delta.text); + } + } else if(delta.action === "removeText") { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + if(otherPos.row === range.start.row && range.start.column < otherPos.column) + newPos.column += lengthDiff; + this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); + } + } + // Special case: insert in beginning + if(range.start.column === this.pos.column && delta.action === "insertText") { + setTimeout(function() { + this.pos.setPosition(this.pos.row, this.pos.column - lengthDiff); + for (var i = 0; i < this.others.length; i++) { + var other = this.others[i]; + var newPos = {row: other.row, column: other.column - lengthDiff}; + if(other.row === range.start.row && range.start.column < other.column) + newPos.column += lengthDiff; + other.setPosition(newPos.row, newPos.column); + } + }.bind(this), 0); + } + else if(range.start.column === this.pos.column && delta.action === "removeText") { + setTimeout(function() { + for (var i = 0; i < this.others.length; i++) { + var other = this.others[i]; + if(other.row === range.start.row && range.start.column < other.column) { + other.setPosition(other.row, other.column - lengthDiff); + } + } + }.bind(this), 0); + } + } + this.pos._emit("change", {value: this.pos}); + for (var i = 0; i < this.others.length; i++) { + this.others[i]._emit("change", {value: this.others[i]}); + } + } + this.$updating = false; + }; + + this.onCursorChange = function(event) { + if (this.$updating) return; + var pos = this.session.selection.getCursor(); + if(pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { + this.showOtherMarkers(); + this._emit("cursorEnter", event); + } else { + this.hideOtherMarkers(); + this._emit("cursorLeave", event); + } + }; + + this.detach = function() { + this.session.removeMarker(this.markerId); + this.hideOtherMarkers(); + this.doc.removeEventListener("change", this.$onUpdate); + this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); + this.pos.detach(); + for (var i = 0; i < this.others.length; i++) { + this.others[i].detach(); + } + this.session.setUndoSelect(true); + }; + + this.cancel = function() { + if(this.$undoStackDepth === -1) + throw Error("Canceling placeholders only supported with undo manager attached to session."); + var undoManager = this.session.getUndoManager(); + var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; + for (var i = 0; i < undosRequired; i++) { + undoManager.undo(true); + } + }; +}).call(PlaceHolder.prototype); + + +exports.PlaceHolder = PlaceHolder; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/theme/textmate', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { +"use strict"; + +exports.isDark = false; +exports.cssClass = "ace-tm"; +exports.cssText = ".ace-tm .ace_editor {\ + border: 2px solid rgb(159, 159, 159);\ +}\ +\ +.ace-tm .ace_editor.ace_focus {\ + border: 2px solid #327fbd;\ +}\ +\ +.ace-tm .ace_gutter {\ + background: #e8e8e8;\ + color: #333;\ +}\ +\ +.ace-tm .ace_print_margin {\ + width: 1px;\ + background: #e8e8e8;\ +}\ +\ +.ace-tm .ace_fold {\ + background-color: #6B72E6;\ +}\ +\ +.ace-tm .ace_text-layer {\ + cursor: text;\ +}\ +\ +.ace-tm .ace_cursor {\ + border-left: 1px solid black;\ +}\ +\ +.ace-tm .ace_cursor.ace_overwrite {\ + border-left: 0px;\ + border-bottom: 1px solid black;\ +}\ + \ +.ace-tm .ace_line .ace_invisible {\ + color: rgb(191, 191, 191);\ +}\ +\ +.ace-tm .ace_line .ace_storage,\ +.ace-tm .ace_line .ace_keyword {\ + color: blue;\ +}\ +\ +.ace-tm .ace_line .ace_constant {\ + color: rgb(197, 6, 11);\ }\ \ .ace-tm .ace_line .ace_constant.ace_buildin {\ diff --git a/apps/files_texteditor/js/aceeditor/ace.js b/apps/files_texteditor/js/aceeditor/ace.js index 8315fd13f75..6043589ac1f 100644 --- a/apps/files_texteditor/js/aceeditor/ace.js +++ b/apps/files_texteditor/js/aceeditor/ace.js @@ -1 +1,10 @@ -(function(){function g(a){var e=function(a,b){return d("",a,b)};e.packaged=!0;var f=b;a&&(b[a]||(b[a]={}),f=b[a]),f.define&&(c.original=f.define),f.define=c,f.require&&(d.original=f.require),f.require=e}var a="",b=function(){return this}();if(typeof requirejs!="undefined")return;var c=function(a,b,d){if(typeof a!="string"){c.original?c.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(d=b),c.modules||(c.modules={}),c.modules[a]=d},d=function(a,b,c){if(Object.prototype.toString.call(b)==="[object Array]"){var e=[];for(var g=0,h=b.length;g1&&h(b,"")>-1&&(i=RegExp(this.source,d.replace.call(g(this),"g","")),d.replace.call(a.slice(b.index),i,function(){for(var a=1;ab.index&&this.lastIndex--}return b},f||(RegExp.prototype.test=function(a){var b=d.exec.call(this,a);return b&&this.global&&!b[0].length&&this.lastIndex>b.index&&this.lastIndex--,!!b})}),define("ace/lib/es5-shim",["require","exports","module"],function(a,b,c){function p(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(b){}}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if(typeof b!="function")throw new TypeError;var c=g.call(arguments,1),d=function(){if(this instanceof d){var e=function(){};e.prototype=b.prototype;var f=new e,h=b.apply(f,c.concat(g.call(arguments)));return h!==null&&Object(h)===h?h:f}return b.apply(a,c.concat(g.call(arguments)))};return d});var d=Function.prototype.call,e=Array.prototype,f=Object.prototype,g=e.slice,h=d.bind(f.toString),i=d.bind(f.hasOwnProperty),j,k,l,m,n;if(n=i(f,"__defineGetter__"))j=d.bind(f.__defineGetter__),k=d.bind(f.__defineSetter__),l=d.bind(f.__lookupGetter__),m=d.bind(f.__lookupSetter__);Array.isArray||(Array.isArray=function(a){return h(a)=="[object Array]"}),Array.prototype.forEach||(Array.prototype.forEach=function(a){var b=G(this),c=arguments[1],d=0,e=b.length>>>0;if(h(a)!="[object Function]")throw new TypeError;while(d>>0,d=Array(c),e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=[],e=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var f=0;f>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0,d=arguments[1];if(h(a)!="[object Function]")throw new TypeError;for(var e=0;e>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d=0,e;if(arguments.length>=2)e=arguments[1];else do{if(d in b){e=b[d++];break}if(++d>=c)throw new TypeError}while(!0);for(;d>>0;if(h(a)!="[object Function]")throw new TypeError;if(!c&&arguments.length==1)throw new TypeError;var d,e=c-1;if(arguments.length>=2)d=arguments[1];else do{if(e in b){d=b[e--];break}if(--e<0)throw new TypeError}while(!0);do e in this&&(d=a.call(void 0,d,b[e],e,b));while(e--);return d}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=G(this),c=b.length>>>0;if(!c)return-1;var d=0;arguments.length>1&&(d=E(arguments[1])),d=d>=0?d:Math.max(0,c+d);for(;d>>0;if(!c)return-1;var d=c-1;arguments.length>1&&(d=Math.min(d,E(arguments[1]))),d=d>=0?d:c-Math.abs(d);for(;d>=0;d--)if(d in b&&a===b[d])return d;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(a){return a.__proto__||(a.constructor?a.constructor.prototype:f)});if(!Object.getOwnPropertyDescriptor){var o="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(a,b){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(o+a);if(!i(a,b))return;var c,d,e;c={enumerable:!0,configurable:!0};if(n){var g=a.__proto__;a.__proto__=f;var d=l(a,b),e=m(a,b);a.__proto__=g;if(d||e)return d&&(c.get=d),e&&(c.set=e),c}return c.value=a[b],c}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(a){return Object.keys(a)}),Object.create||(Object.create=function(a,b){var c;if(a===null)c={"__proto__":null};else{if(typeof a!="object")throw new TypeError("typeof prototype["+typeof a+"] != 'object'");var d=function(){};d.prototype=a,c=new d,c.__proto__=a}return b!==void 0&&Object.defineProperties(c,b),c});if(Object.defineProperty){var q=p({}),r=typeof document=="undefined"||p(document.createElement("div"));if(!q||!r)var s=Object.defineProperty}if(!Object.defineProperty||s){var t="Property description must be an object: ",u="Object.defineProperty called on non-object: ",v="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(a,b,c){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError(u+a);if(typeof c!="object"&&typeof c!="function"||c===null)throw new TypeError(t+c);if(s)try{return s.call(Object,a,b,c)}catch(d){}if(i(c,"value"))if(n&&(l(a,b)||m(a,b))){var e=a.__proto__;a.__proto__=f,delete a[b],a[b]=c.value,a.__proto__=e}else a[b]=c.value;else{if(!n)throw new TypeError(v);i(c,"get")&&j(a,b,c.get),i(c,"set")&&k(a,b,c.set)}return a}}Object.defineProperties||(Object.defineProperties=function(a,b){for(var c in b)i(b,c)&&Object.defineProperty(a,c,b[c]);return a}),Object.seal||(Object.seal=function(a){return a}),Object.freeze||(Object.freeze=function(a){return a});try{Object.freeze(function(){})}catch(w){Object.freeze=function(a){return function b(b){return typeof b=="function"?b:a(b)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(a){return a}),Object.isSealed||(Object.isSealed=function(a){return!1}),Object.isFrozen||(Object.isFrozen=function(a){return!1}),Object.isExtensible||(Object.isExtensible=function(a){if(Object(a)===a)throw new TypeError;var b="";while(i(a,b))b+="?";a[b]=!0;var c=i(a,b);return delete a[b],c});if(!Object.keys){var x=!0,y=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],z=y.length;for(var A in{toString:null})x=!1;Object.keys=function bd(a){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.keys called on a non-object");var bd=[];for(var b in a)i(a,b)&&bd.push(b);if(x)for(var c=0,d=z;c9999?"+":"")+("00000"+Math.abs(d)).slice(0<=d&&d<=9999?-4:-6),b=a.length;while(b--)c=a[b],c<10&&(a[b]="0"+c);return d+"-"+a.slice(0,2).join("-")+"T"+a.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};Date.now||(Date.now=function(){return(new Date).getTime()}),Date.prototype.toJSON||(Date.prototype.toJSON=function(a){if(typeof this.toISOString!="function")throw new TypeError;return this.toISOString()}),Date.parse("+275760-09-13T00:00:00.000Z")!==864e13&&(Date=function(a){var b=function e(b,c,d,f,g,h,i){var j=arguments.length;if(this instanceof a){var k=j==1&&String(b)===b?new a(e.parse(b)):j>=7?new a(b,c,d,f,g,h,i):j>=6?new a(b,c,d,f,g,h):j>=5?new a(b,c,d,f,g):j>=4?new a(b,c,d,f):j>=3?new a(b,c,d):j>=2?new a(b,c):j>=1?new a(b):new a;return k.constructor=e,k}return a.apply(this,arguments)},c=new RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$");for(var d in a)b[d]=a[d];return b.now=a.now,b.UTC=a.UTC,b.prototype=a.prototype,b.prototype.constructor=b,b.parse=function f(b){var d=c.exec(b);if(d){d.shift();for(var e=1;e<7;e++)d[e]=+(d[e]||(e<3?1:0)),e==1&&d[e]--;var f=+d.pop(),g=+d.pop(),h=d.pop(),i=0;if(h){if(g>23||f>59)return NaN;i=(g*60+f)*6e4*(h=="+"?-1:1)}var j=+d[0];return 0<=j&&j<=99?(d[0]=j+400,a.UTC.apply(this,d)+i-126227808e5):a.UTC.apply(this,d)+i}return a.parse.apply(this,arguments)},b}(Date));var B="\t\n \f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||B.trim()){B="["+B+"]";var C=new RegExp("^"+B+B+"*"),D=new RegExp(B+B+"*$");String.prototype.trim=function(){return String(this).replace(C,"").replace(D,"")}}var E=function(a){return a=+a,a!==a?a=0:a!==0&&a!==1/0&&a!==-Infinity&&(a=(a>0||-1)*Math.floor(Math.abs(a))),a},F="a"[0]!="a",G=function(a){if(a==null)throw new TypeError;return F&&typeof a=="string"&&a?a.split(""):Object(a)}}),define("ace/lib/dom",["require","exports","module"],function(a,b,c){"use strict";var d="http://www.w3.org/1999/xhtml";b.createElement=function(a,b){return document.createElementNS?document.createElementNS(b||d,a):document.createElement(a)},b.setText=function(a,b){a.innerText!==undefined&&(a.innerText=b),a.textContent!==undefined&&(a.textContent=b)},b.hasCssClass=function(a,b){var c=a.className.split(/\s+/g);return c.indexOf(b)!==-1},b.addCssClass=function(a,c){b.hasCssClass(a,c)||(a.className+=" "+c)},b.removeCssClass=function(a,b){var c=a.className.split(/\s+/g);for(;;){var d=c.indexOf(b);if(d==-1)break;c.splice(d,1)}a.className=c.join(" ")},b.toggleCssClass=function(a,b){var c=a.className.split(/\s+/g),d=!0;for(;;){var e=c.indexOf(b);if(e==-1)break;d=!1,c.splice(e,1)}return d&&c.push(b),a.className=c.join(" "),d},b.setCssClass=function(a,c,d){d?b.addCssClass(a,c):b.removeCssClass(a,c)},b.hasCssString=function(a,b){var c=0,d;b=b||document;if(b.createStyleSheet&&(d=b.styleSheets)){while(cd&&(d=Math.abs(a.wheelDeltaY));if(d>5e3)var b=400;else var b=8;a.wheelDeltaX!==undefined?(a.wheelX=-a.wheelDeltaX/b,a.wheelY=-a.wheelDeltaY/b):(a.wheelX=0,a.wheelY=-a.wheelDelta/b)}else a.axis&&a.axis==a.HORIZONTAL_AXIS?(a.wheelX=(a.detail||0)*5,a.wheelY=0):(a.wheelX=0,a.wheelY=(a.detail||0)*5);c(a)};b.addListener(a,"DOMMouseScroll",e),b.addListener(a,"mousewheel",e)},b.addMultiMouseDownListener=function(a,c,d,f,g){var h=0,i,j,k=function(a){h+=1,h==1&&(i=a.clientX,j=a.clientY,setTimeout(function(){h=0},f||600));var e=b.getButton(a)==c;if(!e||Math.abs(a.clientX-i)>5||Math.abs(a.clientY-j)>5)h=0;h==d&&(h=0,g(a));if(e)return b.preventDefault(a)};b.addListener(a,"mousedown",k),e.isOldIE&&b.addListener(a,"dblclick",k)},b.addCommandKeyListener=function(a,c){var d=b.addListener;if(e.isOldGecko){var f=null;d(a,"keydown",function(a){f=a.keyCode}),d(a,"keypress",function(a){return g(c,a,f)})}else{var h=null;d(a,"keydown",function(a){return h=a.keyIdentifier||a.keyCode,g(c,a,a.keyCode)}),e.isMac&&e.isOpera&&d(a,"keypress",function(a){var b=a.keyIdentifier||a.keyCode;if(h!==b)return g(c,a,h);h=null})}};if(window.postMessage){var h=1;b.nextTick=function(a,c){c=c||window;var d="zero-timeout-message-"+h;b.addListener(c,"message",function e(f){f.data==d&&(b.stopPropagation(f),b.removeListener(c,"message",e),a())}),c.postMessage(d,"*")}}else b.nextTick=function(a,b){b=b||window,window.setTimeout(a,0)}}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(a,b,c){"use strict";var d=a("./oop"),e=function(){var a={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,meta:8,command:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:'"'}};for(var b in a.FUNCTION_KEYS){var c=a.FUNCTION_KEYS[b].toUpperCase();a[c]=parseInt(b,10)}return d.mixin(a,a.MODIFIER_KEYS),d.mixin(a,a.PRINTABLE_KEYS),d.mixin(a,a.FUNCTION_KEYS),a}();d.mixin(b,e),b.keyCodeToString=function(a){return(e[a]||String.fromCharCode(a)).toLowerCase()}}),define("ace/lib/oop",["require","exports","module"],function(a,b,c){"use strict",b.inherits=function(){var a=function(){};return function(b,c){a.prototype=c.prototype,b.super_=c.prototype,b.prototype=new a,b.prototype.constructor=b}}(),b.mixin=function(a,b){for(var c in b)a[c]=b[c]},b.implement=function(a,c){b.mixin(a,c)}}),define("ace/lib/useragent",["require","exports","module"],function(a,b,c){"use strict";var d=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),e=navigator.userAgent;b.isWin=d=="win",b.isMac=d=="mac",b.isLinux=d=="linux",b.isIE=navigator.appName=="Microsoft Internet Explorer"&&parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]),b.isOldIE=b.isIE&&b.isIE<9,b.isGecko=b.isMozilla=window.controllers&&window.navigator.product==="Gecko",b.isOldGecko=b.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,b.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",b.isWebKit=parseFloat(e.split("WebKit/")[1])||undefined,b.isChrome=parseFloat(e.split(" Chrome/")[1])||undefined,b.isAIR=e.indexOf("AdobeAIR")>=0,b.isIPad=e.indexOf("iPad")>=0,b.isTouchPad=e.indexOf("TouchPad")>=0,b.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},b.getOS=function(){return b.isMac?b.OS.MAC:b.isLinux?b.OS.LINUX:b.OS.WINDOWS}}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands"],function(a,b,c){"use strict",a("./lib/fixoldbrowsers");var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/useragent"),g=a("./keyboard/textinput").TextInput,h=a("./mouse/mouse_handler").MouseHandler,i=a("./mouse/fold_handler").FoldHandler,j=a("./keyboard/keybinding").KeyBinding,k=a("./edit_session").EditSession,l=a("./search").Search,m=a("./range").Range,n=a("./lib/event_emitter").EventEmitter,o=a("./commands/command_manager").CommandManager,p=a("./commands/default_commands").commands,q=function(a,b){var c=a.getContainerElement();this.container=c,this.renderer=a,this.textInput=new g(a.getTextAreaContainer(),this),this.keyBinding=new j(this),f.isIPad||(this.$mouseHandler=new h(this),new i(this)),this.$blockScrolling=0,this.$search=(new l).set({wrap:!0}),this.commands=new o(f.isMac?"mac":"win",p),this.setSession(b||new k(""))};((function(){d.implement(this,n),this.setKeyboardHandler=function(a){this.keyBinding.setKeyboardHandler(a)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(a){if(this.session==a)return;if(this.session){var b=this.session;this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeLeftTop",this.$onScrollLeftChange);var c=this.session.getSelection();c.removeEventListener("changeCursor",this.$onCursorChange),c.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=a,this.$onDocumentChange=this.onDocumentChange.bind(this),a.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(a),this.$onChangeMode=this.onChangeMode.bind(this),a.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),a.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.updateText.bind(this.renderer),a.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),a.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),a.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),a.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=a.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.onCursorChange(),this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull(),this._emit("changeSession",{session:a,oldSession:b})},this.getSession=function(){return this.session},this.getSelection=function(){return this.selection},this.resize=function(){this.renderer.onResize()},this.setTheme=function(a){this.renderer.setTheme(a)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(a){this.renderer.setStyle(a)},this.unsetStyle=function(a){this.renderer.unsetStyle(a)},this.setFontSize=function(a){this.container.style.fontSize=a},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var a=this;this.$highlightPending=!0,setTimeout(function(){a.$highlightPending=!1;var b=a.session.findMatchingBracket(a.getCursorPosition());if(b){var c=new m(b.row,b.column,b.row,b.column+1);a.session.$bracketHighlight=a.session.addMarker(c,"ace_bracket","text")}},10)},this.focus=function(){var a=this;setTimeout(function(){a.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.onDocumentChange=function(a){var b=a.data,c=b.range,d;c.start.row==c.end.row&&b.action!="insertLines"&&b.action!="removeLines"?d=c.end.row:d=Infinity,this.renderer.updateLines(c.start.row,d),this._emit("change",a),this.onCursorChange()},this.onTokenizerUpdate=function(a){var b=a.data;this.renderer.updateLines(b.first,b.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.renderer.updateCursor(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.renderer.moveTextAreaToCursor(this.textInput.getElement()),this.$highlightBrackets(),this.$updateHighlightActiveLine()},this.$updateHighlightActiveLine=function(){var a=this.getSession();a.$highlightLineMarker&&a.removeMarker(a.$highlightLineMarker),a.$highlightLineMarker=null;if(this.getHighlightActiveLine()&&(this.getSelectionStyle()!="line"||!this.selection.isMultiLine())){var b=this.getCursorPosition(),c=this.session.getFoldLine(b.row),d;c?d=new m(c.start.row,0,c.end.row+1,0):d=new m(b.row,0,b.row+1,0),a.$highlightLineMarker=a.addMarker(d,"ace_active_line","background")}},this.onSelectionChange=function(a){var b=this.getSession();b.$selectionMarker&&b.removeMarker(b.$selectionMarker),b.$selectionMarker=null;if(!this.selection.isEmpty()){var c=this.selection.getRange(),d=this.getSelectionStyle();b.$selectionMarker=b.addMarker(c,"ace_selection",d)}else this.$updateHighlightActiveLine();this.$highlightSelectedWord&&this.session.getMode().highlightSelection(this)},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.setBreakpoints(this.session.getBreakpoints())},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(){this.renderer.updateText()},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getCopyText=function(){var a="";return this.selection.isEmpty()||(a=this.session.getTextRange(this.getSelectionRange())),this._emit("copy",a),a},this.onCut=function(){if(this.$readOnly)return;var a=this.getSelectionRange();this._emit("cut",a),this.selection.isEmpty()||(this.session.remove(a),this.clearSelection())},this.insert=function(a){var b=this.session,c=b.getMode(),d=this.getCursorPosition();if(this.getBehavioursEnabled()){var e=c.transformAction(b.getState(d.row),"insertion",this,b,a);e&&(a=e.text)}a=a.replace("\t",this.session.getTabString());if(!this.selection.isEmpty())d=this.session.remove(this.getSelectionRange()),this.clearSelection();else if(this.session.getOverwrite()){var f=new m.fromPoints(d,d);f.end.column+=a.length,this.session.remove(f)}this.clearSelection();var g=d.column,h=b.getState(d.row),i=c.checkOutdent(h,b.getLine(d.row),a),j=b.getLine(d.row),k=c.getNextLineIndent(h,j.slice(0,d.column),b.getTabString()),l=b.insert(d,a);e&&e.selection&&(e.selection.length==2?this.selection.setSelectionRange(new m(d.row,g+e.selection[0],d.row,g+e.selection[1])):this.selection.setSelectionRange(new m(d.row+e.selection[0],e.selection[1],d.row+e.selection[2],e.selection[3])));var h=b.getState(d.row);if(b.getDocument().isNewLine(a)){this.moveCursorTo(d.row+1,0);var n=b.getTabSize(),o=Number.MAX_VALUE;for(var p=d.row+1;p<=l.row;++p){var q=0;j=b.getLine(p);for(var r=0;r0;++r)j.charAt(r)=="\t"?s-=n:j.charAt(r)==" "&&(s-=1);b.remove(new m(p,0,p,r))}b.indentRows(d.row+1,l.row,k)}i&&c.autoOutdent(h,b,d.row)},this.onTextInput=function(a,b){b&&this._emit("paste",a),this.keyBinding.onTextInput(a,b)},this.onCommandKey=function(a,b,c){this.keyBinding.onCommandKey(a,b,c)},this.setOverwrite=function(a){this.session.setOverwrite(a)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(a){this.$mouseHandler.setScrollSpeed(a)},this.getScrollSpeed=function(){return this.$mouseHandler.getScrollSpeed()},this.setDragDelay=function(a){this.$mouseHandler.setDragDelay(a)},this.getDragDelay=function(){return this.$mouseHandler.getDragDelay()},this.$selectionStyle="line",this.setSelectionStyle=function(a){if(this.$selectionStyle==a)return;this.$selectionStyle=a,this.onSelectionChange(),this._emit("changeSelectionStyle",{data:a})},this.getSelectionStyle=function(){return this.$selectionStyle},this.$highlightActiveLine=!0,this.setHighlightActiveLine=function(a){if(this.$highlightActiveLine==a)return;this.$highlightActiveLine=a,this.$updateHighlightActiveLine()},this.getHighlightActiveLine=function(){return this.$highlightActiveLine},this.$highlightSelectedWord=!0,this.setHighlightSelectedWord=function(a){if(this.$highlightSelectedWord==a)return;this.$highlightSelectedWord=a,a?this.session.getMode().highlightSelection(this):this.session.getMode().clearSelectionHighlight(this)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setShowInvisibles=function(a){if(this.getShowInvisibles()==a)return;this.renderer.setShowInvisibles(a)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setShowPrintMargin=function(a){this.renderer.setShowPrintMargin(a)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(a){this.renderer.setPrintMarginColumn(a)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.$readOnly=!1,this.setReadOnly=function(a){this.$readOnly=a},this.getReadOnly=function(){return this.$readOnly},this.$modeBehaviours=!0,this.setBehavioursEnabled=function(a){this.$modeBehaviours=a},this.getBehavioursEnabled=function(){return this.$modeBehaviours},this.setShowFoldWidgets=function(a){var b=this.renderer.$gutterLayer;if(b.getShowFoldWidgets()==a)return;this.renderer.$gutterLayer.setShowFoldWidgets(a),this.$showFoldWidgets=a,this.renderer.updateFull()},this.getShowFoldWidgets=function(){return this.renderer.$gutterLayer.getShowFoldWidgets()},this.remove=function(a){this.selection.isEmpty()&&(a=="left"?this.selection.selectLeft():this.selection.selectRight());var b=this.getSelectionRange();if(this.getBehavioursEnabled()){var c=this.session,d=c.getState(b.start.row),e=c.getMode().transformAction(d,"deletion",this,c,b);e&&(b=e)}this.session.remove(b),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var a=this.getSelectionRange();a.start.column==a.end.column&&a.start.row==a.end.row&&(a.end.column=0,a.end.row++),this.session.remove(a),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var a=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(a)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var a=this.getCursorPosition(),b=a.column;if(b===0)return;var c=this.session.getLine(a.row),d,e;b=this.getFirstVisibleRow()&&a<=this.getLastVisibleRow()},this.isRowFullyVisible=function(a){return a>=this.renderer.getFirstFullyVisibleRow()&&a<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$getPageDownRow=function(){return this.renderer.getScrollBottomRow()},this.$getPageUpRow=function(){var a=this.renderer.getScrollTopRow(),b=this.renderer.getScrollBottomRow();return a-(b-a)},this.selectPageDown=function(){var a=this.$getPageDownRow()+Math.floor(this.$getVisibleRowCount()/2);this.scrollPageDown();var b=this.getSelection(),c=this.session.documentToScreenPosition(b.getSelectionLead()),d=this.session.screenToDocumentPosition(a,c.column);b.selectTo(d.row,d.column)},this.selectPageUp=function(){var a=this.renderer.getScrollTopRow()-this.renderer.getScrollBottomRow(),b=this.$getPageUpRow()+Math.round(a/2);this.scrollPageUp();var c=this.getSelection(),d=this.session.documentToScreenPosition(c.getSelectionLead()),e=this.session.screenToDocumentPosition(b,d.column);c.selectTo(e.row,e.column)},this.gotoPageDown=function(){var a=this.$getPageDownRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.gotoPageUp=function(){var a=this.$getPageUpRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.scrollPageDown=function(){this.scrollToRow(this.$getPageDownRow())},this.scrollPageUp=function(){this.renderer.scrollToRow(this.$getPageUpRow())},this.scrollToRow=function(a){this.renderer.scrollToRow(a)},this.scrollToLine=function(a,b){this.renderer.scrollToLine(a,b)},this.centerSelection=function(){var a=this.getSelectionRange(),b=Math.floor(a.start.row+(a.end.row-a.start.row)/2);this.renderer.scrollToLine(b,!0)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(a,b){this.selection.moveCursorTo(a,b)},this.moveCursorToPosition=function(a){this.selection.moveCursorToPosition(a)},this.jumpToMatching=function(){var a=this.getCursorPosition(),b=this.session.findMatchingBracket(a);b||(a.column+=1,b=this.session.findMatchingBracket(a)),b||(a.column-=2,b=this.session.findMatchingBracket(a)),b&&(this.clearSelection(),this.moveCursorTo(b.row,b.column))},this.gotoLine=function(a,b){this.selection.clearSelection(),this.session.unfold({row:a-1,column:b||0}),this.$blockScrolling+=1,this.moveCursorTo(a-1,b||0),this.$blockScrolling-=1,this.isRowFullyVisible(this.getCursorPosition().row)||this.scrollToLine(a,!0)},this.navigateTo=function(a,b){this.clearSelection(),this.moveCursorTo(a,b)},this.navigateUp=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(-a,0)},this.navigateDown=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(a,0)},this.navigateLeft=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().start;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().end;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(a,b){b&&this.$search.set(b);var c=this.$search.find(this.session);if(!c)return;this.$tryReplace(c,a),c!==null&&this.selection.setSelectionRange(c)},this.replaceAll=function(a,b){b&&this.$search.set(b);var c=this.$search.findAll(this.session);if(!c.length)return;var d=this.getSelectionRange();this.clearSelection(),this.selection.moveCursorTo(0,0),this.$blockScrolling+=1;for(var e=c.length-1;e>=0;--e)this.$tryReplace(c[e],a);this.selection.setSelectionRange(d),this.$blockScrolling-=1},this.$tryReplace=function(a,b){var c=this.session.getTextRange(a);return b=this.$search.replace(c,b),b!==null?(a.end=this.session.replace(a,b),a):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(a,b){this.clearSelection(),b=b||{},b.needle=a,this.$search.set(b),this.$find()},this.findNext=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!1),this.$search.set(a),this.$find()},this.findPrevious=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!0),this.$search.set(a),this.$find()},this.$find=function(a){this.selection.isEmpty()||this.$search.set({needle:this.session.getTextRange(this.getSelectionRange())}),typeof a!="undefined"&&this.$search.set({backwards:a});var b=this.$search.find(this.session);b&&(this.session.unfold(b),this.gotoLine(b.end.row+1,b.end.column),this.selection.setSelectionRange(b))},this.undo=function(){this.session.getUndoManager().undo()},this.redo=function(){this.session.getUndoManager().redo()},this.destroy=function(){this.renderer.destroy()}})).call(q.prototype),b.Editor=q}),define("ace/lib/lang",["require","exports","module"],function(a,b,c){"use strict",b.stringReverse=function(a){return a.split("").reverse().join("")},b.stringRepeat=function(a,b){return(new Array(b+1)).join(a)};var d=/^\s\s*/,e=/\s\s*$/;b.stringTrimLeft=function(a){return a.replace(d,"")},b.stringTrimRight=function(a){return a.replace(e,"")},b.copyObject=function(a){var b={};for(var c in a)b[c]=a[c];return b},b.copyArray=function(a){var b=[];for(var c=0,d=a.length;c128)return;setTimeout(function(){h||m()},0)},p=function(a){h=!0,b.onCompositionStart(),e.isGecko||setTimeout(q,0)},q=function(){if(!h)return;b.onCompositionUpdate(c.value)},r=function(a){h=!1,b.onCompositionEnd()},s=function(a){i=!0;var d=b.getCopyText();d?c.value=d:a.preventDefault(),l(),setTimeout(function(){m()},0)},t=function(a){i=!0;var d=b.getCopyText();d?(c.value=d,b.onCut()):a.preventDefault(),l(),setTimeout(function(){m()},0)};d.addCommandKeyListener(c,b.onCommandKey.bind(b));if(e.isOldIE){var u={13:1,27:1};d.addListener(c,"keyup",function(a){h&&(!c.value||u[a.keyCode])&&setTimeout(r,0);if((c.value.charCodeAt(0)|0)<129)return;h?q():p()})}"onpropertychange"in c&&!("oninput"in c)?d.addListener(c,"propertychange",o):d.addListener(c,"input",n),d.addListener(c,"paste",function(a){j=!0,a.clipboardData&&a.clipboardData.getData?(m(a.clipboardData.getData("text/plain")),a.preventDefault()):o()}),"onbeforecopy"in c&&typeof clipboardData!="undefined"?(d.addListener(c,"beforecopy",function(a){var c=b.getCopyText();c?clipboardData.setData("Text",c):a.preventDefault()}),d.addListener(a,"keydown",function(a){if(a.ctrlKey&&a.keyCode==88){var c=b.getCopyText();c&&(clipboardData.setData("Text",c),b.onCut()),d.preventDefault(a)}})):(d.addListener(c,"copy",s),d.addListener(c,"cut",t)),d.addListener(c,"compositionstart",p),e.isGecko&&d.addListener(c,"text",q),e.isWebKit&&d.addListener(c,"keyup",q),d.addListener(c,"compositionend",r),d.addListener(c,"blur",function(){b.onBlur()}),d.addListener(c,"focus",function(){b.onFocus(),l()}),this.focus=function(){b.onFocus(),l(),c.focus()},this.blur=function(){c.blur()},this.isFocused=v,this.getElement=function(){return c},this.onContextMenu=function(a,b){a&&(k||(k=c.style.cssText),c.style.cssText="position:fixed; z-index:1000;left:"+(a.x-2)+"px; top:"+(a.y-2)+"px;"),b&&(c.value="")},this.onContextMenuClose=function(){setTimeout(function(){k&&(c.style.cssText=k,k=""),m()},0)}};b.TextInput=g}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event"],function(a,b,c){"use strict";var d=a("../lib/event"),e=a("./default_handlers").DefaultHandlers,f=a("./default_gutter_handler").GutterHandler,g=a("./mouse_event").MouseEvent,h=function(a){this.editor=a,new e(a),new f(a),d.addListener(a.container,"mousedown",function(b){return a.focus(),d.preventDefault(b)}),d.addListener(a.container,"selectstart",function(a){return d.preventDefault(a)});var b=a.renderer.getMouseEventTarget();d.addListener(b,"mousedown",this.onMouseEvent.bind(this,"mousedown")),d.addListener(b,"click",this.onMouseEvent.bind(this,"click")),d.addListener(b,"mousemove",this.onMouseMove.bind(this,"mousemove")),d.addMultiMouseDownListener(b,0,2,500,this.onMouseEvent.bind(this,"dblclick")),d.addMultiMouseDownListener(b,0,3,600,this.onMouseEvent.bind(this,"tripleclick")),d.addMultiMouseDownListener(b,0,4,600,this.onMouseEvent.bind(this,"quadclick")),d.addMouseWheelListener(a.container,this.onMouseWheel.bind(this,"mousewheel"));var c=a.renderer.$gutter;d.addListener(c,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),d.addListener(c,"click",this.onMouseEvent.bind(this,"gutterclick")),d.addListener(c,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),d.addListener(c,"mousemove",this.onMouseMove.bind(this,"gutter"))};((function(){this.$scrollSpeed=1,this.setScrollSpeed=function(a){this.$scrollSpeed=a},this.getScrollSpeed=function(){return this.$scrollSpeed},this.onMouseEvent=function(a,b){this.editor._emit(a,new g(b,this.editor))},this.$dragDelay=250,this.setDragDelay=function(a){this.$dragDelay=a},this.getDragDelay=function(){return this.$dragDelay},this.onMouseMove=function(a,b){var c=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!c||!c.length)return;this.editor._emit(a,new g(b,this.editor))},this.onMouseWheel=function(a,b){var c=new g(b,this.editor);c.speed=this.$scrollSpeed*2,c.wheelX=b.wheelX,c.wheelY=b.wheelY,this.editor._emit(a,c)}})).call(h.prototype),b.MouseHandler=h}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/event","ace/lib/dom","ace/lib/browser_focus"],function(a,b,c){function k(a){this.editor=a,this.$clickSelection=null,this.browserFocus=new f,a.setDefaultHandler("mousedown",this.onMouseDown.bind(this)),a.setDefaultHandler("dblclick",this.onDoubleClick.bind(this)),a.setDefaultHandler("tripleclick",this.onTripleClick.bind(this)),a.setDefaultHandler("quadclick",this.onQuadClick.bind(this)),a.setDefaultHandler("mousewheel",this.onScroll.bind(this))}function l(a,b,c,d){return Math.sqrt(Math.pow(c-a,2)+Math.pow(d-b,2))}"use strict";var d=a("../lib/event"),e=a("../lib/dom"),f=a("../lib/browser_focus").BrowserFocus,g=0,h=1,i=2,j=5;((function(){this.onMouseDown=function(a){function C(b){a.getShiftKey()?m.selection.selectToPosition(b):n.$clickSelection||(m.moveCursorToPosition(b),m.selection.clearSelection(b.row,b.column)),q=h}var b=a.inSelection(),c=a.pageX,f=a.pageY,k=a.getDocumentPosition(),m=this.editor,n=this,o=m.getSelectionRange(),p=o.isEmpty(),q=g;if(b&&(!this.browserFocus.isFocused()||(new Date).getTime()-this.browserFocus.lastFocus<20||!m.isFocused())){m.focus();return}var r=a.getButton();if(r!==0){p&&m.moveCursorToPosition(k),r==2&&(m.textInput.onContextMenu({x:a.clientX,y:a.clientY},p),d.capture(m.container,function(){},m.textInput.onContextMenuClose));return}b||C(k);var s=c,t=f,u=(new Date).getTime(),v,w,x,y=function(a){s=d.getDocumentX(a),t=d.getDocumentY(a)},z=function(a){clearInterval(F),q==g?C(k):q==i&&A(a),n.$clickSelection=null,q=g},A=function(a){e.removeCssClass(m.container,"ace_dragging"),m.session.removeMarker(x),m.$mouseHandler.$clickSelection||v||(m.moveCursorToPosition(k),m.selection.clearSelection(k.row,k.column));if(!v)return;if(w.contains(v.row,v.column)){v=null;return}m.clearSelection();if(a&&(a.ctrlKey||a.altKey))var b=m.session,c=b.insert(v,b.getTextRange(w));else var c=m.moveText(w,v);if(!c){v=null;return}m.selection.setSelectionRange(c)},B=function(){if(q==g){var a=l(c,f,s,t),b=(new Date).getTime();if(a>j){q=h;var d=m.renderer.screenToTextCoordinates(s,t);d.row=Math.max(0,Math.min(d.row,m.session.getLength()-1)),C(d)}else if(b-u>m.getDragDelay()){q=i,w=m.getSelectionRange();var k=m.getSelectionStyle();x=m.session.addMarker(w,"ace_selection",k),m.clearSelection(),e.addCssClass(m.container,"ace_dragging")}}q==i?E():q==h&&D()},D=function(){var a,b=m.renderer.screenToTextCoordinates(s,t);b.row=Math.max(0,Math.min(b.row,m.session.getLength()-1)),n.$clickSelection?n.$clickSelection.contains(b.row,b.column)?m.selection.setSelectionRange(n.$clickSelection):(n.$clickSelection.compare(b.row,b.column)==-1?a=n.$clickSelection.end:a=n.$clickSelection.start,m.selection.setSelectionAnchor(a.row,a.column),m.selection.selectToPosition(b)):m.selection.selectToPosition(b),m.renderer.scrollCursorIntoView()},E=function(){v=m.renderer.screenToTextCoordinates(s,t),v.row=Math.max(0,Math.min(v.row,m.session.getLength()-1)),m.moveCursorToPosition(v)};d.capture(m.container,y,z);var F=setInterval(B,20);return a.preventDefault()},this.onDoubleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectWord(),this.$clickSelection=c.getSelectionRange()},this.onTripleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectLine(),this.$clickSelection=c.getSelectionRange()},this.onQuadClick=function(a){var b=this.editor;b.selectAll(),this.$clickSelection=b.getSelectionRange()},this.onScroll=function(a){var b=this.editor;b.renderer.scrollBy(a.wheelX*a.speed,a.wheelY*a.speed);if(b.renderer.isScrollableBy(a.wheelX*a.speed,a.wheelY*a.speed))return a.preventDefault()}})).call(k.prototype),b.DefaultHandlers=k}),define("ace/lib/browser_focus",["require","exports","module","ace/lib/oop","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./oop"),e=a("./event"),f=a("./event_emitter").EventEmitter,g=function(a){a=a||window,this.lastFocus=(new Date).getTime(),this._isFocused=!0;var b=this;"onfocusin"in a.document?(e.addListener(a.document,"focusin",function(a){b._setFocused(!0)}),e.addListener(a.document,"focusout",function(a){b._setFocused(!!a.toElement)})):(e.addListener(a,"blur",function(a){b._setFocused(!1)}),e.addListener(a,"focus",function(a){b._setFocused(!0)}))};((function(){d.implement(this,f),this.isFocused=function(){return this._isFocused},this._setFocused=function(a){if(this._isFocused==a)return;a&&(this.lastFocus=(new Date).getTime()),this._isFocused=a,this._emit("changeFocus")}})).call(g.prototype),b.BrowserFocus=g}),define("ace/lib/event_emitter",["require","exports","module"],function(a,b,c){"use strict";var d={};d._emit=d._dispatchEvent=function(a,b){this._eventRegistry=this._eventRegistry||{},this._defaultHandlers=this._defaultHandlers||{};var c=this._eventRegistry[a]||[],d=this._defaultHandlers[a];if(!c.length&&!d)return;b=b||{},b.type=a,b.stopPropagation||(b.stopPropagation=function(){this.propagationStopped=!0}),b.preventDefault||(b.preventDefault=function(){this.defaultPrevented=!0});for(var e=0;e=4352&&a<=4447||a>=4515&&a<=4519||a>=4602&&a<=4607||a>=9001&&a<=9002||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12283||a>=12288&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12589||a>=12593&&a<=12686||a>=12688&&a<=12730||a>=12736&&a<=12771||a>=12784&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=13054||a>=13056&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=55216&&a<=55238||a>=55243&&a<=55291||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=65281&&a<=65376||a>=65504&&a<=65510}d.implement(this,f),this.setDocument=function(a){if(this.doc)throw new Error("Document is already set");this.doc=a,a.on("change",this.onChange.bind(this)),this.on("changeFold",this.onChangeFold.bind(this)),this.bgTokenizer&&(this.bgTokenizer.setDocument(this.getDocument()),this.bgTokenizer.start(0))},this.getDocument=function(){return this.doc},this.$resetRowCache=function(a){if(a==0){this.$rowCache=[];return}var b=this.$rowCache;for(var c=0;c=a){b.splice(c,b.length);return}},this.onChangeFold=function(a){var b=a.data;this.$resetRowCache(b.start.row)},this.onChange=function(a){var b=a.data;this.$modified=!0,this.$resetRowCache(b.range.start.row);var c=this.$updateInternalDataOnChange(a);!this.$fromUndo&&this.$undoManager&&!b.ignore&&(this.$deltasDoc.push(b),c&&c.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:c}),this.$informUndoManager.schedule()),this.bgTokenizer.start(b.range.start.row),this._emit("change",a)},this.setValue=function(a){this.doc.setValue(a),this.selection.moveCursorTo(0,0),this.selection.clearSelection(),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(a){return this.bgTokenizer.getState(a)},this.getTokens=function(a,b){return this.bgTokenizer.getTokens(a,b)},this.getTokenAt=function(a,b){var c=this.bgTokenizer.getTokens(a,a)[0].tokens,d,e=0;if(b==null)f=c.length-1,e=this.getLine(a).length;else for(var f=0;f=b)break}return d=c[f],d?(d.index=f,d.start=e-d.value.length,d):null},this.setUndoManager=function(a){this.$undoManager=a,this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(a){var b=this;this.$syncInformUndoManager=function(){b.$informUndoManager.cancel(),b.$deltasFold.length&&(b.$deltas.push({group:"fold",deltas:b.$deltasFold}),b.$deltasFold=[]),b.$deltasDoc.length&&(b.$deltas.push({group:"doc",deltas:b.$deltasDoc}),b.$deltasDoc=[]),b.$deltas.length>0&&a.execute({action:"aceupdate",args:[b.$deltas,b]}),b.$deltas=[]},this.$informUndoManager=e.deferredCall(this.$syncInformUndoManager)}},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?e.stringRepeat(" ",this.getTabSize()):"\t"},this.$useSoftTabs=!0,this.setUseSoftTabs=function(a){if(this.$useSoftTabs===a)return;this.$useSoftTabs=a},this.getUseSoftTabs=function(){return this.$useSoftTabs},this.$tabSize=4,this.setTabSize=function(a){if(isNaN(a)||this.$tabSize===a)return;this.$modified=!0,this.$tabSize=a,this._emit("changeTabSize")},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(a){return this.$useSoftTabs&&a.column%this.$tabSize==0},this.$overwrite=!1,this.setOverwrite=function(a){if(this.$overwrite==a)return;this.$overwrite=a,this._emit("changeOverwrite")},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(a){this.$breakpoints=[];for(var b=0;b0&&(d=!!c.charAt(b-1).match(this.tokenRe)),d||(d=!!c.charAt(b).match(this.tokenRe));var e=d?this.tokenRe:this.nonTokenRe,f=b;if(f>0){do f--;while(f>=0&&c.charAt(f).match(e));f++}var g=b;while(g=this.doc.getLength()-1)return 0;var c=this.doc.removeLines(a,b);return this.doc.insertLines(a+1,c),1},this.duplicateLines=function(a,b){var a=this.$clipRowToDocument(a),b=this.$clipRowToDocument(b),c=this.getLines(a,b);this.doc.insertLines(a,c);var d=b-a+1;return d},this.$clipRowToDocument=function(a){return Math.max(0,Math.min(a,this.doc.getLength()-1))},this.$clipColumnToRow=function(a,b){return b<0?0:Math.min(this.doc.getLine(a).length,b)},this.$clipPositionToDocument=function(a,b){b=Math.max(0,b);if(a<0)a=0,b=0;else{var c=this.doc.getLength();a>=c?(a=c-1,b=this.doc.getLine(c-1).length):b=Math.min(this.doc.getLine(a).length,b)}return{row:a,column:b}},this.$clipRangeToDocument=function(a){a.start.row<0?(a.start.row=0,a.start.column=0):a.start.column=this.$clipColumnToRow(a.start.row,a.start.column);var b=this.doc.getLength()-1;return a.end.row>b?(a.end.row=b,a.end.column=this.doc.getLine(b).length):a.end.column=this.$clipColumnToRow(a.end.row,a.end.column),a},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(a){if(a!=this.$useWrapMode){this.$useWrapMode=a,this.$modified=!0,this.$resetRowCache(0);if(a){var b=this.getLength();this.$wrapData=[];for(var c=0;c0?(this.$wrapLimit=b,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._emit("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(a){var b=this.$wrapLimitRange.min;b&&(a=Math.max(b,a));var c=this.$wrapLimitRange.max;return c&&(a=Math.min(c,a)),Math.max(1,a)},this.getWrapLimit=function(){return this.$wrapLimit},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(a){var b=this.$useWrapMode,c,d=a.data.action,e=a.data.range.start.row,f=a.data.range.end.row,g=a.data.range.start,h=a.data.range.end,i=null;d.indexOf("Lines")!=-1?(d=="insertLines"?f=e+a.data.lines.length:f=e,c=a.data.lines?a.data.lines.length:f-e):c=f-e;if(c!=0)if(d.indexOf("remove")!=-1){b&&this.$wrapData.splice(e,c);var j=this.$foldData;i=this.getFoldsInRange(a.data.range),this.removeFolds(i);var k=this.getFoldLine(h.row),l=0;if(k){k.addRemoveChars(h.row,h.column,g.column-h.column),k.shiftRow(-c);var m=this.getFoldLine(e);m&&m!==k&&(m.merge(k),k=m),l=j.indexOf(k)+1}for(l;l=h.row&&k.shiftRow(-c)}f=e}else{var n;if(b){n=[e,0];for(var o=0;o=e&&k.shiftRow(c)}}else{c=Math.abs(a.data.range.start.column-a.data.range.end.column),d.indexOf("remove")!=-1&&(i=this.getFoldsInRange(a.data.range),this.removeFolds(i),c=-c);var k=this.getFoldLine(e);k&&k.addRemoveChars(e,g.column,c)}return b&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),b&&this.$updateWrapData(e,f),i},this.$updateWrapData=function(a,b){var c=this.doc.getAllLines(),d=this.getTabSize(),f=this.$wrapData,i=this.$wrapLimit,j,k,m=a;b=Math.min(b,c.length-1);while(m<=b){k=this.getFoldLine(m,k);if(!k)j=this.$getDisplayTokens(e.stringTrimRight(c[m])),f[m]=this.$computeWrapSplits(j,i,d),m++;else{j=[],k.walk(function(a,b,d,e){var f;if(a){f=this.$getDisplayTokens(a,j.length),f[0]=g;for(var i=1;i=l)j.pop();f[k.start.row]=this.$computeWrapSplits(j,i,d),m=k.end.row+1}}};var b=1,c=2,g=3,h=4,j=9,l=10,m=11,n=12;this.$computeWrapSplits=function(a,b){function i(b){var d=a.slice(e,b),g=d.length;d.join("").replace(/12/g,function(){g-=1}).replace(/2/g,function(){g-=1}),f+=g,c.push(f),e=b}if(a.length==0)return[];var c=[],d=a.length,e=0,f=0;while(d-e>b){var k=e+b;if(a[k]>=l){while(a[k]>=l)k++;i(k);continue}if(a[k]==g||a[k]==h){for(k;k!=e-1;k--)if(a[k]==g)break;if(k>e){i(k);continue}k=e+b;for(k;km&&a[k]m&&a[k]==j)k--;if(k>m){i(++k);continue}k=e+b,i(k)}return c},this.$getDisplayTokens=function(a,d){var e=[],f;d=d||0;for(var g=0;g39&&h<48||h>57&&h<64?e.push(j):h>=4352&&o(h)?e.push(b,c):e.push(b)}return e},this.$getStringScreenWidth=function(a,b,c){if(b==0)return[0,0];b==null&&(b=c+a.length*Math.max(this.getTabSize(),2)),c=c||0;var d,e;for(e=0;e=4352&&o(d)?c+=2:c+=1;if(c>b)break}return[c,e]},this.getRowLength=function(a){return!this.$useWrapMode||!this.$wrapData[a]?1:this.$wrapData[a].length+1},this.getRowHeight=function(a,b){return this.getRowLength(b)*a.lineHeight},this.getScreenLastRowColumn=function(a){return this.documentToScreenColumn(a,this.doc.getLine(a).length)},this.getDocumentLastRowColumn=function(a,b){var c=this.documentToScreenRow(a,b);return this.getScreenLastRowColumn(c)},this.getDocumentLastRowColumnPosition=function(a,b){var c=this.documentToScreenRow(a,b);return this.screenToDocumentPosition(c,Number.MAX_VALUE/10)},this.getRowSplitData=function(a){return this.$useWrapMode?this.$wrapData[a]:undefined},this.getScreenTabSize=function(a){return this.$tabSize-a%this.$tabSize},this.screenToDocumentRow=function(a,b){return this.screenToDocumentPosition(a,b).row},this.screenToDocumentColumn=function(a,b){return this.screenToDocumentPosition(a,b).column},this.screenToDocumentPosition=function(a,b){if(a<0)return{row:0,column:0};var c,d=0,e=0,f,g=0,h=0,i=this.$rowCache;for(var j=0;j=a||d>=l)break;g+=h,d++,d>n&&(d=m.end.row+1,m=this.getNextFoldLine(d,m),n=m?m.start.row:Infinity),k&&i.push({docRow:d,screenRow:g})}if(m&&m.start.row<=d)c=this.getFoldDisplayLine(m),d=m.start.row;else{if(g+h<=a||d>l)return{row:l,column:this.getLine(l).length};c=this.getLine(d),m=null}if(this.$useWrapMode){var o=this.$wrapData[d];o&&(f=o[a-g],a>g&&o.length&&(e=o[a-g-1]||o[o.length-1],c=c.substring(e)))}return e+=this.$getStringScreenWidth(c,b)[1],this.$useWrapMode?e>=f&&(e=f-1):e=Math.min(e,c.length),m?m.idxToPosition(e):{row:d,column:e}},this.documentToScreenPosition=function(a,b){if(typeof b=="undefined")var c=this.$clipPositionToDocument(a.row,a.column);else c=this.$clipPositionToDocument(a,b);a=c.row,b=c.column;var d;if(this.$useWrapMode){d=this.$wrapData;if(a>d.length-1)return{row:this.getScreenLength(),column:d.length==0?0:d[d.length-1].length-1}}var e=0,f=null,g=null;g=this.getFoldAt(a,b,1),g&&(a=g.start.row,b=g.start.column);var h,i=0,j=this.$rowCache;for(var k=0;k=n){h=m.end.row+1;if(h>a)break;m=this.getNextFoldLine(h,m),n=m?m.start.row:Infinity}else h=i+1;e+=this.getRowLength(i),i=h,l&&j.push({docRow:i,screenRow:e})}var o="";m&&i>=n?(o=this.getFoldDisplayLine(m,a,b),f=m.start.row):(o=this.getLine(a).substring(0,b),f=a);if(this.$useWrapMode){var p=d[f],q=0;while(o.length>=p[q])e++,q++;o=o.substring(p[q-1]||0,o.length)}return{row:e,column:this.$getStringScreenWidth(o)[0]}},this.documentToScreenColumn=function(a,b){return this.documentToScreenPosition(a,b).column},this.documentToScreenRow=function(a,b){return this.documentToScreenPosition(a,b).row},this.getScreenLength=function(){var a=0,b=null;if(!this.$useWrapMode){a=this.getLength();var c=this.$foldData;for(var d=0;dg&&(f=b.end.row+1,b=this.$foldData[d++],g=b?b.start.row:Infinity)}return a}})).call(l.prototype),a("./edit_session/folding").Folding.call(l.prototype),a("./edit_session/bracket_match").BracketMatch.call(l.prototype),b.EditSession=l}),define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/event_emitter").EventEmitter,g=a("./range").Range,h=function(a){this.session=a,this.doc=a.getDocument(),this.clearSelection(),this.selectionLead=this.doc.createAnchor(0,0),this.selectionAnchor=this.doc.createAnchor(0,0);var b=this;this.selectionLead.on("change",function(a){b._emit("changeCursor"),b.$isEmpty||b._emit("changeSelection"),!b.$preventUpdateDesiredColumnOnChange&&a.old.column!=a.value.column&&b.$updateDesiredColumn()}),this.selectionAnchor.on("change",function(){b.$isEmpty||b._emit("changeSelection")})};((function(){d.implement(this,f),this.isEmpty=function(){return this.$isEmpty||this.selectionAnchor.row==this.selectionLead.row&&this.selectionAnchor.column==this.selectionLead.column},this.isMultiLine=function(){return this.isEmpty()?!1:this.getRange().isMultiLine()},this.getCursor=function(){return this.selectionLead.getPosition()},this.setSelectionAnchor=function(a,b){this.selectionAnchor.setPosition(a,b),this.$isEmpty&&(this.$isEmpty=!1,this._emit("changeSelection"))},this.getSelectionAnchor=function(){return this.$isEmpty?this.getSelectionLead():this.selectionAnchor.getPosition()},this.getSelectionLead=function(){return this.selectionLead.getPosition()},this.shiftSelection=function(a){if(this.$isEmpty){this.moveCursorTo(this.selectionLead.row,this.selectionLead.column+a);return}var b=this.getSelectionAnchor(),c=this.getSelectionLead(),d=this.isBackwards();(!d||b.column!==0)&&this.setSelectionAnchor(b.row,b.column+a),(d||c.column!==0)&&this.$moveSelection(function(){this.moveCursorTo(c.row,c.column+a)})},this.isBackwards=function(){var a=this.selectionAnchor,b=this.selectionLead;return a.row>b.row||a.row==b.row&&a.column>b.column},this.getRange=function(){var a=this.selectionAnchor,b=this.selectionLead;return this.isEmpty()?g.fromPoints(b,b):this.isBackwards()?g.fromPoints(b,a):g.fromPoints(a,b)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var a=this.doc.getLength()-1;this.setSelectionAnchor(a,this.doc.getLine(a).length),this.moveCursorTo(0,0)},this.setSelectionRange=function(a,b){b?(this.setSelectionAnchor(a.end.row,a.end.column),this.selectTo(a.start.row,a.start.column)):(this.setSelectionAnchor(a.start.row,a.start.column),this.selectTo(a.end.row,a.end.column)),this.$updateDesiredColumn()},this.$updateDesiredColumn=function(){var a=this.getCursor();this.$desiredColumn=this.session.documentToScreenColumn(a.row,a.column)},this.$moveSelection=function(a){var b=this.selectionLead;this.$isEmpty&&this.setSelectionAnchor(b.row,b.column),a.call(this)},this.selectTo=function(a,b){this.$moveSelection(function(){this.moveCursorTo(a,b)})},this.selectToPosition=function(a){this.$moveSelection(function(){this.moveCursorToPosition(a)})},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.selectWord=function(){var a=this.getCursor(),b=this.session.getWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectAWord=function(){var a=this.getCursor(),b=this.session.getAWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectLine=function(){var a=this.selectionLead.row,b,c=this.session.getFoldLine(a);c?(a=c.start.row,b=c.end.row):b=a,this.setSelectionAnchor(a,0),this.$moveSelection(function(){this.moveCursorTo(b+1,0)})},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,-1))this.moveCursorTo(b.start.row,b.start.column);else if(a.column==0)a.row>0&&this.moveCursorTo(a.row-1,this.doc.getLine(a.row-1).length);else{var c=this.session.getTabSize();this.session.isTabStop(a)&&this.doc.getLine(a.row).slice(a.column-c,a.column).split(" ").length-1==c?this.moveCursorBy(0,-c):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,1))this.moveCursorTo(b.end.row,b.end.column);else if(this.selectionLead.column==this.doc.getLine(this.selectionLead.row).length)this.selectionLead.row=c.length){this.moveCursorTo(a,c.length),this.moveCursorRight(),a0&&this.moveCursorWordLeft();return}if(g=this.session.tokenRe.exec(f))b-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(a,b)},this.moveCursorBy=function(a,b){var c=this.session.documentToScreenPosition(this.selectionLead.row,this.selectionLead.column),d=b===0&&this.$desiredColumn||c.column,e=this.session.screenToDocumentPosition(c.row+a,d);this.moveCursorTo(e.row,e.column+b,b===0)},this.moveCursorToPosition=function(a){this.moveCursorTo(a.row,a.column)},this.moveCursorTo=function(a,b,c){var d=this.session.getFoldAt(a,b,1);d&&(a=d.start.row,b=d.start.column),this.$preventUpdateDesiredColumnOnChange=!0,this.selectionLead.setPosition(a,b),this.$preventUpdateDesiredColumnOnChange=!1,c||this.$updateDesiredColumn(this.selectionLead.column)},this.moveCursorToScreen=function(a,b,c){var d=this.session.screenToDocumentPosition(a,b);a=d.row,b=d.column,this.moveCursorTo(a,b,c)}})).call(h.prototype),b.Selection=h}),define("ace/range",["require","exports","module"],function(a,b,c){"use strict";var d=function(a,b,c,d){this.start={row:a,column:b},this.end={row:c,column:d}};((function(){this.isEequal=function(a){return this.start.row==a.start.row&&this.end.row==a.end.row&&this.start.column==a.start.column&&this.end.column==a.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(a,b){return this.compare(a,b)==0},this.compareRange=function(a){var b,c=a.end,d=a.start;return b=this.compare(c.row,c.column),b==1?(b=this.compare(d.row,d.column),b==1?2:b==0?1:0):b==-1?-2:(b=this.compare(d.row,d.column),b==-1?-1:b==1?42:0)},this.comparePoint=function(a){return this.compare(a.row,a.column)},this.containsRange=function(a){return this.comparePoint(a.start)==0&&this.comparePoint(a.end)==0},this.isEnd=function(a,b){return this.end.row==a&&this.end.column==b},this.isStart=function(a,b){return this.start.row==a&&this.start.column==b},this.setStart=function(a,b){typeof a=="object"?(this.start.column=a.column,this.start.row=a.row):(this.start.row=a,this.start.column=b)},this.setEnd=function(a,b){typeof a=="object"?(this.end.column=a.column,this.end.row=a.row):(this.end.row=a,this.end.column=b)},this.inside=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)||this.isStart(a,b)?!1:!0:!1},this.insideStart=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)?!1:!0:!1},this.insideEnd=function(a,b){return this.compare(a,b)==0?this.isStart(a,b)?!1:!0:!1},this.compare=function(a,b){return!this.isMultiLine()&&a===this.start.row?bthis.end.column?1:0:athis.end.row?1:this.start.row===a?b>=this.start.column?0:-1:this.end.row===a?b<=this.end.column?0:1:0},this.compareStart=function(a,b){return this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.compareEnd=function(a,b){return this.end.row==a&&this.end.column==b?1:this.compare(a,b)},this.compareInside=function(a,b){return this.end.row==a&&this.end.column==b?1:this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.clipRows=function(a,b){if(this.end.row>b)var c={row:b+1,column:0};if(this.start.row>b)var e={row:b+1,column:0};if(this.start.row=0&&/^[\w\d]/.test(h)||e<=g&&/[\w\d]$/.test(h))return;h=f.substring(c.start.column,c.end.column);if(!/^[\w\d]+$/.test(h))return;var i=a.getCursorPosition(),j={wrap:!0,wholeWord:!0,caseSensitive:!0,needle:h},k=a.$search.getOptions();a.$search.set(j);var l=a.$search.findAll(b);l.forEach(function(a){if(!a.contains(i.row,i.column)){var c=b.addMarker(a,"ace_selected_word","text");b.$selectionOccurrences.push(c)}}),a.$search.set(k)},this.clearSelectionHighlight=function(a){if(!a.session.$selectionOccurrences)return;a.session.$selectionOccurrences.forEach(function(b){a.session.removeMarker(b)}),a.session.$selectionOccurrences=[]},this.createModeDelegates=function(a){if(!this.$embeds)return;this.$modes={};for(var b=0;b1&&(m=g.slice(n+2,n+1+e[n].len)),typeof l.token=="function"?k=l.token.apply(this,m):k=l.token;var o=l.next;o&&o!==c&&(c=o,d=this.rules[c],e=this.matchMappings[c],i=f.lastIndex,f=this.regExps[c],f.lastIndex=i);break}if(m[0]){typeof k=="string"&&(m=[m.join("")],k=[k]);for(var n=0;n=b&&(a.row=Math.max(0,b-1),a.column=this.getLine(b-1).length),a},this.insert=function(a,b){if(b.length==0)return a;a=this.$clipPosition(a),this.getLength()<=1&&this.$detectNewLine(b);var c=this.$split(b),d=c.splice(0,1)[0],e=c.length==0?null:c.splice(c.length-1,1)[0];return a=this.insertInLine(a,d),e!==null&&(a=this.insertNewLine(a),a=this.insertLines(a.row,c),a=this.insertInLine(a,e||"")),a},this.insertLines=function(a,b){if(b.length==0)return{row:a,column:0};var c=[a,0];c.push.apply(c,b),this.$lines.splice.apply(this.$lines,c);var d=new f(a,0,a+b.length,0),e={action:"insertLines",range:d,lines:b};return this._emit("change",{data:e}),d.end},this.insertNewLine=function(a){a=this.$clipPosition(a);var b=this.$lines[a.row]||"";this.$lines[a.row]=b.substring(0,a.column),this.$lines.splice(a.row+1,0,b.substring(a.column,b.length));var c={row:a.row+1,column:0},d={action:"insertText",range:f.fromPoints(a,c),text:this.getNewLineCharacter()};return this._emit("change",{data:d}),c},this.insertInLine=function(a,b){if(b.length==0)return a;var c=this.$lines[a.row]||"";this.$lines[a.row]=c.substring(0,a.column)+b+c.substring(a.column);var d={row:a.row,column:a.column+b.length},e={action:"insertText",range:f.fromPoints(a,d),text:b};return this._emit("change",{data:e}),d},this.remove=function(a){a.start=this.$clipPosition(a.start),a.end=this.$clipPosition(a.end);if(a.isEmpty())return a.start;var b=a.start.row,c=a.end.row;if(a.isMultiLine()){var d=a.start.column==0?b:b+1,e=c-1;a.end.column>0&&this.removeInLine(c,0,a.end.column),e>=d&&this.removeLines(d,e),d!=b&&(this.removeInLine(b,a.start.column,this.getLine(b).length),this.removeNewLine(a.start.row))}else this.removeInLine(b,a.start.column,a.end.column);return a.start},this.removeInLine=function(a,b,c){if(b==c)return;var d=new f(a,b,a,c),e=this.getLine(a),g=e.substring(b,c),h=e.substring(0,b)+e.substring(c,e.length);this.$lines.splice(a,1,h);var i={action:"removeText",range:d,text:g};return this._emit("change",{data:i}),d.start},this.removeLines=function(a,b){var c=new f(a,0,b+1,0),d=this.$lines.splice(a,b-a+1),e={action:"removeLines",range:c,nl:this.getNewLineCharacter(),lines:d};return this._emit("change",{data:e}),d},this.removeNewLine=function(a){var b=this.getLine(a),c=this.getLine(a+1),d=new f(a,b.length,a+1,0),e=b+c;this.$lines.splice(a,2,e);var g={action:"removeText",range:d,text:this.getNewLineCharacter()};this._emit("change",{data:g})},this.replace=function(a,b){if(b.length==0&&a.isEmpty())return a.start;if(b==this.getTextRange(a))return a.end;this.remove(a);if(b)var c=this.insert(a.start,b);else c=a.start;return c},this.applyDeltas=function(a){for(var b=0;b=0;b--){var c=a[b],d=f.fromPoints(c.range.start,c.range.end);c.action=="insertLines"?this.removeLines(d.start.row,d.end.row-1):c.action=="insertText"?this.remove(d):c.action=="removeLines"?this.insertLines(d.start.row,c.lines):c.action=="removeText"&&this.insert(d.start,c.text)}}})).call(h.prototype),b.Document=h}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=b.Anchor=function(a,b,c){this.document=a,typeof c=="undefined"?this.setPosition(b.row,b.column):this.setPosition(b,c),this.$onChange=this.onChange.bind(this),a.on("change",this.$onChange)};((function(){d.implement(this,e),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.onChange=function(a){var b=a.data,c=b.range;if(c.start.row==c.end.row&&c.start.row!=this.row)return;if(c.start.row>this.row)return;if(c.start.row==this.row&&c.start.column>this.column)return;var d=this.row,e=this.column;b.action==="insertText"?c.start.row===d&&c.start.column<=e?c.start.row===c.end.row?e+=c.end.column-c.start.column:(e-=c.start.column,d+=c.end.row-c.start.row):c.start.row!==c.end.row&&c.start.row=e?e=c.start.column:e=Math.max(0,e-(c.end.column-c.start.column)):c.start.row!==c.end.row&&c.start.row=this.document.getLength()?(c.row=Math.max(0,this.document.getLength()-1),c.column=this.document.getLine(c.row).length):a<0?(c.row=0,c.column=0):(c.row=a,c.column=Math.min(this.document.getLine(c.row).length,Math.max(0,b))),b<0&&(c.column=0),c}})).call(f.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=function(a,b){this.running=!1,this.lines=[],this.currentLine=0,this.tokenizer=a;var c=this;this.$worker=function(){if(!c.running)return;var a=new Date,b=c.currentLine,d=c.doc,e=0,f=d.getLength();while(c.currentLine20){c.fireUpdateEvent(b,c.currentLine-1),c.running=setTimeout(c.$worker,20);return}}c.running=!1,c.fireUpdateEvent(b,f-1)}};((function(){d.implement(this,e),this.setTokenizer=function(a){this.tokenizer=a,this.lines=[],this.start(0)},this.setDocument=function(a){this.doc=a,this.lines=[],this.stop()},this.fireUpdateEvent=function(a,b){var c={first:a,last:b};this._emit("update",{data:c})},this.start=function(a){this.currentLine=Math.min(a||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(a,b){return this.$tokenizeRows(a,b)},this.getState=function(a){return this.$tokenizeRows(a,a)[0].state},this.$tokenizeRows=function(a,b){if(!this.doc||isNaN(a)||isNaN(b))return[{state:"start",tokens:[]}];var c=[],d="start",e=!1;a>0&&this.lines[a-1]?(d=this.lines[a-1].state,e=!0):a==0?(d="start",e=!0):this.lines.length>0&&(d=this.lines[this.lines.length-1].state);var f=this.doc.getLines(a,b);for(var g=a;g<=b;g++)if(!this.lines[g]){var h=this.tokenizer.getLineTokens(f[g-a]||"",d),d=h.state;c.push(h),e&&(this.lines[g]=h)}else{var h=this.lines[g];d=h.state,c.push(h)}return c}})).call(f.prototype),b.BackgroundTokenizer=f}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(a,b,c){function h(){this.getFoldAt=function(a,b,c){var d=this.getFoldLine(a);if(!d)return null;var e=d.folds;for(var f=0;f=a)return e;if(e.end.row>a)return null}return null},this.getNextFoldLine=function(a,b){var c=this.$foldData,d=0;b&&(d=c.indexOf(b)),d==-1&&(d=0);for(d;d=a)return e}return null},this.getFoldedRowCount=function(a,b){var c=this.$foldData,d=b-a+1;for(var e=0;e=b){h=a?d-=b-h:d=0);break}g>=a&&(h>=a?d-=g-h:d-=g-a+1)}return d},this.$addFoldLine=function(a){return this.$foldData.push(a),this.$foldData.sort(function(a,b){return a.start.row-b.start.row}),a},this.addFold=function(a,b){var c=this.$foldData,d=!1,g;a instanceof f?g=a:g=new f(b,a),this.$clipRangeToDocument(g.range);var h=g.start.row,i=g.start.column,j=g.end.row,k=g.end.column;if(g.placeholder.length<2)throw"Placeholder has to be at least 2 characters";if(h==j&&k-i<2)throw"The range has to be at least 2 characters width";var l=this.getFoldAt(h,i,1),m=this.getFoldAt(j,k,-1);if(l&&m==l)return l.addSubFold(g);if(l&&!l.range.isStart(h,i)||m&&!m.range.isEnd(j,k))throw"A fold can't intersect already existing fold"+g.range+l.range;var n=this.getFoldsInRange(g.range);n.length>0&&(this.removeFolds(n),g.subFolds=n);for(var o=0;othis.endRow)throw"Can't add a fold to this FoldLine as it has no connection";this.folds.push(a),this.folds.sort(function(a,b){return-a.range.compareEnd(b.start.row,b.start.column)}),this.range.compareEnd(a.start.row,a.start.column)>0?(this.end.row=a.end.row,this.end.column=a.end.column):this.range.compareStart(a.end.row,a.end.column)<0&&(this.start.row=a.start.row,this.start.column=a.start.column)}else if(a.start.row==this.end.row)this.folds.push(a),this.end.row=a.end.row,this.end.column=a.end.column;else if(a.end.row==this.start.row)this.folds.unshift(a),this.start.row=a.start.row,this.start.column=a.start.column;else throw"Trying to add fold to FoldRow that doesn't have a matching row";a.foldLine=this},this.containsRow=function(a){return a>=this.start.row&&a<=this.end.row},this.walk=function(a,b,c){var d=0,e=this.folds,f,g,h,i=!0;b==null&&(b=this.end.row,c=this.end.column);for(var j=0;j=this.$rowTokens.length){this.$row+=1;if(this.$row>=a)return this.$row=a-1,null;this.$rowTokens=this.$session.getTokens(this.$row,this.$row)[0].tokens,this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var a=this.$rowTokens,b=this.$tokenIndex,c=a[b].start;if(c!==undefined)return c;c=0;while(b>0)b-=1,c+=a[b].value.length;return c}})).call(d.prototype),b.TokenIterator=d}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator"],function(a,b,c){function e(){this.findMatchingBracket=function(a){if(a.column==0)return null;var b=this.getLine(a.row).charAt(a.column-1);if(b=="")return null;var c=b.match(/([\(\[\{])|([\)\]\}])/);return c?c[1]?this.$findClosingBracket(c[1],a):this.$findOpeningBracket(c[2],a):null},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("rparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn()-2,j=g.value;for(;;){while(i>=0){var k=j.charAt(i);if(k==c){e-=1;if(e==0)return{row:f.getCurrentTokenRow(),column:i+f.getCurrentTokenColumn()}}else k==a&&(e+=1);i-=1}do g=f.stepBackward();while(g&&!h.test(g.type));if(g==null)break;j=g.value,i=j.length-1}return null},this.$findClosingBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("lparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn();for(;;){var j=g.value,k=j.length;while(i=0;h--){var i=g[h],j=c.$rangeFromMatch(f,i.offset,i.str.length);if(d(j))return!0}})}}},this.$rangeFromMatch=function(a,b,c){return new f(a,b,a,b+c)},this.$assembleRegExp=function(){if(this.$options.regExp)var a=this.$options.needle;else a=d.escapeRegExp(this.$options.needle);this.$options.wholeWord&&(a="\\b"+a+"\\b");var b="g";this.$options.caseSensitive||(b+="i");var c=new RegExp(a,b);return c},this.$forwardLineIterator=function(a){function k(e){var f=a.getLine(e);return b&&e==c.end.row&&(f=f.substring(0,c.end.column)),j&&e==d.row&&(f=f.substring(0,d.column)),f}var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"start":"end"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap,j=!1;return{forEach:function(a){var b=d.row,c=k(b),g=d.column,l=!1;j=!1;while(!a(c,g,b)){if(l)return;b++,g=0;if(b>h)if(i)b=e,g=f,j=!0;else return;b==d.row&&(l=!0),c=k(b)}}}},this.$backwardLineIterator=function(a){var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"end":"start"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap;return{forEach:function(g){var j=d.row,k=a.getLine(j).substring(0,d.column),l=0,m=!1,n=!1;while(!g(k,l,j)){if(m)return;j--,l=0;if(j0},this.hasRedo=function(){return this.$redoStack.length>0}})).call(d.prototype),b.UndoManager=d}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/lib/event_emitter","text!ace/css/editor.css"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/useragent"),h=a("./layer/gutter").Gutter,i=a("./layer/marker").Marker,j=a("./layer/text").Text,k=a("./layer/cursor").Cursor,l=a("./scrollbar").ScrollBar,m=a("./renderloop").RenderLoop,n=a("./lib/event_emitter").EventEmitter,o=a("text!./css/editor.css");e.importCssString(o,"ace_editor");var p=function(a,b){var c=this;this.container=a,e.addCssClass(a,"ace_editor"),this.setTheme(b),this.$gutter=e.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=e.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=e.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new h(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onResize.bind(this,!0)),this.$markerBack=new i(this.content);var d=this.$textLayer=new j(this.content);this.canvas=d.element,this.$markerFront=new i(this.content),this.characterWidth=d.getCharacterWidth(),this.lineHeight=d.getLineHeight(),this.$cursorLayer=new k(this.content),this.$cursorPadding=8,this.$horizScroll=!0,this.$horizScrollAlwaysVisible=!0,this.scrollBar=new l(a),this.scrollBar.addEventListener("scroll",function(a){c.session.setScrollTop(a.data)}),this.scrollTop=0,this.scrollLeft=0,f.addListener(this.scroller,"scroll",function(){c.session.setScrollLeft(c.scroller.scrollLeft)}),this.cursorPos={row:0,column:0},this.$textLayer.addEventListener("changeCharaterSize",function(){c.characterWidth=d.getCharacterWidth(),c.lineHeight=d.getLineHeight(),c.$updatePrintMargin(),c.onResize(!0),c.$loop.schedule(c.CHANGE_FULL)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:1,characterWidth:1,minHeight:1,maxHeight:1,offset:0,height:1},this.$loop=new m(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.setPadding(4),this.$updatePrintMargin()};((function(){this.showGutter=!0,this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,d.implement(this,n),this.setSession=function(a){this.session=a,this.$cursorLayer.setSession(a),this.$markerBack.setSession(a),this.$markerFront.setSession(a),this.$gutterLayer.setSession(a),this.$textLayer.setSession(a),this.$loop.schedule(this.CHANGE_FULL)},this.updateLines=function(a,b){b===undefined&&(b=Infinity),this.$changedLines?(this.$changedLines.firstRow>a&&(this.$changedLines.firstRow=a),this.$changedLines.lastRowc.lastRow+1)return;if(bc&&this.session.setScrollTop(c),this.scrollTop+this.$size.scrollerHeightb&&(bthis.layerConfig.width+2*this.$padding?this.$desiredScrollLeft=b:this.scrollToX(Math.round(b+this.characterWidth-this.$size.scrollerWidth)))},this.getScrollTop=function(){return this.session.getScrollTop()},this.getScrollLeft=function(){return this.session.getScrollTop()},this.getScrollTopRow=function(){return this.scrollTop/this.lineHeight},this.getScrollBottomRow=function(){return Math.max(0,Math.floor((this.scrollTop+this.$size.scrollerHeight)/this.lineHeight)-1)},this.scrollToRow=function(a){this.session.setScrollTop(a*this.lineHeight)},this.scrollToLine=function(a,b){var c={lineHeight:this.lineHeight},d=0;for(var e=1;e0)return!0;if(b>0&&this.session.getScrollTop()+this.$size.scrollerHeighth&&(e=g.end.row+1,g=this.session.getNextFoldLine(e,g),h=g?g.start.row:Infinity);if(e>f)break;var j=this.$annotations[e]||b;c.push("
    ",e+1);if(i){var k=i[e];k==null&&(k=i[e]=this.session.getFoldWidget(e)),k&&c.push("")}var l=this.session.getRowLength(e)-1;while(l--)c.push("
    ¦");c.push("
    "),e++}this.element=d.setInnerHtml(this.element,c.join("")),this.element.style.height=a.minHeight+"px";var m=this.element.offsetWidth;m!==this.gutterWidth&&(this.gutterWidth=m,this._emit("changeGutterWidth",m))},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(a){a?d.addCssClass(this.element,"ace_folding-enabled"):d.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=a},this.getShowFoldWidgets=function(){return this.$showFoldWidgets}})).call(g.prototype),b.Gutter=g}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../range").Range,e=a("../lib/dom"),f=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_marker-layer",a.appendChild(this.element)};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.setMarkers=function(a){this.markers=a},this.update=function(a){var a=a||this.config;if(!a)return;this.config=a;var b=[];for(var c in this.markers){var d=this.markers[c],f=d.range.clipRows(a.firstRow,a.lastRow);if(f.isEmpty())continue;f=f.toScreenRange(this.session);if(d.renderer){var g=this.$getTop(f.start.row,a),h=Math.round(this.$padding+f.start.column*a.characterWidth);d.renderer(b,f,h,g,a)}else f.isMultiLine()?d.type=="text"?this.drawTextMarker(b,f,d.clazz,a):this.drawMultiLineMarker(b,f,d.clazz,a,d.type):this.drawSingleLineMarker(b,f,d.clazz,a,null,d.type)}this.element=e.setInnerHtml(this.element,b.join(""))},this.$getTop=function(a,b){return(a-b.firstRowScreen)*b.lineHeight},this.drawTextMarker=function(a,b,c,e){var f=b.start.row,g=new d(f,b.start.column,f,this.session.getScreenLastRowColumn(f));this.drawSingleLineMarker(a,g,c,e,1,"text"),f=b.end.row,g=new d(f,0,f,b.end.column),this.drawSingleLineMarker(a,g,c,e,0,"text");for(f=b.start.row+1;f"),j=this.$getTop(b.end.row,d),i=Math.round(b.end.column*d.characterWidth),a.push("
    "),h=(b.end.row-b.start.row-1)*d.lineHeight;if(h<0)return;j=this.$getTop(b.start.row+1,d),a.push("
    ")},this.drawSingleLineMarker=function(a,b,c,d,e,f){var g=f==="background"?0:this.$padding,h=d.lineHeight;if(f==="background")var i=d.width;else i=Math.round((b.end.column+(e||0)-b.start.column)*d.characterWidth);var j=this.$getTop(b.start.row,d),k=Math.round(g+b.start.column*d.characterWidth);a.push("
    ")}})).call(f.prototype),b.Marker=f}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/dom"),f=a("../lib/lang"),g=a("../lib/useragent"),h=a("../lib/event_emitter").EventEmitter,i=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_text-layer",a.appendChild(this.element),this.$characterSize=this.$measureSizes()||{width:0,height:0},this.$pollSizeChanges()};((function(){d.implement(this,h),this.EOF_CHAR="¶",this.EOL_CHAR="¬",this.TAB_CHAR="→",this.SPACE_CHAR="·",this.$padding=0,this.setPadding=function(a){this.$padding=a,this.element.style.padding="0 "+a+"px"},this.getLineHeight=function(){return this.$characterSize.height||1},this.getCharacterWidth=function(){return this.$characterSize.width||1},this.checkForSizeChanges=function(){var a=this.$measureSizes();a&&(this.$characterSize.width!==a.width||this.$characterSize.height!==a.height)&&(this.$characterSize=a,this._emit("changeCharaterSize",{data:a}))},this.$pollSizeChanges=function(){var a=this;this.$pollSizeChangesTimer=setInterval(function(){a.checkForSizeChanges()},500)},this.$fontStyles={fontFamily:1,fontSize:1,fontWeight:1,fontStyle:1,lineHeight:1},this.$measureSizes=function(){var a=1e3;if(!this.$measureNode){var b=this.$measureNode=e.createElement("div"),c=b.style;c.width=c.height="auto",c.left=c.top=-a*40+"px",c.visibility="hidden",c.position="absolute",c.overflow="visible",c.whiteSpace="nowrap",b.innerHTML=f.stringRepeat("Xy",a);if(this.element.ownerDocument.body)this.element.ownerDocument.body.appendChild(b);else{var d=this.element.parentNode;while(!e.hasCssClass(d,"ace_editor"))d=d.parentNode;d.appendChild(b)}}var c=this.$measureNode.style,g=e.computedStyle(this.element);for(var h in this.$fontStyles)c[h]=g[h];var i={height:this.$measureNode.offsetHeight,width:this.$measureNode.offsetWidth/(a*2)};return i.width==0&&i.height==0?null:i},this.setSession=function(a){this.session=a},this.showInvisibles=!1,this.setShowInvisibles=function(a){return this.showInvisibles==a?!1:(this.showInvisibles=a,!0)},this.$tabStrings=[],this.$computeTabString=function(){var a=this.session.getTabSize(),b=this.$tabStrings=[0];for(var c=1;c"+this.TAB_CHAR+(new Array(c)).join(" ")+""):b.push((new Array(c+1)).join(" "))},this.updateLines=function(a,b,c){this.$computeTabString(),(this.config.lastRow!=a.lastRow||this.config.firstRow!=a.firstRow)&&this.scrollLines(a),this.config=a;var d=Math.max(b,a.firstRow),f=Math.min(c,a.lastRow),g=this.element.childNodes,h=0;for(var i=a.firstRow;i0;d--)c.removeChild(c.firstChild);if(b.lastRow>a.lastRow)for(var d=this.session.getFoldedRowCount(a.lastRow+1,b.lastRow);d>0;d--)c.removeChild(c.lastChild);if(a.firstRowb.lastRow){var e=this.$renderLinesFragment(a,b.lastRow+1,a.lastRow);c.appendChild(e)}},this.$renderLinesFragment=function(a,b,c){var d=this.element.ownerDocument.createDocumentFragment(),f=b,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>c)break;var i=e.createElement("div"),j=[],k=this.session.getTokens(f,f);k.length==1&&this.$renderLine(j,f,k[0].tokens,!1),i.innerHTML=j.join("");if(this.$useLineGroups())i.className="ace_line_group",d.appendChild(i);else{var l=i.childNodes;while(l.length)d.appendChild(l[0])}f++}return d},this.update=function(a){this.$computeTabString(),this.config=a;var b=[],c=a.firstRow,d=a.lastRow,f=c,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>d)break;this.$useLineGroups()&&b.push("
    ");var i=this.session.getTokens(f,f);i.length==1&&this.$renderLine(b,f,i[0].tokens,!1),this.$useLineGroups()&&b.push("
    "),f++}this.element=e.setInnerHtml(this.element,b.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(a,b,c,d){var e=this,f=/\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g,h=function(a,c,d,f,h){if(a.charCodeAt(0)==32)return(new Array(a.length+1)).join(" ");if(a=="\t"){var i=e.session.getScreenTabSize(b+f);return b+=i-1,e.$tabStrings[i]}if(a=="&")return g.isOldGecko?"&":"&";if(a=="<")return"<";if(a==" "){var j=e.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",k=e.showInvisibles?e.SPACE_CHAR:"";return b+=1,""+k+""}if(a.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)){if(e.showInvisibles){var k=(new Array(a.length+1)).join(e.SPACE_CHAR);return""+k+""}return" "}return b+=1,""+a+""},i=d.replace(f,h);if(!this.$textToken[c.type]){var j="ace_"+c.type.replace(/\./g," ace_"),k="";c.type=="fold"&&(k=" style='width:"+c.value.length*this.config.characterWidth+"px;' "),a.push("",i,"")}else a.push(i);return b+d.length},this.$renderLineCore=function(a,b,c,d,e){var f=0,g=0,h,i=0,j=this;!d||d.length==0?h=Number.MAX_VALUE:h=d[0],e||a.push("
    ");for(var k=0;k=h)i=j.$renderToken(a,i,l,m.substring(0,h-f)),m=m.substring(h-f),f=h,e||a.push("
    ","
    "),g++,i=0,h=d[g]||Number.MAX_VALUE;m.length!=0&&(f+=m.length,i=j.$renderToken(a,i,l,m))}}this.showInvisibles&&(b!==this.session.getLength()-1?a.push(""+this.EOL_CHAR+""):a.push(""+this.EOF_CHAR+"")),e||a.push("
    ")},this.$renderLine=function(a,b,c,d){if(!this.session.isRowFolded(b)){var e=this.session.getRowSplitData(b);this.$renderLineCore(a,b,c,e,d)}else this.$renderFoldLine(a,b,c,d)},this.$renderFoldLine=function(a,b,c,d){function h(a,b,c){var d=0,e=0;while(e+a[d].value.lengthc-b&&(f=f.substring(0,c-b)),g.push({type:a[d].type,value:f}),e=b+f.length,d+=1}while(ec&&(f=f.substring(0,c-e)),g.push({type:a[d].type,value:f}),e+=f.length,d+=1}}var e=this.session,f=e.getFoldLine(b),g=[];f.walk(function(a,b,d,e,f){a?g.push({type:"fold",value:a}):(f&&(c=this.session.getTokens(b,b)[0].tokens),c.length!=0&&h(c,e,d))}.bind(this),f.end.row,this.session.getLine(f.end.row).length);var i=this.session.$useWrapMode?this.session.$wrapData[b]:null;this.$renderLineCore(a,b,g,i,d)},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}})).call(i.prototype),b.Text=i}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../lib/dom"),e=function(a){this.element=d.createElement("div"),this.element.className="ace_layer ace_cursor-layer",a.appendChild(this.element),this.cursor=d.createElement("div"),this.cursor.className="ace_cursor ace_hidden",this.element.appendChild(this.cursor),this.isVisible=!1};((function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.hideCursor=function(){this.isVisible=!1,d.addCssClass(this.cursor,"ace_hidden"),clearInterval(this.blinkId)},this.showCursor=function(){this.isVisible=!0,d.removeCssClass(this.cursor,"ace_hidden"),this.cursor.style.visibility="visible",this.restartTimer()},this.restartTimer=function(){clearInterval(this.blinkId);if(!this.isVisible)return;var a=this.cursor;this.blinkId=setInterval(function(){a.style.visibility="hidden",setTimeout(function(){a.style.visibility="visible"},400)},1e3)},this.getPixelPosition=function(a){if(!this.config||!this.session)return{left:0,top:0};var b=this.session.selection.getCursor(),c=this.session.documentToScreenPosition(b),d=Math.round(this.$padding+c.column*this.config.characterWidth),e=(c.row-(a?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:d,top:e}},this.update=function(a){this.config=a,this.pixelPos=this.getPixelPosition(!0),this.cursor.style.left=this.pixelPos.left+"px",this.cursor.style.top=this.pixelPos.top+"px",this.cursor.style.width=a.characterWidth+"px",this.cursor.style.height=a.lineHeight+"px";var b=this.session.getOverwrite();b!=this.overwrite&&(this.overwrite=b,b?d.addCssClass(this.cursor,"ace_overwrite"):d.removeCssClass(this.cursor,"ace_overwrite")),this.restartTimer()},this.destroy=function(){clearInterval(this.blinkId)}})).call(e.prototype),b.Cursor=e}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/event_emitter").EventEmitter,h=function(a){this.element=e.createElement("div"),this.element.className="ace_sb",this.inner=e.createElement("div"),this.element.appendChild(this.inner),a.appendChild(this.element),this.width=e.scrollbarWidth(a.ownerDocument),this.element.style.width=(this.width||15)+5+"px",f.addListener(this.element,"scroll",this.onScroll.bind(this))};((function(){d.implement(this,g),this.onScroll=function(){this._emit("scroll",{data:this.element.scrollTop})},this.getWidth=function(){return this.width},this.setHeight=function(a){this.element.style.height=a+"px"},this.setInnerHeight=function(a){this.inner.style.height=a+"px"},this.setScrollTop=function(a){this.element.scrollTop=a}})).call(h.prototype),b.ScrollBar=h}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(a,b,c){"use strict";var d=a("./lib/event"),e=function(a,b){this.onRender=a,this.pending=!1,this.changes=0,this.window=b||window};((function(){this.schedule=function(a){this.changes=this.changes|a;if(!this.pending){this.pending=!0;var b=this;d.nextTick(function(){b.pending=!1;var a;while(a=b.changes)b.changes=0,b.onRender(a)},this.window)}}})).call(e.prototype),b.RenderLoop=e}),define("text!ace/css/editor.css",[],"\n\n\n.ace_editor {\n position: absolute;\n overflow: hidden;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Courier New', monospace;\n font-size: 12px;\n}\n\n.ace_scroller {\n position: absolute;\n overflow-x: scroll;\n overflow-y: hidden;\n}\n\n.ace_content {\n position: absolute;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n cursor: text;\n}\n\n/* setting pointer-events: auto; on node under the mouse, which changes during scroll,\n will break mouse wheel scrolling in Safari */\n.ace_content * {\n pointer-events: none;\n}\n\n.ace_composition {\n position: absolute;\n background: #555;\n color: #DDD;\n z-index: 4;\n}\n\n.ace_gutter .ace_layer {\n position: relative;\n min-width: 54px;\n text-align: right;\n}\n\n.ace_gutter {\n position: absolute;\n overflow : hidden;\n height: 100%;\n width: auto;\n cursor: default;\n}\n\n.ace_gutter-cell {\n padding-left: 19px;\n padding-right: 6px;\n}\n\n.ace_gutter-cell.ace_error {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_warning {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_info {\n background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_editor .ace_sb {\n position: absolute;\n overflow-x: hidden;\n overflow-y: scroll;\n right: 0;\n}\n\n.ace_editor .ace_sb div {\n position: absolute;\n width: 1px;\n left: 0;\n}\n\n.ace_editor .ace_print_margin_layer {\n z-index: 0;\n position: absolute;\n overflow: hidden;\n margin: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.ace_editor .ace_print_margin {\n position: absolute;\n height: 100%;\n}\n\n.ace_editor textarea {\n position: fixed;\n z-index: 0;\n width: 10px;\n height: 30px;\n opacity: 0;\n background: transparent;\n appearance: none;\n -moz-appearance: none;\n border: none;\n resize: none;\n outline: none;\n overflow: hidden;\n}\n\n.ace_layer {\n z-index: 1;\n position: absolute;\n overflow: hidden;\n white-space: nowrap;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_text-layer {\n color: black;\n}\n\n.ace_cjk {\n display: inline-block;\n text-align: center;\n}\n\n.ace_cursor-layer {\n z-index: 4;\n}\n\n.ace_cursor {\n z-index: 4;\n position: absolute;\n}\n\n.ace_cursor.ace_hidden {\n opacity: 0.2;\n}\n\n.ace_line {\n white-space: nowrap;\n}\n\n.ace_marker-layer .ace_step {\n position: absolute;\n z-index: 3;\n}\n\n.ace_marker-layer .ace_selection {\n position: absolute;\n z-index: 4;\n}\n\n.ace_marker-layer .ace_bracket {\n position: absolute;\n z-index: 5;\n}\n\n.ace_marker-layer .ace_active_line {\n position: absolute;\n z-index: 2;\n}\n\n.ace_marker-layer .ace_selected_word {\n position: absolute;\n z-index: 6;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_line .ace_fold {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n \n display: inline-block;\n height: 11px;\n margin-top: -2px;\n vertical-align: middle;\n\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n color: transparent;\n\n border: 1px solid black;\n -moz-border-radius: 2px;\n -webkit-border-radius: 2px;\n border-radius: 2px;\n \n cursor: pointer;\n pointer-events: auto;\n}\n\n.ace_dark .ace_fold {\n}\n\n.ace_fold:hover{\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n}\n\n.ace_dragging .ace_content {\n cursor: move;\n}\n\n.ace_folding-enabled .ace_gutter-cell {\n padding-right: 13px;\n}\n\n.ace_fold-widget {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n\n margin: 0 -12px 1px 1px;\n display: inline-block;\n height: 14px;\n width: 11px;\n vertical-align: text-bottom;\n \n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat;\n background-position: center 5px;\n\n border-radius: 3px;\n}\n\n.ace_fold-widget.end {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget.closed {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget:hover {\n border: 1px solid rgba(0, 0, 0, 0.3);\n background-color: rgba(255, 255, 255, 0.2);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n background-position: center 4px;\n}\n\n.ace_fold-widget:active {\n border: 1px solid rgba(0, 0, 0, 0.4);\n background-color: rgba(0, 0, 0, 0.05);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n}\n\n.ace_fold-widget.invalid {\n background-color: #FFB4B4;\n border-color: #DE5555;\n}\n"),define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict",b.isDark=!1,b.cssClass="ace-tm",b.cssText=".ace-tm .ace_editor { border: 2px solid rgb(159, 159, 159);}.ace-tm .ace_editor.ace_focus { border: 2px solid #327fbd;}.ace-tm .ace_gutter { background: #e8e8e8; color: #333;}.ace-tm .ace_print_margin { width: 1px; background: #e8e8e8;}.ace-tm .ace_fold { background-color: #0000A2;}.ace-tm .ace_text-layer { cursor: text;}.ace-tm .ace_cursor { border-left: 2px solid black;}.ace-tm .ace_cursor.ace_overwrite { border-left: 0px; border-bottom: 1px solid black;} .ace-tm .ace_line .ace_invisible { color: rgb(191, 191, 191);}.ace-tm .ace_line .ace_keyword { color: blue;}.ace-tm .ace_line .ace_constant.ace_buildin { color: rgb(88, 72, 246);}.ace-tm .ace_line .ace_constant.ace_language { color: rgb(88, 92, 246);}.ace-tm .ace_line .ace_constant.ace_library { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_invalid { background-color: rgb(153, 0, 0); color: white;}.ace-tm .ace_line .ace_support.ace_function { color: rgb(60, 76, 114);}.ace-tm .ace_line .ace_support.ace_constant { color: rgb(6, 150, 14);}.ace-tm .ace_line .ace_support.ace_type,.ace-tm .ace_line .ace_support.ace_class { color: rgb(109, 121, 222);}.ace-tm .ace_line .ace_keyword.ace_operator { color: rgb(104, 118, 135);}.ace-tm .ace_line .ace_string { color: rgb(3, 106, 7);}.ace-tm .ace_line .ace_comment { color: rgb(76, 136, 107);}.ace-tm .ace_line .ace_comment.ace_doc { color: rgb(0, 102, 255);}.ace-tm .ace_line .ace_comment.ace_doc.ace_tag { color: rgb(128, 159, 191);}.ace-tm .ace_line .ace_constant.ace_numeric { color: rgb(0, 0, 205);}.ace-tm .ace_line .ace_variable { color: rgb(49, 132, 149);}.ace-tm .ace_line .ace_xml_pe { color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function { color: #0000A2;}.ace-tm .ace_markup.ace_markupine { text-decoration:underline;}.ace-tm .ace_markup.ace_heading { color: rgb(12, 7, 255);}.ace-tm .ace_markup.ace_list { color:rgb(185, 6, 144);}.ace-tm .ace_marker-layer .ace_selection { background: rgb(181, 213, 255);}.ace-tm .ace_marker-layer .ace_step { background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack { background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active_line { background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_marker-layer .ace_selected_word { background: rgb(250, 250, 255); border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_meta.ace_tag { color:rgb(28, 2, 255);}.ace-tm .ace_string.ace_regex { color: rgb(255, 0, 0)}";var d=a("../lib/dom");d.importCssString(b.cssText,b.cssClass)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +(function(){function g(a){if(typeof requirejs!="undefined"){var e=b.define;b.define=function(a,b,c){return typeof c!="function"?e.apply(this,arguments):e(a,b,function(a,d,e){return b[2]=="module"&&(e.packaged=!0),c.apply(this,arguments)})},b.define.packaged=!0;return}var f=function(a,b){return d("",a,b)};f.packaged=!0;var g=b;a&&(b[a]||(b[a]={}),g=b[a]),g.define&&(c.original=g.define),g.define=c,g.require&&(d.original=g.require),g.require=f}var a="",b=function(){return this}(),c=function(a,b,d){if(typeof a!="string"){c.original?c.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(d=b),c.modules||(c.modules={}),c.modules[a]=d},d=function(a,b,c){if(Object.prototype.toString.call(b)==="[object Array]"){var e=[];for(var g=0,h=b.length;g1&&h(b,"")>-1&&(i=RegExp(this.source,d.replace.call(g(this),"g","")),d.replace.call(a.slice(b.index),i,function(){for(var a=1;ab.index&&this.lastIndex--}return b},f||(RegExp.prototype.test=function(a){var b=d.exec.call(this,a);return b&&this.global&&!b[0].length&&this.lastIndex>b.index&&this.lastIndex--,!!b})}),define("ace/lib/es5-shim",["require","exports","module"],function(a,b,c){function p(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(b){}}Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=g.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,h=c.apply(f,d.concat(g.call(arguments)));return h!==null&&Object(h)===h?h:f}return c.apply(b,d.concat(g.call(arguments)))};return e});var d=Function.prototype.call,e=Array.prototype,f=Object.prototype,g=e.slice,h=d.bind(f.toString),i=d.bind(f.hasOwnProperty),j,k,l,m,n;if(n=i(f,"__defineGetter__"))j=d.bind(f.__defineGetter__),k=d.bind(f.__defineSetter__),l=d.bind(f.__lookupGetter__),m=d.bind(f.__lookupSetter__);Array.isArray||(Array.isArray=function(b){return h(b)=="[object Array]"}),Array.prototype.forEach||(Array.prototype.forEach=function(b){var c=G(this),d=arguments[1],e=0,f=c.length>>>0;if(h(b)!="[object Function]")throw new TypeError;while(e>>0,e=Array(d),f=arguments[1];if(h(b)!="[object Function]")throw new TypeError;for(var g=0;g>>0,e=[],f=arguments[1];if(h(b)!="[object Function]")throw new TypeError;for(var g=0;g>>0,e=arguments[1];if(h(b)!="[object Function]")throw new TypeError;for(var f=0;f>>0,e=arguments[1];if(h(b)!="[object Function]")throw new TypeError;for(var f=0;f>>0;if(h(b)!="[object Function]")throw new TypeError;if(!d&&arguments.length==1)throw new TypeError;var e=0,f;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);for(;e>>0;if(h(b)!="[object Function]")throw new TypeError;if(!d&&arguments.length==1)throw new TypeError;var e,f=d-1;if(arguments.length>=2)e=arguments[1];else do{if(f in c){e=c[f--];break}if(--f<0)throw new TypeError}while(!0);do f in this&&(e=b.call(void 0,e,c[f],f,c));while(f--);return e}),Array.prototype.indexOf||(Array.prototype.indexOf=function(b){var c=G(this),d=c.length>>>0;if(!d)return-1;var e=0;arguments.length>1&&(e=E(arguments[1])),e=e>=0?e:Math.max(0,d+e);for(;e>>0;if(!d)return-1;var e=d-1;arguments.length>1&&(e=Math.min(e,E(arguments[1]))),e=e>=0?e:d-Math.abs(e);for(;e>=0;e--)if(e in c&&b===c[e])return e;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(b){return b.__proto__||(b.constructor?b.constructor.prototype:f)});if(!Object.getOwnPropertyDescriptor){var o="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(b,c){if(typeof b!="object"&&typeof b!="function"||b===null)throw new TypeError(o+b);if(!i(b,c))return;var d,e,g;d={enumerable:!0,configurable:!0};if(n){var h=b.__proto__;b.__proto__=f;var e=l(b,c),g=m(b,c);b.__proto__=h;if(e||g)return e&&(d.get=e),g&&(d.set=g),d}return d.value=b[c],d}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(b){return Object.keys(b)}),Object.create||(Object.create=function(b,c){var d;if(b===null)d={__proto__:null};else{if(typeof b!="object")throw new TypeError("typeof prototype["+typeof b+"] != 'object'");var e=function(){};e.prototype=b,d=new e,d.__proto__=b}return c!==void 0&&Object.defineProperties(d,c),d});if(Object.defineProperty){var q=p({}),r=typeof document=="undefined"||p(document.createElement("div"));if(!q||!r)var s=Object.defineProperty}if(!Object.defineProperty||s){var t="Property description must be an object: ",u="Object.defineProperty called on non-object: ",v="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(b,c,d){if(typeof b!="object"&&typeof b!="function"||b===null)throw new TypeError(u+b);if(typeof d!="object"&&typeof d!="function"||d===null)throw new TypeError(t+d);if(s)try{return s.call(Object,b,c,d)}catch(e){}if(i(d,"value"))if(n&&(l(b,c)||m(b,c))){var g=b.__proto__;b.__proto__=f,delete b[c],b[c]=d.value,b.__proto__=g}else b[c]=d.value;else{if(!n)throw new TypeError(v);i(d,"get")&&j(b,c,d.get),i(d,"set")&&k(b,c,d.set)}return b}}Object.defineProperties||(Object.defineProperties=function(b,c){for(var d in c)i(c,d)&&Object.defineProperty(b,d,c[d]);return b}),Object.seal||(Object.seal=function(b){return b}),Object.freeze||(Object.freeze=function(b){return b});try{Object.freeze(function(){})}catch(w){Object.freeze=function(b){return function(c){return typeof c=="function"?c:b(c)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(b){return b}),Object.isSealed||(Object.isSealed=function(b){return!1}),Object.isFrozen||(Object.isFrozen=function(b){return!1}),Object.isExtensible||(Object.isExtensible=function(b){if(Object(b)===b)throw new TypeError;var c="";while(i(b,c))c+="?";b[c]=!0;var d=i(b,c);return delete b[c],d});if(!Object.keys){var x=!0,y=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],z=y.length;for(var A in{toString:null})x=!1;Object.keys=function H(a){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.keys called on a non-object");var H=[];for(var b in a)i(a,b)&&H.push(b);if(x)for(var c=0,d=z;c9999?"+":"")+("00000"+Math.abs(e)).slice(0<=e&&e<=9999?-4:-6),c=b.length;while(c--)d=b[c],d<10&&(b[c]="0"+d);return e+"-"+b.slice(0,2).join("-")+"T"+b.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};Date.now||(Date.now=function(){return(new Date).getTime()}),Date.prototype.toJSON||(Date.prototype.toJSON=function(b){if(typeof this.toISOString!="function")throw new TypeError;return this.toISOString()}),Date.parse("+275760-09-13T00:00:00.000Z")!==864e13&&(Date=function(a){var b=function e(b,c,d,f,g,h,i){var j=arguments.length;if(this instanceof a){var k=j==1&&String(b)===b?new a(e.parse(b)):j>=7?new a(b,c,d,f,g,h,i):j>=6?new a(b,c,d,f,g,h):j>=5?new a(b,c,d,f,g):j>=4?new a(b,c,d,f):j>=3?new a(b,c,d):j>=2?new a(b,c):j>=1?new a(b):new a;return k.constructor=e,k}return a.apply(this,arguments)},c=new RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$");for(var d in a)b[d]=a[d];return b.now=a.now,b.UTC=a.UTC,b.prototype=a.prototype,b.prototype.constructor=b,b.parse=function(d){var e=c.exec(d);if(e){e.shift();for(var f=1;f<7;f++)e[f]=+(e[f]||(f<3?1:0)),f==1&&e[f]--;var g=+e.pop(),h=+e.pop(),i=e.pop(),j=0;if(i){if(h>23||g>59)return NaN;j=(h*60+g)*6e4*(i=="+"?-1:1)}var k=+e[0];return 0<=k&&k<=99?(e[0]=k+400,a.UTC.apply(this,e)+j-126227808e5):a.UTC.apply(this,e)+j}return a.parse.apply(this,arguments)},b}(Date));var B=" \n \f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||B.trim()){B="["+B+"]";var C=new RegExp("^"+B+B+"*"),D=new RegExp(B+B+"*$");String.prototype.trim=function(){return String(this).replace(C,"").replace(D,"")}}var E=function(a){return a=+a,a!==a?a=0:a!==0&&a!==1/0&&a!==-Infinity&&(a=(a>0||-1)*Math.floor(Math.abs(a))),a},F="a"[0]!="a",G=function(a){if(a==null)throw new TypeError;return F&&typeof a=="string"&&a?a.split(""):Object(a)}}),define("ace/lib/dom",["require","exports","module"],function(a,b,c){"use strict";var d="http://www.w3.org/1999/xhtml";b.createElement=function(a,b){return document.createElementNS?document.createElementNS(b||d,a):document.createElement(a)},b.setText=function(a,b){a.innerText!==undefined&&(a.innerText=b),a.textContent!==undefined&&(a.textContent=b)},b.hasCssClass=function(a,b){var c=a.className.split(/\s+/g);return c.indexOf(b)!==-1},b.addCssClass=function(a,c){b.hasCssClass(a,c)||(a.className+=" "+c)},b.removeCssClass=function(a,b){var c=a.className.split(/\s+/g);for(;;){var d=c.indexOf(b);if(d==-1)break;c.splice(d,1)}a.className=c.join(" ")},b.toggleCssClass=function(a,b){var c=a.className.split(/\s+/g),d=!0;for(;;){var e=c.indexOf(b);if(e==-1)break;d=!1,c.splice(e,1)}return d&&c.push(b),a.className=c.join(" "),d},b.setCssClass=function(a,c,d){d?b.addCssClass(a,c):b.removeCssClass(a,c)},b.hasCssString=function(a,b){var c=0,d;b=b||document;if(b.createStyleSheet&&(d=b.styleSheets)){while(c5||Math.abs(a.clientY-j)>5)h=0;h==d&&(h=0,g(a));if(e)return b.preventDefault(a)};b.addListener(a,"mousedown",k),e.isOldIE&&b.addListener(a,"dblclick",k)},b.addCommandKeyListener=function(a,c){var d=b.addListener;if(e.isOldGecko||e.isOpera){var f=null;d(a,"keydown",function(a){f=a.keyCode}),d(a,"keypress",function(a){return g(c,a,f)})}else{var h=null;d(a,"keydown",function(a){return h=a.keyIdentifier||a.keyCode,g(c,a,a.keyCode)})}};if(window.postMessage){var h=1;b.nextTick=function(a,c){c=c||window;var d="zero-timeout-message-"+h;b.addListener(c,"message",function e(f){f.data==d&&(b.stopPropagation(f),b.removeListener(c,"message",e),a())}),c.postMessage(d,"*")}}else b.nextTick=function(a,b){b=b||window,window.setTimeout(a,0)}}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(a,b,c){"use strict";var d=a("./oop"),e=function(){var a={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,meta:8,command:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:'"'}};for(var b in a.FUNCTION_KEYS){var c=a.FUNCTION_KEYS[b].toUpperCase();a[c]=parseInt(b,10)}return d.mixin(a,a.MODIFIER_KEYS),d.mixin(a,a.PRINTABLE_KEYS),d.mixin(a,a.FUNCTION_KEYS),a}();d.mixin(b,e),b.keyCodeToString=function(a){return(e[a]||String.fromCharCode(a)).toLowerCase()}}),define("ace/lib/oop",["require","exports","module"],function(a,b,c){"use strict",b.inherits=function(){var a=function(){};return function(b,c){a.prototype=c.prototype,b.super_=c.prototype,b.prototype=new a,b.prototype.constructor=b}}(),b.mixin=function(a,b){for(var c in b)a[c]=b[c]},b.implement=function(a,c){b.mixin(a,c)}}),define("ace/lib/useragent",["require","exports","module"],function(a,b,c){"use strict";var d=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),e=navigator.userAgent;b.isWin=d=="win",b.isMac=d=="mac",b.isLinux=d=="linux",b.isIE=navigator.appName=="Microsoft Internet Explorer"&&parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]),b.isOldIE=b.isIE&&b.isIE<9,b.isGecko=b.isMozilla=window.controllers&&window.navigator.product==="Gecko",b.isOldGecko=b.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,b.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",b.isWebKit=parseFloat(e.split("WebKit/")[1])||undefined,b.isChrome=parseFloat(e.split(" Chrome/")[1])||undefined,b.isAIR=e.indexOf("AdobeAIR")>=0,b.isIPad=e.indexOf("iPad")>=0,b.isTouchPad=e.indexOf("TouchPad")>=0,b.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},b.getOS=function(){return b.isMac?b.OS.MAC:b.isLinux?b.OS.LINUX:b.OS.WINDOWS}}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands"],function(a,b,c){"use strict",a("./lib/fixoldbrowsers");var d=a("./lib/oop"),e=a("./lib/lang"),f=a("./lib/useragent"),g=a("./keyboard/textinput").TextInput,h=a("./mouse/mouse_handler").MouseHandler,i=a("./mouse/fold_handler").FoldHandler,j=a("./keyboard/keybinding").KeyBinding,k=a("./edit_session").EditSession,l=a("./search").Search,m=a("./range").Range,n=a("./lib/event_emitter").EventEmitter,o=a("./commands/command_manager").CommandManager,p=a("./commands/default_commands").commands,q=function(a,b){var c=a.getContainerElement();this.container=c,this.renderer=a,this.textInput=new g(a.getTextAreaContainer(),this),this.keyBinding=new j(this),f.isIPad||(this.$mouseHandler=new h(this),new i(this)),this.$blockScrolling=0,this.$search=(new l).set({wrap:!0}),this.commands=new o(f.isMac?"mac":"win",p),this.setSession(b||new k(""))};(function(){d.implement(this,n),this.setKeyboardHandler=function(a){this.keyBinding.setKeyboardHandler(a)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(a){if(this.session==a)return;if(this.session){var b=this.session;this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeLeftTop",this.$onScrollLeftChange);var c=this.session.getSelection();c.removeEventListener("changeCursor",this.$onCursorChange),c.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=a,this.$onDocumentChange=this.onDocumentChange.bind(this),a.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(a),this.$onChangeMode=this.onChangeMode.bind(this),a.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),a.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.updateText.bind(this.renderer),a.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),a.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),a.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),a.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=a.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.$blockScrolling+=1,this.onCursorChange(),this.$blockScrolling-=1,this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull(),this._emit("changeSession",{session:a,oldSession:b})},this.getSession=function(){return this.session},this.getSelection=function(){return this.selection},this.resize=function(){this.renderer.onResize()},this.setTheme=function(a){this.renderer.setTheme(a)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(a){this.renderer.setStyle(a)},this.unsetStyle=function(a){this.renderer.unsetStyle(a)},this.setFontSize=function(a){this.container.style.fontSize=a,this.renderer.updateFontSize()},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var a=this;this.$highlightPending=!0,setTimeout(function(){a.$highlightPending=!1;var b=a.session.findMatchingBracket(a.getCursorPosition());if(b){var c=new m(b.row,b.column,b.row,b.column+1);a.session.$bracketHighlight=a.session.addMarker(c,"ace_bracket","text")}},10)},this.focus=function(){var a=this;setTimeout(function(){a.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.onDocumentChange=function(a){var b=a.data,c=b.range,d;c.start.row==c.end.row&&b.action!="insertLines"&&b.action!="removeLines"?d=c.end.row:d=Infinity,this.renderer.updateLines(c.start.row,d),this._emit("change",a),this.onCursorChange()},this.onTokenizerUpdate=function(a){var b=a.data;this.renderer.updateLines(b.first,b.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.renderer.updateCursor(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.renderer.moveTextAreaToCursor(this.textInput.getElement()),this.$highlightBrackets(),this.$updateHighlightActiveLine()},this.$updateHighlightActiveLine=function(){var a=this.getSession();a.$highlightLineMarker&&a.removeMarker(a.$highlightLineMarker),typeof this.$lastrow=="number"&&this.renderer.removeGutterDecoration(this.$lastrow,"ace_gutter_active_line"),a.$highlightLineMarker=null,this.$lastrow=null;if(this.getHighlightActiveLine()){var b=this.getCursorPosition(),c=this.session.getFoldLine(b.row);if(this.getSelectionStyle()!="line"||!this.selection.isMultiLine()){var d;c?d=new m(c.start.row,0,c.end.row+1,0):d=new m(b.row,0,b.row+1,0),a.$highlightLineMarker=a.addMarker(d,"ace_active_line","background")}this.renderer.addGutterDecoration(this.$lastrow=b.row,"ace_gutter_active_line")}},this.onSelectionChange=function(a){var b=this.getSession();b.$selectionMarker&&b.removeMarker(b.$selectionMarker),b.$selectionMarker=null;if(!this.selection.isEmpty()){var c=this.selection.getRange(),d=this.getSelectionStyle();b.$selectionMarker=b.addMarker(c,"ace_selection",d)}else this.$updateHighlightActiveLine();this.$highlightSelectedWord&&this.session.getMode().highlightSelection(this)},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.setBreakpoints(this.session.getBreakpoints())},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(){this.renderer.updateText()},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getCopyText=function(){var a="";return this.selection.isEmpty()||(a=this.session.getTextRange(this.getSelectionRange())),this._emit("copy",a),a},this.onCut=function(){this.commands.exec("cut",this)},this.insert=function(a){var b=this.session,c=b.getMode(),d=this.getCursorPosition();if(this.getBehavioursEnabled()){var e=c.transformAction(b.getState(d.row),"insertion",this,b,a);e&&(a=e.text)}a=a.replace(" ",this.session.getTabString());if(!this.selection.isEmpty())d=this.session.remove(this.getSelectionRange()),this.clearSelection();else if(this.session.getOverwrite()){var f=new m.fromPoints(d,d);f.end.column+=a.length,this.session.remove(f)}this.clearSelection();var g=d.column,h=b.getState(d.row),i=c.checkOutdent(h,b.getLine(d.row),a),j=b.getLine(d.row),k=c.getNextLineIndent(h,j.slice(0,d.column),b.getTabString()),l=b.insert(d,a);e&&e.selection&&(e.selection.length==2?this.selection.setSelectionRange(new m(d.row,g+e.selection[0],d.row,g+e.selection[1])):this.selection.setSelectionRange(new m(d.row+e.selection[0],e.selection[1],d.row+e.selection[2],e.selection[3])));var h=b.getState(d.row);if(b.getDocument().isNewLine(a)){this.moveCursorTo(d.row+1,0);var n=b.getTabSize(),o=Number.MAX_VALUE;for(var p=d.row+1;p<=l.row;++p){var q=0;j=b.getLine(p);for(var r=0;r0;++r)j.charAt(r)==" "?s-=n:j.charAt(r)==" "&&(s-=1);b.remove(new m(p,0,p,r))}b.indentRows(d.row+1,l.row,k)}i&&c.autoOutdent(h,b,d.row)},this.onTextInput=function(a,b){b&&this._emit("paste",a),this.keyBinding.onTextInput(a,b)},this.onCommandKey=function(a,b,c){this.keyBinding.onCommandKey(a,b,c)},this.setOverwrite=function(a){this.session.setOverwrite(a)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(a){this.$mouseHandler.setScrollSpeed(a)},this.getScrollSpeed=function(){return this.$mouseHandler.getScrollSpeed()},this.setDragDelay=function(a){this.$mouseHandler.setDragDelay(a)},this.getDragDelay=function(){return this.$mouseHandler.getDragDelay()},this.$selectionStyle="line",this.setSelectionStyle=function(a){if(this.$selectionStyle==a)return;this.$selectionStyle=a,this.onSelectionChange(),this._emit("changeSelectionStyle",{data:a})},this.getSelectionStyle=function(){return this.$selectionStyle},this.$highlightActiveLine=!0,this.setHighlightActiveLine=function(a){if(this.$highlightActiveLine==a)return;this.$highlightActiveLine=a,this.$updateHighlightActiveLine()},this.getHighlightActiveLine=function(){return this.$highlightActiveLine},this.$highlightSelectedWord=!0,this.setHighlightSelectedWord=function(a){if(this.$highlightSelectedWord==a)return;this.$highlightSelectedWord=a,a?this.session.getMode().highlightSelection(this):this.session.getMode().clearSelectionHighlight(this)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setAnimatedScroll=function(a){this.renderer.setAnimatedScroll(a)},this.getAnimatedScroll=function(){return this.renderer.getAnimatedScroll()},this.setShowInvisibles=function(a){if(this.getShowInvisibles()==a)return;this.renderer.setShowInvisibles(a)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setShowPrintMargin=function(a){this.renderer.setShowPrintMargin(a)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(a){this.renderer.setPrintMarginColumn(a)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.$readOnly=!1,this.setReadOnly=function(a){this.$readOnly=a},this.getReadOnly=function(){return this.$readOnly},this.$modeBehaviours=!0,this.setBehavioursEnabled=function(a){this.$modeBehaviours=a},this.getBehavioursEnabled=function(){return this.$modeBehaviours},this.setShowFoldWidgets=function(a){var b=this.renderer.$gutterLayer;if(b.getShowFoldWidgets()==a)return;this.renderer.$gutterLayer.setShowFoldWidgets(a),this.$showFoldWidgets=a,this.renderer.updateFull()},this.getShowFoldWidgets=function(){return this.renderer.$gutterLayer.getShowFoldWidgets()},this.remove=function(a){this.selection.isEmpty()&&(a=="left"?this.selection.selectLeft():this.selection.selectRight());var b=this.getSelectionRange();if(this.getBehavioursEnabled()){var c=this.session,d=c.getState(b.start.row),e=c.getMode().transformAction(d,"deletion",this,c,b);e&&(b=e)}this.session.remove(b),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var a=this.getSelectionRange();a.start.column==a.end.column&&a.start.row==a.end.row&&(a.end.column=0,a.end.row++),this.session.remove(a),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var a=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(a)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var a=this.getCursorPosition(),b=a.column;if(b===0)return;var c=this.session.getLine(a.row),d,e;b=this.getFirstVisibleRow()&&a<=this.getLastVisibleRow()},this.isRowFullyVisible=function(a){return a>=this.renderer.getFirstFullyVisibleRow()&&a<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$getPageDownRow=function(){return this.renderer.getScrollBottomRow()},this.$getPageUpRow=function(){var a=this.renderer.getScrollTopRow(),b=this.renderer.getScrollBottomRow();return a-(b-a)},this.selectPageDown=function(){var a=this.$getPageDownRow()+Math.floor(this.$getVisibleRowCount()/2);this.scrollPageDown();var b=this.getSelection(),c=this.session.documentToScreenPosition(b.getSelectionLead()),d=this.session.screenToDocumentPosition(a,c.column);b.selectTo(d.row,d.column)},this.selectPageUp=function(){var a=this.renderer.getScrollTopRow()-this.renderer.getScrollBottomRow(),b=this.$getPageUpRow()+Math.round(a/2);this.scrollPageUp();var c=this.getSelection(),d=this.session.documentToScreenPosition(c.getSelectionLead()),e=this.session.screenToDocumentPosition(b,d.column);c.selectTo(e.row,e.column)},this.gotoPageDown=function(){var a=this.$getPageDownRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.gotoPageUp=function(){var a=this.$getPageUpRow(),b=this.getCursorPositionScreen().column;this.scrollToRow(a),this.getSelection().moveCursorToScreen(a,b)},this.scrollPageDown=function(){this.scrollToRow(this.$getPageDownRow())},this.scrollPageUp=function(){this.renderer.scrollToRow(this.$getPageUpRow())},this.scrollToRow=function(a){this.renderer.scrollToRow(a)},this.scrollToLine=function(a,b){this.renderer.scrollToLine(a,b)},this.centerSelection=function(){var a=this.getSelectionRange(),b=Math.floor(a.start.row+(a.end.row-a.start.row)/2);this.renderer.scrollToLine(b,!0)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(a,b){this.selection.moveCursorTo(a,b)},this.moveCursorToPosition=function(a){this.selection.moveCursorToPosition(a)},this.jumpToMatching=function(){var a=this.getCursorPosition(),b=this.session.findMatchingBracket(a);b||(a.column+=1,b=this.session.findMatchingBracket(a)),b||(a.column-=2,b=this.session.findMatchingBracket(a)),b&&(this.clearSelection(),this.moveCursorTo(b.row,b.column))},this.gotoLine=function(a,b){this.selection.clearSelection(),this.session.unfold({row:a-1,column:b||0}),this.$blockScrolling+=1,this.moveCursorTo(a-1,b||0),this.$blockScrolling-=1,this.isRowFullyVisible(this.getCursorPosition().row)||this.scrollToLine(a,!0)},this.navigateTo=function(a,b){this.clearSelection(),this.moveCursorTo(a,b)},this.navigateUp=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(-a,0)},this.navigateDown=function(a){this.selection.clearSelection(),a=a||1,this.selection.moveCursorBy(a,0)},this.navigateLeft=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().start;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(a){if(!this.selection.isEmpty()){var b=this.getSelectionRange().end;this.moveCursorToPosition(b)}else{a=a||1;while(a--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(a,b){b&&this.$search.set(b);var c=this.$search.find(this.session),d=0;return c?(this.$tryReplace(c,a)&&(d=1),c!==null&&(this.selection.setSelectionRange(c),this.renderer.scrollSelectionIntoView(c.start,c.end)),d):d},this.replaceAll=function(a,b){b&&this.$search.set(b);var c=this.$search.findAll(this.session),d=0;if(!c.length)return d;var e=this.getSelectionRange();this.clearSelection(),this.selection.moveCursorTo(0,0),this.$blockScrolling+=1;for(var f=c.length-1;f>=0;--f)this.$tryReplace(c[f],a)&&d++;return this.selection.setSelectionRange(e),this.$blockScrolling-=1,d},this.$tryReplace=function(a,b){var c=this.session.getTextRange(a);return b=this.$search.replace(c,b),b!==null?(a.end=this.session.replace(a,b),a):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(a,b){this.clearSelection(),b=b||{},b.needle=a,this.$search.set(b),this.$find()},this.findNext=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!1),this.$search.set(a),this.$find()},this.findPrevious=function(a){a=a||{},typeof a.backwards=="undefined"&&(a.backwards=!0),this.$search.set(a),this.$find()},this.$find=function(a){this.selection.isEmpty()||this.$search.set({needle:this.session.getTextRange(this.getSelectionRange())}),typeof a!="undefined"&&this.$search.set({backwards:a});var b=this.$search.find(this.session);if(b){this.session.unfold(b),this.$blockScrolling+=1,this.selection.setSelectionRange(b),this.$blockScrolling-=1;if(this.getAnimatedScroll()){var c=this.getCursorPosition();this.isRowFullyVisible(c.row)||this.scrollToLine(c.row,!0)}else this.renderer.scrollSelectionIntoView(b.start,b.end)}},this.undo=function(){this.session.getUndoManager().undo()},this.redo=function(){this.session.getUndoManager().redo()},this.destroy=function(){this.renderer.destroy()}}).call(q.prototype),b.Editor=q}),define("ace/lib/lang",["require","exports","module"],function(a,b,c){"use strict",b.stringReverse=function(a){return a.split("").reverse().join("")},b.stringRepeat=function(a,b){return(new Array(b+1)).join(a)};var d=/^\s\s*/,e=/\s\s*$/;b.stringTrimLeft=function(a){return a.replace(d,"")},b.stringTrimRight=function(a){return a.replace(e,"")},b.copyObject=function(a){var b={};for(var c in a)b[c]=a[c];return b},b.copyArray=function(a){var b=[];for(var c=0,d=a.length;c128)return;setTimeout(function(){h||m()},0)},p=function(a){h=!0,b.onCompositionStart(),e.isGecko||setTimeout(q,0)},q=function(){if(!h)return;b.onCompositionUpdate(c.value)},r=function(a){h=!1,b.onCompositionEnd()},s=function(a){i=!0;var d=b.getCopyText();d?c.value=d:a.preventDefault(),l(),setTimeout(function(){m()},0)},t=function(a){i=!0;var d=b.getCopyText();d?(c.value=d,b.onCut()):a.preventDefault(),l(),setTimeout(function(){m()},0)};d.addCommandKeyListener(c,b.onCommandKey.bind(b));if(e.isOldIE){var u={13:1,27:1};d.addListener(c,"keyup",function(a){h&&(!c.value||u[a.keyCode])&&setTimeout(r,0);if((c.value.charCodeAt(0)|0)<129)return;h?q():p()})}"onpropertychange"in c&&!("oninput"in c)?d.addListener(c,"propertychange",o):d.addListener(c,"input",n),d.addListener(c,"paste",function(a){j=!0,a.clipboardData&&a.clipboardData.getData?(m(a.clipboardData.getData("text/plain")),a.preventDefault()):o()}),"onbeforecopy"in c&&typeof clipboardData!="undefined"?(d.addListener(c,"beforecopy",function(a){var c=b.getCopyText();c?clipboardData.setData("Text",c):a.preventDefault()}),d.addListener(a,"keydown",function(a){if(a.ctrlKey&&a.keyCode==88){var c=b.getCopyText();c&&(clipboardData.setData("Text",c),b.onCut()),d.preventDefault(a)}})):(d.addListener(c,"copy",s),d.addListener(c,"cut",t)),d.addListener(c,"compositionstart",p),e.isGecko&&d.addListener(c,"text",q),e.isWebKit&&d.addListener(c,"keyup",q),d.addListener(c,"compositionend",r),d.addListener(c,"blur",function(){b.onBlur()}),d.addListener(c,"focus",function(){b.onFocus(),l()}),this.focus=function(){b.onFocus(),l(),c.focus()},this.blur=function(){c.blur()},this.isFocused=v,this.getElement=function(){return c},this.onContextMenu=function(a,b){a&&(k||(k=c.style.cssText),c.style.cssText="position:fixed; z-index:1000;left:"+(a.x-2)+"px; top:"+(a.y-2)+"px;"),b&&(c.value="")},this.onContextMenuClose=function(){setTimeout(function(){k&&(c.style.cssText=k,k=""),m()},0)}};b.TextInput=g}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event"],function(a,b,c){"use strict";var d=a("../lib/event"),e=a("./default_handlers").DefaultHandlers,f=a("./default_gutter_handler").GutterHandler,g=a("./mouse_event").MouseEvent,h=function(a){this.editor=a,new e(a),new f(a),d.addListener(a.container,"mousedown",function(b){return a.focus(),d.preventDefault(b)}),d.addListener(a.container,"selectstart",function(a){return d.preventDefault(a)});var b=a.renderer.getMouseEventTarget();d.addListener(b,"mousedown",this.onMouseEvent.bind(this,"mousedown")),d.addListener(b,"click",this.onMouseEvent.bind(this,"click")),d.addListener(b,"mousemove",this.onMouseMove.bind(this,"mousemove")),d.addMultiMouseDownListener(b,0,2,500,this.onMouseEvent.bind(this,"dblclick")),d.addMultiMouseDownListener(b,0,3,600,this.onMouseEvent.bind(this,"tripleclick")),d.addMultiMouseDownListener(b,0,4,600,this.onMouseEvent.bind(this,"quadclick")),d.addMouseWheelListener(a.container,this.onMouseWheel.bind(this,"mousewheel"));var c=a.renderer.$gutter;d.addListener(c,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),d.addListener(c,"click",this.onMouseEvent.bind(this,"gutterclick")),d.addListener(c,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),d.addListener(c,"mousemove",this.onMouseMove.bind(this,"gutter"))};(function(){this.$scrollSpeed=1,this.setScrollSpeed=function(a){this.$scrollSpeed=a},this.getScrollSpeed=function(){return this.$scrollSpeed},this.onMouseEvent=function(a,b){this.editor._emit(a,new g(b,this.editor))},this.$dragDelay=250,this.setDragDelay=function(a){this.$dragDelay=a},this.getDragDelay=function(){return this.$dragDelay},this.onMouseMove=function(a,b){var c=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!c||!c.length)return;this.editor._emit(a,new g(b,this.editor))},this.onMouseWheel=function(a,b){var c=new g(b,this.editor);c.speed=this.$scrollSpeed*2,c.wheelX=b.wheelX,c.wheelY=b.wheelY,this.editor._emit(a,c)}}).call(h.prototype),b.MouseHandler=h}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/event","ace/lib/dom","ace/lib/browser_focus"],function(a,b,c){function k(a){this.editor=a,this.$clickSelection=null,this.browserFocus=new f,a.setDefaultHandler("mousedown",this.onMouseDown.bind(this)),a.setDefaultHandler("dblclick",this.onDoubleClick.bind(this)),a.setDefaultHandler("tripleclick",this.onTripleClick.bind(this)),a.setDefaultHandler("quadclick",this.onQuadClick.bind(this)),a.setDefaultHandler("mousewheel",this.onScroll.bind(this))}function l(a,b,c,d){return Math.sqrt(Math.pow(c-a,2)+Math.pow(d-b,2))}"use strict";var d=a("../lib/event"),e=a("../lib/dom"),f=a("../lib/browser_focus").BrowserFocus,g=0,h=1,i=2,j=5;(function(){this.onMouseDown=function(a){function C(b){a.getShiftKey()?m.selection.selectToPosition(b):n.$clickSelection||(m.moveCursorToPosition(b),m.selection.clearSelection()),q=h}var b=a.inSelection(),c=a.pageX,f=a.pageY,k=a.getDocumentPosition(),m=this.editor,n=this,o=m.getSelectionRange(),p=o.isEmpty(),q=g;if(b&&(!this.browserFocus.isFocused()||(new Date).getTime()-this.browserFocus.lastFocus<20||!m.isFocused())){m.focus();return}var r=a.getButton();if(r!==0){p&&m.moveCursorToPosition(k),r==2&&(m.textInput.onContextMenu({x:a.clientX,y:a.clientY},p),d.capture(m.container,function(){},m.textInput.onContextMenuClose));return}b||C(k);var s=c,t=f,u=(new Date).getTime(),v,w,x,y=function(a){s=d.getDocumentX(a),t=d.getDocumentY(a)},z=function(a){clearInterval(F),q==g?C(k):q==i&&A(a),n.$clickSelection=null,q=g},A=function(a){e.removeCssClass(m.container,"ace_dragging"),m.session.removeMarker(x),m.$mouseHandler.$clickSelection||v||(m.moveCursorToPosition(k),m.selection.clearSelection());if(!v)return;if(w.contains(v.row,v.column)){v=null;return}m.clearSelection();if(a&&(a.ctrlKey||a.altKey))var b=m.session,c=b.insert(v,b.getTextRange(w));else var c=m.moveText(w,v);if(!c){v=null;return}m.selection.setSelectionRange(c)},B=function(){if(q==g){var a=l(c,f,s,t),b=(new Date).getTime();if(a>j){q=h;var d=m.renderer.screenToTextCoordinates(s,t);C(d)}else if(b-u>m.getDragDelay()){q=i,w=m.getSelectionRange();var k=m.getSelectionStyle();x=m.session.addMarker(w,"ace_selection",k),m.clearSelection(),e.addCssClass(m.container,"ace_dragging")}}q==i?E():q==h&&D()},D=function(){var a,b=m.renderer.screenToTextCoordinates(s,t);n.$clickSelection?n.$clickSelection.contains(b.row,b.column)?m.selection.setSelectionRange(n.$clickSelection):(n.$clickSelection.compare(b.row,b.column)==-1?a=n.$clickSelection.end:a=n.$clickSelection.start,m.selection.setSelectionAnchor(a.row,a.column),m.selection.selectToPosition(b)):m.selection.selectToPosition(b),m.renderer.scrollCursorIntoView()},E=function(){v=m.renderer.screenToTextCoordinates(s,t),m.moveCursorToPosition(v)};d.capture(m.container,y,z);var F=setInterval(B,20);return a.preventDefault()},this.onDoubleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectWord(),this.$clickSelection=c.getSelectionRange()},this.onTripleClick=function(a){var b=a.getDocumentPosition(),c=this.editor;c.moveCursorToPosition(b),c.selection.selectLine(),this.$clickSelection=c.getSelectionRange()},this.onQuadClick=function(a){var b=this.editor;b.selectAll(),this.$clickSelection=b.getSelectionRange()},this.onScroll=function(a){var b=this.editor;b.renderer.scrollBy(a.wheelX*a.speed,a.wheelY*a.speed);if(b.renderer.isScrollableBy(a.wheelX*a.speed,a.wheelY*a.speed))return a.preventDefault()}}).call(k.prototype),b.DefaultHandlers=k}),define("ace/lib/browser_focus",["require","exports","module","ace/lib/oop","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./oop"),e=a("./event"),f=a("./event_emitter").EventEmitter,g=function(a){a=a||window,this.lastFocus=(new Date).getTime(),this._isFocused=!0;var b=this;"onfocusin"in a.document?(e.addListener(a.document,"focusin",function(a){b._setFocused(!0)}),e.addListener(a.document,"focusout",function(a){b._setFocused(!!a.toElement)})):(e.addListener(a,"blur",function(a){b._setFocused(!1)}),e.addListener(a,"focus",function(a){b._setFocused(!0)}))};(function(){d.implement(this,f),this.isFocused=function(){return this._isFocused},this._setFocused=function(a){if(this._isFocused==a)return;a&&(this.lastFocus=(new Date).getTime()),this._isFocused=a,this._emit("changeFocus")}}).call(g.prototype),b.BrowserFocus=g}),define("ace/lib/event_emitter",["require","exports","module"],function(a,b,c){"use strict";var d={};d._emit=d._dispatchEvent=function(a,b){this._eventRegistry=this._eventRegistry||{},this._defaultHandlers=this._defaultHandlers||{};var c=this._eventRegistry[a]||[],d=this._defaultHandlers[a];if(!c.length&&!d)return;b=b||{},b.type=a,b.stopPropagation||(b.stopPropagation=function(){this.propagationStopped=!0}),b.preventDefault||(b.preventDefault=function(){this.defaultPrevented=!0});for(var e=0;e=4352&&a<=4447||a>=4515&&a<=4519||a>=4602&&a<=4607||a>=9001&&a<=9002||a>=11904&&a<=11929||a>=11931&&a<=12019||a>=12032&&a<=12245||a>=12272&&a<=12283||a>=12288&&a<=12350||a>=12353&&a<=12438||a>=12441&&a<=12543||a>=12549&&a<=12589||a>=12593&&a<=12686||a>=12688&&a<=12730||a>=12736&&a<=12771||a>=12784&&a<=12830||a>=12832&&a<=12871||a>=12880&&a<=13054||a>=13056&&a<=19903||a>=19968&&a<=42124||a>=42128&&a<=42182||a>=43360&&a<=43388||a>=44032&&a<=55203||a>=55216&&a<=55238||a>=55243&&a<=55291||a>=63744&&a<=64255||a>=65040&&a<=65049||a>=65072&&a<=65106||a>=65108&&a<=65126||a>=65128&&a<=65131||a>=65281&&a<=65376||a>=65504&&a<=65510}e.implement(this,h),this.setDocument=function(a){if(this.doc)throw new Error("Document is already set");this.doc=a,a.on("change",this.onChange.bind(this)),this.on("changeFold",this.onChangeFold.bind(this)),this.bgTokenizer&&(this.bgTokenizer.setDocument(this.getDocument()),this.bgTokenizer.start(0))},this.getDocument=function(){return this.doc},this.$resetRowCache=function(a){if(a==0){this.$rowCache=[];return}var b=this.$rowCache;for(var c=0;c=a){b.splice(c,b.length);return}},this.onChangeFold=function(a){var b=a.data;this.$resetRowCache(b.start.row)},this.onChange=function(a){var b=a.data;this.$modified=!0,this.$resetRowCache(b.range.start.row);var c=this.$updateInternalDataOnChange(a);!this.$fromUndo&&this.$undoManager&&!b.ignore&&(this.$deltasDoc.push(b),c&&c.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:c}),this.$informUndoManager.schedule()),this.bgTokenizer.start(b.range.start.row),this._emit("change",a)},this.setValue=function(a){this.doc.setValue(a),this.selection.moveCursorTo(0,0),this.selection.clearSelection(),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(a){return this.bgTokenizer.getState(a)},this.getTokens=function(a,b){return this.bgTokenizer.getTokens(a,b)},this.getTokenAt=function(a,b){var c=this.bgTokenizer.getTokens(a,a)[0].tokens,d,e=0;if(b==null)f=c.length-1,e=this.getLine(a).length;else for(var f=0;f=b)break}return d=c[f],d?(d.index=f,d.start=e-d.value.length,d):null},this.setUndoManager=function(a){this.$undoManager=a,this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(a){var b=this;this.$syncInformUndoManager=function(){b.$informUndoManager.cancel(),b.$deltasFold.length&&(b.$deltas.push({group:"fold",deltas:b.$deltasFold}),b.$deltasFold=[]),b.$deltasDoc.length&&(b.$deltas.push({group:"doc",deltas:b.$deltasDoc}),b.$deltasDoc=[]),b.$deltas.length>0&&a.execute({action:"aceupdate",args:[b.$deltas,b]}),b.$deltas=[]},this.$informUndoManager=f.deferredCall(this.$syncInformUndoManager)}},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?f.stringRepeat(" ",this.getTabSize()):" "},this.$useSoftTabs=!0,this.setUseSoftTabs=function(a){if(this.$useSoftTabs===a)return;this.$useSoftTabs=a},this.getUseSoftTabs=function(){return this.$useSoftTabs},this.$tabSize=4,this.setTabSize=function(a){if(isNaN(a)||this.$tabSize===a)return;this.$modified=!0,this.$tabSize=a,this._emit("changeTabSize")},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(a){return this.$useSoftTabs&&a.column%this.$tabSize==0},this.$overwrite=!1,this.setOverwrite=function(a){if(this.$overwrite==a)return;this.$overwrite=a,this._emit("changeOverwrite")},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(a){this.$breakpoints=[];for(var b=0;b0&&(d=!!c.charAt(b-1).match(this.tokenRe)),d||(d=!!c.charAt(b).match(this.tokenRe));var e=d?this.tokenRe:this.nonTokenRe,f=b;if(f>0){do f--;while(f>=0&&c.charAt(f).match(e));f++}var g=b;while(g=this.doc.getLength()-1)return 0;var c=this.doc.removeLines(a,b);return this.doc.insertLines(a+1,c),1},this.duplicateLines=function(a,b){var a=this.$clipRowToDocument(a),b=this.$clipRowToDocument(b),c=this.getLines(a,b);this.doc.insertLines(a,c);var d=b-a+1;return d},this.$clipRowToDocument=function(a){return Math.max(0,Math.min(a,this.doc.getLength()-1))},this.$clipColumnToRow=function(a,b){return b<0?0:Math.min(this.doc.getLine(a).length,b)},this.$clipPositionToDocument=function(a,b){b=Math.max(0,b);if(a<0)a=0,b=0;else{var c=this.doc.getLength();a>=c?(a=c-1,b=this.doc.getLine(c-1).length):b=Math.min(this.doc.getLine(a).length,b)}return{row:a,column:b}},this.$clipRangeToDocument=function(a){a.start.row<0?(a.start.row=0,a.start.column=0):a.start.column=this.$clipColumnToRow(a.start.row,a.start.column);var b=this.doc.getLength()-1;return a.end.row>b?(a.end.row=b,a.end.column=this.doc.getLine(b).length):a.end.column=this.$clipColumnToRow(a.end.row,a.end.column),a},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(a){if(a!=this.$useWrapMode){this.$useWrapMode=a,this.$modified=!0,this.$resetRowCache(0);if(a){var b=this.getLength();this.$wrapData=[];for(var c=0;c0?(this.$wrapLimit=b,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._emit("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(a){var b=this.$wrapLimitRange.min;b&&(a=Math.max(b,a));var c=this.$wrapLimitRange.max;return c&&(a=Math.min(c,a)),Math.max(1,a)},this.getWrapLimit=function(){return this.$wrapLimit},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(a){var b=this.$useWrapMode,c,d=a.data.action,e=a.data.range.start.row,f=a.data.range.end.row,g=a.data.range.start,h=a.data.range.end,i=null;d.indexOf("Lines")!=-1?(d=="insertLines"?f=e+a.data.lines.length:f=e,c=a.data.lines?a.data.lines.length:f-e):c=f-e;if(c!=0)if(d.indexOf("remove")!=-1){b&&this.$wrapData.splice(e,c);var j=this.$foldData;i=this.getFoldsInRange(a.data.range),this.removeFolds(i);var k=this.getFoldLine(h.row),l=0;if(k){k.addRemoveChars(h.row,h.column,g.column-h.column),k.shiftRow(-c);var m=this.getFoldLine(e);m&&m!==k&&(m.merge(k),k=m),l=j.indexOf(k)+1}for(l;l=h.row&&k.shiftRow(-c)}f=e}else{var n;if(b){n=[e,0];for(var o=0;o=e&&k.shiftRow(c)}}else{c=Math.abs(a.data.range.start.column-a.data.range.end.column),d.indexOf("remove")!=-1&&(i=this.getFoldsInRange(a.data.range),this.removeFolds(i),c=-c);var k=this.getFoldLine(e);k&&k.addRemoveChars(e,g.column,c)}return b&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),b&&this.$updateWrapData(e,f),i},this.$updateWrapData=function(a,b){var c=this.doc.getAllLines(),d=this.getTabSize(),e=this.$wrapData,g=this.$wrapLimit,h,k,l=a;b=Math.min(b,c.length-1);while(l<=b){k=this.getFoldLine(l,k);if(!k)h=this.$getDisplayTokens(f.stringTrimRight(c[l])),e[l]=this.$computeWrapSplits(h,g,d),l++;else{h=[],k.walk(function(a,b,d,e){var f;if(a){f=this.$getDisplayTokens(a,h.length),f[0]=i;for(var g=1;g=n)h.pop();e[k.start.row]=this.$computeWrapSplits(h,g,d),l=k.end.row+1}}};var b=1,c=2,i=3,j=4,l=9,n=10,o=11,p=12;this.$computeWrapSplits=function(a,b){function g(b){var d=a.slice(e,b),g=d.length;d.join("").replace(/12/g,function(){g-=1}).replace(/2/g,function(){g-=1}),f+=g,c.push(f),e=b}if(a.length==0)return[];var c=[],d=a.length,e=0,f=0;while(d-e>b){var h=e+b;if(a[h]>=n){while(a[h]>=n)h++;g(h);continue}if(a[h]==i||a[h]==j){for(h;h!=e-1;h--)if(a[h]==i)break;if(h>e){g(h);continue}h=e+b;for(h;hk&&a[h]k&&a[h]==l)h--;if(h>k){g(++h);continue}h=e+b,g(h)}return c},this.$getDisplayTokens=function(a,d){var e=[],f;d=d||0;for(var g=0;g39&&h<48||h>57&&h<64?e.push(l):h>=4352&&q(h)?e.push(b,c):e.push(b)}return e},this.$getStringScreenWidth=function(a,b,c){if(b==0)return[0,0];b==null&&(b=c+a.length*Math.max(this.getTabSize(),2)),c=c||0;var d,e;for(e=0;e=4352&&q(d)?c+=2:c+=1;if(c>b)break}return[c,e]},this.getRowLength=function(a){return!this.$useWrapMode||!this.$wrapData[a]?1:this.$wrapData[a].length+1},this.getRowHeight=function(a,b){return this.getRowLength(b)*a.lineHeight},this.getScreenLastRowColumn=function(a){var b=this.screenToDocumentPosition(a,Number.MAX_VALUE);return this.documentToScreenColumn(b.row,b.column)},this.getDocumentLastRowColumn=function(a,b){var c=this.documentToScreenRow(a,b);return this.getScreenLastRowColumn(c)},this.getDocumentLastRowColumnPosition=function(a,b){var c=this.documentToScreenRow(a,b);return this.screenToDocumentPosition(c,Number.MAX_VALUE/10)},this.getRowSplitData=function(a){return this.$useWrapMode?this.$wrapData[a]:undefined},this.getScreenTabSize=function(a){return this.$tabSize-a%this.$tabSize},this.screenToDocumentRow=function(a,b){return this.screenToDocumentPosition(a,b).row},this.screenToDocumentColumn=function(a,b){return this.screenToDocumentPosition(a,b).column},this.screenToDocumentPosition=function(a,b){if(a<0)return{row:0,column:0};var c,d=0,e=0,f,g=0,h=0,i=this.$rowCache;for(var j=0;j=a||d>=l)break;g+=h,d++,d>n&&(d=m.end.row+1,m=this.getNextFoldLine(d,m),n=m?m.start.row:Infinity),k&&i.push({docRow:d,screenRow:g})}if(m&&m.start.row<=d)c=this.getFoldDisplayLine(m),d=m.start.row;else{if(g+h<=a||d>l)return{row:l,column:this.getLine(l).length};c=this.getLine(d),m=null}if(this.$useWrapMode){var o=this.$wrapData[d];o&&(f=o[a-g],a>g&&o.length&&(e=o[a-g-1]||o[o.length-1],c=c.substring(e)))}return e+=this.$getStringScreenWidth(c,b)[1],this.$useWrapMode&&e>=f&&(e=f-1),m?m.idxToPosition(e):{row:d,column:e}},this.documentToScreenPosition=function(a,b){if(typeof b=="undefined")var c=this.$clipPositionToDocument(a.row,a.column);else c=this.$clipPositionToDocument(a,b);a=c.row,b=c.column;var d;if(this.$useWrapMode){d=this.$wrapData;if(a>d.length-1)return{row:this.getScreenLength(),column:d.length==0?0:d[d.length-1].length-1}}var e=0,f=null,g=null;g=this.getFoldAt(a,b,1),g&&(a=g.start.row,b=g.start.column);var h,i=0,j=this.$rowCache;for(var k=0;k=n){h=m.end.row+1;if(h>a)break;m=this.getNextFoldLine(h,m),n=m?m.start.row:Infinity}else h=i+1;e+=this.getRowLength(i),i=h,l&&j.push({docRow:i,screenRow:e})}var o="";m&&i>=n?(o=this.getFoldDisplayLine(m,a,b),f=m.start.row):(o=this.getLine(a).substring(0,b),f=a);if(this.$useWrapMode){var p=d[f],q=0;while(o.length>=p[q])e++,q++;o=o.substring(p[q-1]||0,o.length)}return{row:e,column:this.$getStringScreenWidth(o)[0]}},this.documentToScreenColumn=function(a,b){return this.documentToScreenPosition(a,b).column},this.documentToScreenRow=function(a,b){return this.documentToScreenPosition(a,b).row},this.getScreenLength=function(){var a=0,b=null;if(!this.$useWrapMode){a=this.getLength();var c=this.$foldData;for(var d=0;dg&&(f=b.end.row+1,b=this.$foldData[d++],g=b?b.start.row:Infinity)}return a}}).call(n.prototype),a("./edit_session/folding").Folding.call(n.prototype),a("./edit_session/bracket_match").BracketMatch.call(n.prototype),b.EditSession=n}),define("ace/config",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return a.replace(/-(.)/g,function(a,b){return b.toUpperCase()})}"no use strict";var d=a("./lib/lang"),e=function(){return this}(),f={packaged:!1,workerPath:"",modePath:"",themePath:"",suffix:".js"};b.get=function(a){if(!f.hasOwnProperty(a))throw new Error("Unknown confik key: "+a);return f[a]},b.set=function(a,b){if(!f.hasOwnProperty(a))throw new Error("Unknown confik key: "+a);f[a]=b},b.all=function(){return d.copyObject(f)},b.init=function(){f.packaged=a.packaged||c.packaged||e.define&&define.packaged;if(!e.document)return"";var d={},h="",i,j=document.getElementsByTagName("script");for(var k=0;kb.row||a.row==b.row&&a.column>b.column},this.getRange=function(){var a=this.selectionAnchor,b=this.selectionLead;return this.isEmpty()?g.fromPoints(b,b):this.isBackwards()?g.fromPoints(b,a):g.fromPoints(a,b)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var a=this.doc.getLength()-1;this.setSelectionAnchor(a,this.doc.getLine(a).length),this.moveCursorTo(0,0)},this.setSelectionRange=function(a,b){b?(this.setSelectionAnchor(a.end.row,a.end.column),this.selectTo(a.start.row,a.start.column)):(this.setSelectionAnchor(a.start.row,a.start.column),this.selectTo(a.end.row,a.end.column)),this.$desiredColumn=null},this.$moveSelection=function(a){var b=this.selectionLead;this.$isEmpty&&this.setSelectionAnchor(b.row,b.column),a.call(this)},this.selectTo=function(a,b){this.$moveSelection(function(){this.moveCursorTo(a,b)})},this.selectToPosition=function(a){this.$moveSelection(function(){this.moveCursorToPosition(a)})},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.selectWord=function(){var a=this.getCursor(),b=this.session.getWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectAWord=function(){var a=this.getCursor(),b=this.session.getAWordRange(a.row,a.column);this.setSelectionRange(b)},this.selectLine=function(){var a=this.selectionLead.row,b,c=this.session.getFoldLine(a);c?(a=c.start.row,b=c.end.row):b=a,this.setSelectionAnchor(a,0),this.$moveSelection(function(){this.moveCursorTo(b+1,0)})},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,-1))this.moveCursorTo(b.start.row,b.start.column);else if(a.column==0)a.row>0&&this.moveCursorTo(a.row-1,this.doc.getLine(a.row-1).length);else{var c=this.session.getTabSize();this.session.isTabStop(a)&&this.doc.getLine(a.row).slice(a.column-c,a.column).split(" ").length-1==c?this.moveCursorBy(0,-c):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var a=this.selectionLead.getPosition(),b;if(b=this.session.getFoldAt(a.row,a.column,1))this.moveCursorTo(b.end.row,b.end.column);else if(this.selectionLead.column==this.doc.getLine(this.selectionLead.row).length)this.selectionLead.row=c.length){this.moveCursorTo(a,c.length),this.moveCursorRight(),a0&&this.moveCursorWordLeft();return}if(g=this.session.tokenRe.exec(f))b-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(a,b)},this.moveCursorBy=function(a,b){var c=this.session.documentToScreenPosition(this.selectionLead.row,this.selectionLead.column);b===0&&(this.$desiredColumn?c.column=this.$desiredColumn:this.$desiredColumn=c.column);var d=this.session.screenToDocumentPosition(c.row+a,c.column);this.moveCursorTo(d.row,d.column+b,b===0)},this.moveCursorToPosition=function(a){this.moveCursorTo(a.row,a.column)},this.moveCursorTo=function(a,b,c){var d=this.session.getFoldAt(a,b,1);d&&(a=d.start.row,b=d.start.column),this.$keepDesiredColumnOnChange=!0,this.selectionLead.setPosition(a,b),this.$keepDesiredColumnOnChange=!1,c||(this.$desiredColumn=null)},this.moveCursorToScreen=function(a,b,c){var d=this.session.screenToDocumentPosition(a,b);this.moveCursorTo(d.row,d.column,c)},this.detach=function(){this.selectionLead.detach(),this.selectionAnchor.detach(),this.session=this.doc=null},this.fromOrientedRange=function(a){this.setSelectionRange(a,a.cursor==a.start),this.$desiredColumn=a.desiredColumn||this.$desiredColumn},this.toOrientedRange=function(a){var b=this.getRange();return a?(a.start.column=b.start.column,a.start.row=b.start.row,a.end.column=b.end.column,a.end.row=b.end.row):a=b,a.cursor=this.isBackwards()?a.start:a.end,a.desiredColumn=this.$desiredColumn,a}}).call(h.prototype),b.Selection=h}),define("ace/range",["require","exports","module"],function(a,b,c){"use strict";var d=function(a,b,c,d){this.start={row:a,column:b},this.end={row:c,column:d}};(function(){this.isEqual=function(a){return this.start.row==a.start.row&&this.end.row==a.end.row&&this.start.column==a.start.column&&this.end.column==a.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(a,b){return this.compare(a,b)==0},this.compareRange=function(a){var b,c=a.end,d=a.start;return b=this.compare(c.row,c.column),b==1?(b=this.compare(d.row,d.column),b==1?2:b==0?1:0):b==-1?-2:(b=this.compare(d.row,d.column),b==-1?-1:b==1?42:0)},this.comparePoint=function(a){return this.compare(a.row,a.column)},this.containsRange=function(a){return this.comparePoint(a.start)==0&&this.comparePoint(a.end)==0},this.intersectsRange=function(a){var b=this.compareRange(a);return b==-1||b==0||b==1},this.isEnd=function(a,b){return this.end.row==a&&this.end.column==b},this.isStart=function(a,b){return this.start.row==a&&this.start.column==b},this.setStart=function(a,b){typeof a=="object"?(this.start.column=a.column,this.start.row=a.row):(this.start.row=a,this.start.column=b)},this.setEnd=function(a,b){typeof a=="object"?(this.end.column=a.column,this.end.row=a.row):(this.end.row=a,this.end.column=b)},this.inside=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)||this.isStart(a,b)?!1:!0:!1},this.insideStart=function(a,b){return this.compare(a,b)==0?this.isEnd(a,b)?!1:!0:!1},this.insideEnd=function(a,b){return this.compare(a,b)==0?this.isStart(a,b)?!1:!0:!1},this.compare=function(a,b){return!this.isMultiLine()&&a===this.start.row?bthis.end.column?1:0:athis.end.row?1:this.start.row===a?b>=this.start.column?0:-1:this.end.row===a?b<=this.end.column?0:1:0},this.compareStart=function(a,b){return this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.compareEnd=function(a,b){return this.end.row==a&&this.end.column==b?1:this.compare(a,b)},this.compareInside=function(a,b){return this.end.row==a&&this.end.column==b?1:this.start.row==a&&this.start.column==b?-1:this.compare(a,b)},this.clipRows=function(a,b){if(this.end.row>b)var c={row:b+1,column:0};if(this.start.row>b)var e={row:b+1,column:0};if(this.start.row=0&&/^[\w\d]/.test(h)||e<=g&&/[\w\d]$/.test(h))return;h=f.substring(c.start.column,c.end.column);if(!/^[\w\d]+$/.test(h))return;var i=a.getCursorPosition(),j={wrap:!0,wholeWord:!0,caseSensitive:!0,needle:h},k=a.$search.getOptions();a.$search.set(j);var l=a.$search.findAll(b);l.forEach(function(a){if(!a.contains(i.row,i.column)){var c=b.addMarker(a,"ace_selected_word","text");b.$selectionOccurrences.push(c)}}),a.$search.set(k)},this.clearSelectionHighlight=function(a){if(!a.session.$selectionOccurrences)return;a.session.$selectionOccurrences.forEach(function(b){a.session.removeMarker(b)}),a.session.$selectionOccurrences=[]},this.createModeDelegates=function(a){if(!this.$embeds)return;this.$modes={};for(var b=0;b1&&e[i].token.length!==j-1)throw new Error("Matching groups and length of the token array don't match in rule #"+i+" of state "+c);h[g]={rule:i,len:j},g+=j,f.push(k)}this.regExps[c]=new RegExp("(?:("+f.join(")|(")+")|(.))",b)}};(function(){this.getLineTokens=function(a,b){var c=b,d=this.rules[c],e=this.matchMappings[c],f=this.regExps[c];f.lastIndex=0;var g,h=[],i=0,j={type:null,value:""};while(g=f.exec(a)){var k="text",l=null,m=[g[0]];for(var n=0;n1&&(m=g.slice(n+2,n+1+e[n].len)),typeof l.token=="function"?k=l.token.apply(this,m):k=l.token;var o=l.next;o&&o!==c&&(c=o,d=this.rules[c],e=this.matchMappings[c],i=f.lastIndex,f=this.regExps[c],f.lastIndex=i);break}if(m[0]){typeof k=="string"&&(m=[m.join("")],k=[k]);for(var n=0;n=b&&(a.row=Math.max(0,b-1),a.column=this.getLine(b-1).length),a},this.insert=function(a,b){if(!b||b.length===0)return a;a=this.$clipPosition(a),this.getLength()<=1&&this.$detectNewLine(b);var c=this.$split(b),d=c.splice(0,1)[0],e=c.length==0?null:c.splice(c.length-1,1)[0];return a=this.insertInLine(a,d),e!==null&&(a=this.insertNewLine(a),a=this.insertLines(a.row,c),a=this.insertInLine(a,e||"")),a},this.insertLines=function(a,b){if(b.length==0)return{row:a,column:0};var c=[a,0];c.push.apply(c,b),this.$lines.splice.apply(this.$lines,c);var d=new f(a,0,a+b.length,0),e={action:"insertLines",range:d,lines:b};return this._emit("change",{data:e}),d.end},this.insertNewLine=function(a){a=this.$clipPosition(a);var b=this.$lines[a.row]||"";this.$lines[a.row]=b.substring(0,a.column),this.$lines.splice(a.row+1,0,b.substring(a.column,b.length));var c={row:a.row+1,column:0},d={action:"insertText",range:f.fromPoints(a,c),text:this.getNewLineCharacter()};return this._emit("change",{data:d}),c},this.insertInLine=function(a,b){if(b.length==0)return a;var c=this.$lines[a.row]||"";this.$lines[a.row]=c.substring(0,a.column)+b+c.substring(a.column);var d={row:a.row,column:a.column+b.length},e={action:"insertText",range:f.fromPoints(a,d),text:b};return this._emit("change",{data:e}),d},this.remove=function(a){a.start=this.$clipPosition(a.start),a.end=this.$clipPosition(a.end);if(a.isEmpty())return a.start;var b=a.start.row,c=a.end.row;if(a.isMultiLine()){var d=a.start.column==0?b:b+1,e=c-1;a.end.column>0&&this.removeInLine(c,0,a.end.column),e>=d&&this.removeLines(d,e),d!=b&&(this.removeInLine(b,a.start.column,this.getLine(b).length),this.removeNewLine(a.start.row))}else this.removeInLine(b,a.start.column,a.end.column);return a.start},this.removeInLine=function(a,b,c){if(b==c)return;var d=new f(a,b,a,c),e=this.getLine(a),g=e.substring(b,c),h=e.substring(0,b)+e.substring(c,e.length);this.$lines.splice(a,1,h);var i={action:"removeText",range:d,text:g};return this._emit("change",{data:i}),d.start},this.removeLines=function(a,b){var c=new f(a,0,b+1,0),d=this.$lines.splice(a,b-a+1),e={action:"removeLines",range:c,nl:this.getNewLineCharacter(),lines:d};return this._emit("change",{data:e}),d},this.removeNewLine=function(a){var b=this.getLine(a),c=this.getLine(a+1),d=new f(a,b.length,a+1,0),e=b+c;this.$lines.splice(a,2,e);var g={action:"removeText",range:d,text:this.getNewLineCharacter()};this._emit("change",{data:g})},this.replace=function(a,b){if(b.length==0&&a.isEmpty())return a.start;if(b==this.getTextRange(a))return a.end;this.remove(a);if(b)var c=this.insert(a.start,b);else c=a.start;return c},this.applyDeltas=function(a){for(var b=0;b=0;b--){var c=a[b],d=f.fromPoints(c.range.start,c.range.end);c.action=="insertLines"?this.removeLines(d.start.row,d.end.row-1):c.action=="insertText"?this.remove(d):c.action=="removeLines"?this.insertLines(d.start.row,c.lines):c.action=="removeText"&&this.insert(d.start,c.text)}}}).call(h.prototype),b.Document=h}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=b.Anchor=function(a,b,c){this.document=a,typeof c=="undefined"?this.setPosition(b.row,b.column):this.setPosition(b,c),this.$onChange=this.onChange.bind(this),a.on("change",this.$onChange)};(function(){d.implement(this,e),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.onChange=function(a){var b=a.data,c=b.range;if(c.start.row==c.end.row&&c.start.row!=this.row)return;if(c.start.row>this.row)return;if(c.start.row==this.row&&c.start.column>this.column)return;var d=this.row,e=this.column;b.action==="insertText"?c.start.row===d&&c.start.column<=e?c.start.row===c.end.row?e+=c.end.column-c.start.column:(e-=c.start.column,d+=c.end.row-c.start.row):c.start.row!==c.end.row&&c.start.row=e?e=c.start.column:e=Math.max(0,e-(c.end.column-c.start.column)):c.start.row!==c.end.row&&c.start.row=this.document.getLength()?(c.row=Math.max(0,this.document.getLength()-1),c.column=this.document.getLine(c.row).length):a<0?(c.row=0,c.column=0):(c.row=a,c.column=Math.min(this.document.getLine(c.row).length,Math.max(0,b))),b<0&&(c.column=0),c}}).call(f.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/event_emitter").EventEmitter,f=function(a,b){this.running=!1,this.lines=[],this.currentLine=0,this.tokenizer=a;var c=this;this.$worker=function(){if(!c.running)return;var a=new Date,b=c.currentLine,d=c.doc,e=0,f=d.getLength();while(c.currentLine20){c.fireUpdateEvent(b,c.currentLine-1),c.running=setTimeout(c.$worker,20);return}}c.running=!1,c.fireUpdateEvent(b,f-1)}};(function(){d.implement(this,e),this.setTokenizer=function(a){this.tokenizer=a,this.lines=[],this.start(0)},this.setDocument=function(a){this.doc=a,this.lines=[],this.stop()},this.fireUpdateEvent=function(a,b){var c={first:a,last:b};this._emit("update",{data:c})},this.start=function(a){this.currentLine=Math.min(a||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(a,b){return this.$tokenizeRows(a,b)},this.getState=function(a){return this.$tokenizeRows(a,a)[0].state},this.$tokenizeRows=function(a,b){if(!this.doc||isNaN(a)||isNaN(b))return[{state:"start",tokens:[]}];var c=[],d="start",e=!1;a>0&&this.lines[a-1]?(d=this.lines[a-1].state,e=!0):a==0?(d="start",e=!0):this.lines.length>0&&(d=this.lines[this.lines.length-1].state);var f=this.doc.getLines(a,b);for(var g=a;g<=b;g++)if(!this.lines[g]){var h=this.tokenizer.getLineTokens(f[g-a]||"",d),d=h.state;c.push(h),e&&(this.lines[g]=h)}else{var h=this.lines[g];d=h.state,c.push(h)}return c}}).call(f.prototype),b.BackgroundTokenizer=f}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(a,b,c){function h(){this.getFoldAt=function(a,b,c){var d=this.getFoldLine(a);if(!d)return null;var e=d.folds;for(var f=0;f=a)return e;if(e.end.row>a)return null}return null},this.getNextFoldLine=function(a,b){var c=this.$foldData,d=0;b&&(d=c.indexOf(b)),d==-1&&(d=0);for(d;d=a)return e}return null},this.getFoldedRowCount=function(a,b){var c=this.$foldData,d=b-a+1;for(var e=0;e=b){h=a?d-=b-h:d=0);break}g>=a&&(h>=a?d-=g-h:d-=g-a+1)}return d},this.$addFoldLine=function(a){return this.$foldData.push(a),this.$foldData.sort(function(a,b){return a.start.row-b.start.row}),a},this.addFold=function(a,b){var c=this.$foldData,d=!1,g;a instanceof f?g=a:g=new f(b,a),this.$clipRangeToDocument(g.range);var h=g.start.row,i=g.start.column,j=g.end.row,k=g.end.column;if(g.placeholder.length<2)throw"Placeholder has to be at least 2 characters";if(h==j&&k-i<2)throw"The range has to be at least 2 characters width";var l=this.getFoldAt(h,i,1),m=this.getFoldAt(j,k,-1);if(l&&m==l)return l.addSubFold(g);if(l&&!l.range.isStart(h,i)||m&&!m.range.isEnd(j,k))throw"A fold can't intersect already existing fold"+g.range+l.range;var n=this.getFoldsInRange(g.range);n.length>0&&(this.removeFolds(n),g.subFolds=n);for(var o=0;othis.endRow)throw"Can't add a fold to this FoldLine as it has no connection";this.folds.push(a),this.folds.sort(function(a,b){return-a.range.compareEnd(b.start.row,b.start.column)}),this.range.compareEnd(a.start.row,a.start.column)>0?(this.end.row=a.end.row,this.end.column=a.end.column):this.range.compareStart(a.end.row,a.end.column)<0&&(this.start.row=a.start.row,this.start.column=a.start.column)}else if(a.start.row==this.end.row)this.folds.push(a),this.end.row=a.end.row,this.end.column=a.end.column;else{if(a.end.row!=this.start.row)throw"Trying to add fold to FoldRow that doesn't have a matching row";this.folds.unshift(a),this.start.row=a.start.row,this.start.column=a.start.column}a.foldLine=this},this.containsRow=function(a){return a>=this.start.row&&a<=this.end.row},this.walk=function(a,b,c){var d=0,e=this.folds,f,g,h,i=!0;b==null&&(b=this.end.row,c=this.end.column);for(var j=0;j=this.$rowTokens.length){this.$row+=1;if(this.$row>=a)return this.$row=a-1,null;this.$rowTokens=this.$session.getTokens(this.$row,this.$row)[0].tokens,this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var a=this.$rowTokens,b=this.$tokenIndex,c=a[b].start;if(c!==undefined)return c;c=0;while(b>0)b-=1,c+=a[b].value.length;return c}}).call(d.prototype),b.TokenIterator=d}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator"],function(a,b,c){function e(){this.findMatchingBracket=function(a){if(a.column==0)return null;var b=this.getLine(a.row).charAt(a.column-1);if(b=="")return null;var c=b.match(/([\(\[\{])|([\)\]\}])/);return c?c[1]?this.$findClosingBracket(c[1],a):this.$findOpeningBracket(c[2],a):null},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("rparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn()-2,j=g.value;for(;;){while(i>=0){var k=j.charAt(i);if(k==c){e-=1;if(e==0)return{row:f.getCurrentTokenRow(),column:i+f.getCurrentTokenColumn()}}else k==a&&(e+=1);i-=1}do g=f.stepBackward();while(g&&!h.test(g.type));if(g==null)break;j=g.value,i=j.length-1}return null},this.$findClosingBracket=function(a,b){var c=this.$brackets[a],e=1,f=new d(this,b.row,b.column),g=f.getCurrentToken();if(!g)return null;var h=new RegExp("(\\.?"+g.type.replace(".","|").replace("lparen","lparen|rparen")+")+"),i=b.column-f.getCurrentTokenColumn();for(;;){var j=g.value,k=j.length;while(i=0;h--){var i=g[h],j=c.$rangeFromMatch(f,i.offset,i.str.length);if(d(j))return!0}})}}},this.$rangeFromMatch=function(a,b,c){return new f(a,b,a,b+c)},this.$assembleRegExp=function(){if(this.$options.regExp)var a=this.$options.needle;else a=d.escapeRegExp(this.$options.needle);this.$options.wholeWord&&(a="\\b"+a+"\\b");var b="g";this.$options.caseSensitive||(b+="i");var c=new RegExp(a,b);return c},this.$forwardLineIterator=function(a){function k(e){var f=a.getLine(e);return b&&e==c.end.row&&(f=f.substring(0,c.end.column)),j&&e==d.row&&(f=f.substring(0,d.column)),f}var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"start":"end"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap,j=!1;return{forEach:function(a){var b=d.row,c=k(b),g=d.column,l=!1;j=!1;while(!a(c,g,b)){if(l)return;b++,g=0;if(b>h){if(!i)return;b=e,g=f,j=!0}b==d.row&&(l=!0),c=k(b)}}}},this.$backwardLineIterator=function(a){var b=this.$options.scope==g.SELECTION,c=this.$options.range||a.getSelection().getRange(),d=this.$options.start||c[b?"end":"start"],e=b?c.start.row:0,f=b?c.start.column:0,h=b?c.end.row:a.getLength()-1,i=this.$options.wrap;return{forEach:function(g){var j=d.row,k=a.getLine(j).substring(0,d.column),l=0,m=!1,n=!1;while(!g(k,l,j)){if(m)return;j--,l=0;if(j0},this.hasRedo=function(){return this.$redoStack.length>0}}).call(d.prototype),b.UndoManager=d}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/useragent","ace/config","ace/lib/net","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/lib/event_emitter","text!ace/css/editor.css"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/useragent"),h=a("./config"),i=a("./lib/net"),j=a("./layer/gutter").Gutter,k=a("./layer/marker").Marker,l=a("./layer/text").Text,m=a("./layer/cursor").Cursor,n=a("./scrollbar").ScrollBar,o=a("./renderloop").RenderLoop,p=a("./lib/event_emitter").EventEmitter,q=a("text!./css/editor.css");e.importCssString(q,"ace_editor");var r=function(a,b){var c=this;this.container=a,e.addCssClass(a,"ace_editor"),this.setTheme(b),this.$gutter=e.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=e.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=e.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new j(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onResize.bind(this,!0)),this.$markerBack=new k(this.content);var d=this.$textLayer=new l(this.content);this.canvas=d.element,this.$markerFront=new k(this.content),this.characterWidth=d.getCharacterWidth(),this.lineHeight=d.getLineHeight(),this.$cursorLayer=new m(this.content),this.$cursorPadding=8,this.$horizScroll=!0,this.$horizScrollAlwaysVisible=!0,this.$animatedScroll=!1,this.scrollBar=new n(a),this.scrollBar.addEventListener("scroll",function(a){c.session.setScrollTop(a.data)}),this.scrollTop=0,this.scrollLeft=0,f.addListener(this.scroller,"scroll",function(){var a=c.scroller.scrollLeft;c.scrollLeft=a,c.session.setScrollLeft(a),a==0?c.$gutter.className="ace_gutter":c.$gutter.className="ace_gutter horscroll"}),this.cursorPos={row:0,column:0},this.$textLayer.addEventListener("changeCharacterSize",function(){c.characterWidth=d.getCharacterWidth(),c.lineHeight=d.getLineHeight(),c.$updatePrintMargin(),c.onResize(!0),c.$loop.schedule(c.CHANGE_FULL)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:1,characterWidth:1,minHeight:1,maxHeight:1,offset:0,height:1},this.$loop=new o(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.setPadding(4),this.$updatePrintMargin()};(function(){this.showGutter=!0,this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,this.CHANGE_H_SCROLL=1024,d.implement(this,p),this.setSession=function(a){this.session=a,this.$cursorLayer.setSession(a),this.$markerBack.setSession(a),this.$markerFront.setSession(a),this.$gutterLayer.setSession(a),this.$textLayer.setSession(a),this.$loop.schedule(this.CHANGE_FULL)},this.updateLines=function(a,b){b===undefined&&(b=Infinity),this.$changedLines?(this.$changedLines.firstRow>a&&(this.$changedLines.firstRow=a),this.$changedLines.lastRowc.lastRow+1)return;if(bd&&this.session.setScrollTop(d),this.scrollTop+this.$size.scrollerHeightc&&(c0)return!0;if(b>0&&this.session.getScrollTop()+this.$size.scrollerHeighth&&(e=g.end.row+1,g=this.session.getNextFoldLine(e,g),h=g?g.start.row:Infinity);if(e>f)break;var j=this.$annotations[e]||b;c.push("
    ",e+1);if(i){var k=i[e];k==null&&(k=i[e]=this.session.getFoldWidget(e)),k&&c.push("")}var l=this.session.getRowLength(e)-1;while(l--)c.push("
    ¦");c.push("
    "),e++}this.element=d.setInnerHtml(this.element,c.join("")),this.element.style.height=a.minHeight+"px";var m=this.element.offsetWidth;m!==this.gutterWidth&&(this.gutterWidth=m,this._emit("changeGutterWidth",m))},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(a){a?d.addCssClass(this.element,"ace_folding-enabled"):d.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=a},this.getShowFoldWidgets=function(){return this.$showFoldWidgets}}).call(g.prototype),b.Gutter=g}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../range").Range,e=a("../lib/dom"),f=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_marker-layer",a.appendChild(this.element)};(function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.setMarkers=function(a){this.markers=a},this.update=function(a){var a=a||this.config;if(!a)return;this.config=a;var b=[];for(var c in this.markers){var d=this.markers[c],f=d.range.clipRows(a.firstRow,a.lastRow);if(f.isEmpty())continue;f=f.toScreenRange(this.session);if(d.renderer){var g=this.$getTop(f.start.row,a),h=Math.round(this.$padding+f.start.column*a.characterWidth);d.renderer(b,f,h,g,a)}else f.isMultiLine()?d.type=="text"?this.drawTextMarker(b,f,d.clazz,a):this.drawMultiLineMarker(b,f,d.clazz,a,d.type):this.drawSingleLineMarker(b,f,d.clazz,a,null,d.type)}this.element=e.setInnerHtml(this.element,b.join(""))},this.$getTop=function(a,b){return(a-b.firstRowScreen)*b.lineHeight},this.drawTextMarker=function(a,b,c,e){var f=b.start.row,g=new d(f,b.start.column,f,this.session.getScreenLastRowColumn(f));this.drawSingleLineMarker(a,g,c,e,1,"text"),f=b.end.row,g=new d(f,0,f,b.end.column),this.drawSingleLineMarker(a,g,c,e,0,"text");for(f=b.start.row+1;f"),j=this.$getTop(b.end.row,d),i=Math.round(b.end.column*d.characterWidth),a.push("
    "),h=(b.end.row-b.start.row-1)*d.lineHeight;if(h<0)return;j=this.$getTop(b.start.row+1,d),a.push("
    ")},this.drawSingleLineMarker=function(a,b,c,d,e,f){var g=f==="background"?0:this.$padding,h=d.lineHeight;if(f==="background")var i=d.width;else i=Math.round((b.end.column+(e||0)-b.start.column)*d.characterWidth);var j=this.$getTop(b.start.row,d),k=Math.round(g+b.start.column*d.characterWidth);a.push("
    ")}}).call(f.prototype),b.Marker=f}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/dom"),f=a("../lib/lang"),g=a("../lib/useragent"),h=a("../lib/event_emitter").EventEmitter,i=function(a){this.element=e.createElement("div"),this.element.className="ace_layer ace_text-layer",a.appendChild(this.element),this.$characterSize=this.$measureSizes()||{width:0,height:0},this.$pollSizeChanges()};(function(){d.implement(this,h),this.EOF_CHAR="¶",this.EOL_CHAR="¬",this.TAB_CHAR="→",this.SPACE_CHAR="·",this.$padding=0,this.setPadding=function(a){this.$padding=a,this.element.style.padding="0 "+a+"px"},this.getLineHeight=function(){return this.$characterSize.height||1},this.getCharacterWidth=function(){return this.$characterSize.width||1},this.checkForSizeChanges=function(){var a=this.$measureSizes();a&&(this.$characterSize.width!==a.width||this.$characterSize.height!==a.height)&&(this.$characterSize=a,this._emit("changeCharacterSize",{data:a}))},this.$pollSizeChanges=function(){var a=this;this.$pollSizeChangesTimer=setInterval(function(){a.checkForSizeChanges()},500)},this.$fontStyles={fontFamily:1,fontSize:1,fontWeight:1,fontStyle:1,lineHeight:1},this.$measureSizes=g.isIE||g.isOldGecko?function(){var a=1e3;if(!this.$measureNode){var b=this.$measureNode=e.createElement("div"),c=b.style;c.width=c.height="auto",c.left=c.top=-a*40+"px",c.visibility="hidden",c.position="fixed",c.overflow="visible",c.whiteSpace="nowrap",b.innerHTML=f.stringRepeat("Xy",a);if(this.element.ownerDocument.body)this.element.ownerDocument.body.appendChild(b);else{var d=this.element.parentNode;while(!e.hasCssClass(d,"ace_editor"))d=d.parentNode;d.appendChild(b)}}if(!this.element.offsetWidth)return null;var c=this.$measureNode.style,g=e.computedStyle(this.element);for(var h in this.$fontStyles)c[h]=g[h];var i={height:this.$measureNode.offsetHeight,width:this.$measureNode.offsetWidth/(a*2)};return i.width==0||i.height==0?null:i}:function(){if(!this.$measureNode){var a=this.$measureNode=e.createElement("div"),b=a.style;b.width=b.height="auto",b.left=b.top="-100px",b.visibility="hidden",b.position="fixed",b.overflow="visible",b.whiteSpace="nowrap",a.innerHTML="X";var c=this.element.parentNode;while(c&&!e.hasCssClass(c,"ace_editor"))c=c.parentNode;if(!c)return this.$measureNode=null;c.appendChild(a)}var d=this.$measureNode.getBoundingClientRect(),f={height:d.height,width:d.width};return f.width==0||f.height==0?null:f},this.setSession=function(a){this.session=a},this.showInvisibles=!1,this.setShowInvisibles=function(a){return this.showInvisibles==a?!1:(this.showInvisibles=a,!0)},this.$tabStrings=[],this.$computeTabString=function(){var a=this.session.getTabSize(),b=this.$tabStrings=[0];for(var c=1;c"+this.TAB_CHAR+(new Array(c)).join(" ")+""):b.push((new Array(c+1)).join(" "))},this.updateLines=function(a,b,c){this.$computeTabString(),(this.config.lastRow!=a.lastRow||this.config.firstRow!=a.firstRow)&&this.scrollLines(a),this.config=a;var d=Math.max(b,a.firstRow),f=Math.min(c,a.lastRow),g=this.element.childNodes,h=0;for(var i=a.firstRow;i0;d--)c.removeChild(c.firstChild);if(b.lastRow>a.lastRow)for(var d=this.session.getFoldedRowCount(a.lastRow+1,b.lastRow);d>0;d--)c.removeChild(c.lastChild);if(a.firstRowb.lastRow){var e=this.$renderLinesFragment(a,b.lastRow+1,a.lastRow);c.appendChild(e)}},this.$renderLinesFragment=function(a,b,c){var d=this.element.ownerDocument.createDocumentFragment(),f=b,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>c)break;var i=e.createElement("div"),j=[],k=this.session.getTokens(f,f);k.length==1&&this.$renderLine(j,f,k[0].tokens,!1),i.innerHTML=j.join("");if(this.$useLineGroups())i.className="ace_line_group",d.appendChild(i);else{var l=i.childNodes;while(l.length)d.appendChild(l[0])}f++}return d},this.update=function(a){this.$computeTabString(),this.config=a;var b=[],c=a.firstRow,d=a.lastRow,f=c,g=this.session.getNextFoldLine(f),h=g?g.start.row:Infinity;for(;;){f>h&&(f=g.end.row+1,g=this.session.getNextFoldLine(f,g),h=g?g.start.row:Infinity);if(f>d)break;this.$useLineGroups()&&b.push("
    ");var i=this.session.getTokens(f,f);i.length==1&&this.$renderLine(b,f,i[0].tokens,!1),this.$useLineGroups()&&b.push("
    "),f++}this.element=e.setInnerHtml(this.element,b.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(a,b,c,d){var e=this,f=/\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g,h=function(a,c,d,f,h){if(a.charCodeAt(0)==32)return(new Array(a.length+1)).join(" ");if(a==" "){var i=e.session.getScreenTabSize(b+f);return b+=i-1,e.$tabStrings[i]}if(a=="&")return g.isOldGecko?"&":"&";if(a=="<")return"<";if(a==" "){var j=e.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",k=e.showInvisibles?e.SPACE_CHAR:"";return b+=1,""+k+""}if(a.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)){if(e.showInvisibles){var k=(new Array(a.length+1)).join(e.SPACE_CHAR);return""+k+""}return" "}return b+=1,""+a+""},i=d.replace(f,h);if(!this.$textToken[c.type]){var j="ace_"+c.type.replace(/\./g," ace_"),k="";c.type=="fold"&&(k=" style='width:"+c.value.length*this.config.characterWidth+"px;' "),a.push("",i,"")}else a.push(i);return b+d.length},this.$renderLineCore=function(a,b,c,d,e){var f=0,g=0,h,i=0,j=this;!d||d.length==0?h=Number.MAX_VALUE:h=d[0],e||a.push("
    ");for(var k=0;k=h)i=j.$renderToken(a,i,l,m.substring(0,h-f)),m=m.substring(h-f),f=h,e||a.push("
    ","
    "),g++,i=0,h=d[g]||Number.MAX_VALUE;m.length!=0&&(f+=m.length,i=j.$renderToken(a,i,l,m))}}this.showInvisibles&&(b!==this.session.getLength()-1?a.push(""+this.EOL_CHAR+""):a.push(""+this.EOF_CHAR+"")),e||a.push("
    ")},this.$renderLine=function(a,b,c,d){if(!this.session.isRowFolded(b)){var e=this.session.getRowSplitData(b);this.$renderLineCore(a,b,c,e,d)}else this.$renderFoldLine(a,b,c,d)},this.$renderFoldLine=function(a,b,c,d){function h(a,b,c){var d=0,e=0;while(e+a[d].value.lengthc-b&&(f=f.substring(0,c-b)),g.push({type:a[d].type,value:f}),e=b+f.length,d+=1}while(ec&&(f=f.substring(0,c-e)),g.push({type:a[d].type,value:f}),e+=f.length,d+=1}}var e=this.session,f=e.getFoldLine(b),g=[];f.walk(function(a,b,d,e,f){a?g.push({type:"fold",value:a}):(f&&(c=this.session.getTokens(b,b)[0].tokens),c.length!=0&&h(c,e,d))}.bind(this),f.end.row,this.session.getLine(f.end.row).length);var i=this.session.$useWrapMode?this.session.$wrapData[b]:null;this.$renderLineCore(a,b,g,i,d)},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}}).call(i.prototype),b.Text=i}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(a,b,c){"use strict";var d=a("../lib/dom"),e=function(a){this.element=d.createElement("div"),this.element.className="ace_layer ace_cursor-layer",a.appendChild(this.element),this.isVisible=!1,this.cursors=[],this.cursor=this.addCursor()};(function(){this.$padding=0,this.setPadding=function(a){this.$padding=a},this.setSession=function(a){this.session=a},this.addCursor=function(){var a=d.createElement("div"),b="ace_cursor";return this.isVisible||(b+=" ace_hidden"),this.overwrite&&(b+=" ace_overwrite"),a.className=b,this.element.appendChild(a),this.cursors.push(a),a},this.removeCursor=function(){if(this.cursors.length>1){var a=this.cursors.pop();return a.parentNode.removeChild(a),a}},this.hideCursor=function(){this.isVisible=!1;for(var a=this.cursors.length;a--;)d.addCssClass(this.cursors[a],"ace_hidden");clearInterval(this.blinkId)},this.showCursor=function(){this.isVisible=!0;for(var a=this.cursors.length;a--;)d.removeCssClass(this.cursors[a],"ace_hidden");this.element.style.visibility="",this.restartTimer()},this.restartTimer=function(){clearInterval(this.blinkId);if(!this.isVisible)return;var a=this.element;this.blinkId=setInterval(function(){a.style.visibility="hidden",setTimeout(function(){a.style.visibility="visible"},400)},1e3)},this.getPixelPosition=function(a,b){if(!this.config||!this.session)return{left:0,top:0};a||(a=this.session.selection.getCursor());var c=this.session.documentToScreenPosition(a),d=Math.round(this.$padding+c.column*this.config.characterWidth),e=(c.row-(b?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:d,top:e}},this.update=function(a){this.config=a;if(this.session.selectionMarkerCount>1){var b=this.session.$selectionMarkers,c=0,d,e=0;for(var c=b.length;c--;){d=b[c];var f=this.getPixelPosition(d.cursor,!0),g=(this.cursors[e++]||this.addCursor()).style;g.left=f.left+"px",g.top=f.top+"px",g.width=a.characterWidth+"px",g.height=a.lineHeight+"px"}if(e>1)while(this.cursors.length>e)this.removeCursor()}else{var f=this.getPixelPosition(null,!0),g=this.cursor.style;g.left=f.left+"px",g.top=f.top+"px",g.width=a.characterWidth+"px",g.height=a.lineHeight+"px";while(this.cursors.length>1)this.removeCursor()}var h=this.session.getOverwrite();h!=this.overwrite&&this.$setOverite(h),this.restartTimer()},this.$setOverite=function(a){this.overwrite=a;for(var b=this.cursors.length;b--;)a?d.addCssClass(this.cursors[b],"ace_overwrite"):d.removeCssClass(this.cursors[b],"ace_overwrite")},this.destroy=function(){clearInterval(this.blinkId)}}).call(e.prototype),b.Cursor=e}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("./lib/oop"),e=a("./lib/dom"),f=a("./lib/event"),g=a("./lib/event_emitter").EventEmitter,h=function(a){this.element=e.createElement("div"),this.element.className="ace_sb",this.inner=e.createElement("div"),this.element.appendChild(this.inner),a.appendChild(this.element),this.width=e.scrollbarWidth(a.ownerDocument),this.element.style.width=(this.width||15)+5+"px",f.addListener(this.element,"scroll",this.onScroll.bind(this))};(function(){d.implement(this,g),this.onScroll=function(){this._emit("scroll",{data:this.element.scrollTop})},this.getWidth=function(){return this.width},this.setHeight=function(a){this.element.style.height=a+"px"},this.setInnerHeight=function(a){this.inner.style.height=a+"px"},this.setScrollTop=function(a){this.element.scrollTop=a}}).call(h.prototype),b.ScrollBar=h}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(a,b,c){"use strict";var d=a("./lib/event"),e=function(a,b){this.onRender=a,this.pending=!1,this.changes=0,this.window=b||window};(function(){this.schedule=function(a){this.changes=this.changes|a;if(!this.pending){this.pending=!0;var b=this;d.nextTick(function(){b.pending=!1;var a;while(a=b.changes)b.changes=0,b.onRender(a)},this.window)}}}).call(e.prototype),b.RenderLoop=e}),define("text!ace/css/editor.css",[],"@import url(//fonts.googleapis.com/css?family=Droid+Sans+Mono);\n\n.ace_editor {\n position: absolute;\n overflow: hidden;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Consolas', monospace;\n font-size: 12px;\n}\n\n.ace_scroller {\n position: absolute;\n overflow-x: scroll;\n overflow-y: hidden;\n}\n\n.ace_content {\n position: absolute;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n cursor: text;\n}\n\n.ace_composition {\n position: absolute;\n background: #555;\n color: #DDD;\n z-index: 4;\n}\n\n.ace_gutter {\n position: absolute;\n overflow : hidden;\n height: 100%;\n width: auto;\n cursor: default;\n z-index: 1000;\n}\n\n.ace_gutter.horscroll {\n box-shadow: 0px 0px 20px rgba(0,0,0,0.4);\n}\n\n.ace_gutter-cell {\n padding-left: 19px;\n padding-right: 6px;\n}\n\n.ace_gutter-cell.ace_error {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_warning {\n background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_gutter-cell.ace_info {\n background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n background-repeat: no-repeat;\n background-position: 2px center;\n}\n\n.ace_editor .ace_sb {\n position: absolute;\n overflow-x: hidden;\n overflow-y: scroll;\n right: 0;\n}\n\n.ace_editor .ace_sb div {\n position: absolute;\n width: 1px;\n left: 0;\n}\n\n.ace_editor .ace_print_margin_layer {\n z-index: 0;\n position: absolute;\n overflow: hidden;\n margin: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.ace_editor .ace_print_margin {\n position: absolute;\n height: 100%;\n}\n\n.ace_editor textarea {\n position: fixed;\n z-index: 0;\n width: 10px;\n height: 30px;\n opacity: 0;\n background: transparent;\n appearance: none;\n -moz-appearance: none;\n border: none;\n resize: none;\n outline: none;\n overflow: hidden;\n}\n\n.ace_layer {\n z-index: 1;\n position: absolute;\n overflow: hidden;\n white-space: nowrap;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n /* setting pointer-events: auto; on node under the mouse, which changes\n during scroll, will break mouse wheel scrolling in Safari */\n pointer-events: none;\n}\n\n.ace_gutter .ace_layer {\n position: relative;\n min-width: 40px;\n text-align: right;\n pointer-events: auto;\n}\n\n.ace_text-layer {\n color: black;\n}\n\n.ace_cjk {\n display: inline-block;\n text-align: center;\n}\n\n.ace_cursor-layer {\n z-index: 4;\n}\n\n.ace_cursor {\n z-index: 4;\n position: absolute;\n}\n\n.ace_cursor.ace_hidden {\n opacity: 0.2;\n}\n\n.ace_line {\n white-space: nowrap;\n}\n\n.ace_marker-layer .ace_step {\n position: absolute;\n z-index: 3;\n}\n\n.ace_marker-layer .ace_selection {\n position: absolute;\n z-index: 5;\n}\n\n.ace_marker-layer .ace_bracket {\n position: absolute;\n z-index: 6;\n}\n\n.ace_marker-layer .ace_active_line {\n position: absolute;\n z-index: 2;\n}\n\n.ace_gutter .ace_gutter_active_line{\n background-color : #dcdcdc;\n}\n\n.ace_marker-layer .ace_selected_word {\n position: absolute;\n z-index: 4;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n}\n\n.ace_line .ace_fold {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n \n display: inline-block;\n height: 11px;\n margin-top: -2px;\n vertical-align: middle;\n\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n color: transparent;\n\n border: 1px solid black;\n -moz-border-radius: 2px;\n -webkit-border-radius: 2px;\n border-radius: 2px;\n \n cursor: pointer;\n pointer-events: auto;\n}\n\n.ace_dark .ace_fold {\n}\n\n.ace_fold:hover{\n background-image: \n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat, repeat-x;\n background-position: center center, top left;\n}\n\n.ace_dragging .ace_content {\n cursor: move;\n}\n\n.ace_folding-enabled > .ace_gutter-cell {\n padding-right: 13px;\n}\n\n.ace_fold-widget {\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n\n margin: 0 -12px 1px 1px;\n display: inline-block;\n height: 14px;\n width: 11px;\n vertical-align: text-bottom;\n \n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n background-repeat: no-repeat;\n background-position: center 5px;\n\n border-radius: 3px;\n}\n\n.ace_fold-widget.end {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget.closed {\n background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n}\n\n.ace_fold-widget:hover {\n border: 1px solid rgba(0, 0, 0, 0.3);\n background-color: rgba(255, 255, 255, 0.2);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n background-position: center 4px;\n}\n\n.ace_fold-widget:active {\n border: 1px solid rgba(0, 0, 0, 0.4);\n background-color: rgba(0, 0, 0, 0.05);\n -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n}\n\n.ace_fold-widget.invalid {\n background-color: #FFB4B4;\n border-color: #DE5555;\n}\n"),define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor"],function(a,b,c){function j(a,b,c){return i.$options.wrap=!0,i.$options.needle=b,i.$options.backwards=c==-1,i.find(a)}function m(a,b){return a.row==b.row&&a.column==b.column}function n(a){a.$onAddRange=a.$onAddRange.bind(a),a.$onRemoveRange=a.$onRemoveRange.bind(a),a.$onMultiSelect=a.$onMultiSelect.bind(a),a.$onSingleSelect=a.$onSingleSelect.bind(a),b.onSessionChange.call(a,a),a.on("changeSession",b.onSessionChange.bind(a)),a.on("mousedown",g),a.commands.addCommands(b.commands.defaultCommands)}var d=a("./range_list").RangeList,e=a("./range").Range,f=a("./selection").Selection,g=a("./mouse/multi_select_handler").onMouseDown;b.commands=a("./commands/multi_select_commands");var h=a("./search").Search,i=new h,k=a("./edit_session").EditSession;(function(){this.getSelectionMarkers=function(){return this.$selectionMarkers}}).call(k.prototype),function(){this.ranges=null,this.rangeList=null,this.addRange=function(a){if(!this.inMultiSelectMode&&this.rangeCount==0){var b=this.toOrientedRange();if(!a||!a.isEqual(b))this.rangeList.add(b),this.$onAddRange(b)}if(!a)return;a.cursor||(a.cursor=a.end);var c=this.rangeList.add(a);this.$onAddRange(a),c.length&&this.$onRemoveRange(c),this.rangeCount>0&&!this.inMultiSelectMode&&(this._emit("multiSelect"),this.inMultiSelectMode=!0,this.session.$undoSelect=!1,this.rangeList.attach(this.session))},this.toSingleRange=function(a){a=a||this.ranges[0];var b=this.rangeList.removeAll();b.length&&this.$onRemoveRange(b),a&&this.fromOrientedRange(a)},this.substractPoint=function(a){var b=this.rangeList.substractPoint(a);if(b)return this.$onRemoveRange(b),b[0]},this.mergeOverlappingRanges=function(){var a=this.rangeList.merge();a.length?this.$onRemoveRange(a):this.ranges[0]&&this.fromOrientedRange(this.ranges[0])},this.$onAddRange=function(a){this.rangeCount=this.rangeList.ranges.length,this.ranges.unshift(a),this.fromOrientedRange(a),this._emit("addRange",{range:a})},this.$onRemoveRange=function(a){this.rangeCount=this.rangeList.ranges.length;if(this.rangeCount==1&&this.inMultiSelectMode){var b=this.rangeList.ranges.pop();a.push(b),this.rangeCount=0}for(var c=a.length;c--;){var d=this.ranges.indexOf(a[c]);this.ranges.splice(d,1)}this._emit("removeRange",{ranges:a}),this.rangeCount==0&&this.inMultiSelectMode&&(this.inMultiSelectMode=!1,this._emit("singleSelect"),this.session.$undoSelect=!0,this.rangeList.detach(this.session)),b=b||this.ranges[0],b&&!b.isEqual(this.getRange())&&this.fromOrientedRange(b)},this.$initRangeList=function(){if(this.rangeList)return;this.rangeList=new d,this.ranges=[],this.rangeCount=0},this.getAllRanges=function(){return this.rangeList.ranges.concat()},this.splitIntoLines=function(){if(this.rangeCount>1){var a=this.rangeList.ranges,b=a[a.length-1],c=e.fromPoints(a[0].start,b.end);this.toSingleRange(),this.setSelectionRange(c,b.cursor==b.start)}else{var d=this.session.documentToScreenPosition(this.selectionLead),f=this.session.documentToScreenPosition(this.selectionAnchor),g=this.rectangularRangeBlock(d,f);g.forEach(this.addRange,this)}},this.rectangularRangeBlock=function(a,b,c){var d=[],f=a.column0)p--;if(p>0){var q=0;while(d[q].isEmpty())q++}for(var r=p;r>=q;r--)d[r].isEmpty()&&d.splice(r,1)}return d}}.call(f.prototype);var l=a("./editor").Editor;(function(){this.updateSelectionMarkers=function(){this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.addSelectionMarker=function(a){a.cursor||(a.cursor=a.end);var b=this.getSelectionStyle();return a.marker=this.session.addMarker(a,"ace_selection",b),this.session.$selectionMarkers.push(a),this.session.selectionMarkerCount=this.session.$selectionMarkers.length,a},this.removeSelectionMarkers=function(a){for(var b=a.length;b--;){var c=a[b];if(!c.marker)continue;this.session.removeMarker(c.marker);var d=this.session.$selectionMarkers.indexOf(c);d!=-1&&this.session.$selectionMarkers.splice(d,1)}this.session.selectionMarkerCount=this.session.$selectionMarkers.length},this.$onAddRange=function(a){this.addSelectionMarker(a.range),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onRemoveRange=function(a){this.removeSelectionMarkers(a.ranges),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onMultiSelect=function(a){if(this.inMultiSelectMode)return;this.inMultiSelectMode=!0,this.setStyle("multiselect"),this.keyBinding.addKeyboardHandler(b.commands.keyboardHandler),this.commands.on("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onSingleSelect=function(a){if(this.session.multiSelect.inVirtualMode)return;this.inMultiSelectMode=!1,this.unsetStyle("multiselect"),this.keyBinding.removeKeyboardHandler(b.commands.keyboardHandler),this.commands.removeEventListener("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onMultiSelectExec=function(a){var b=a.command,c=a.editor;b.multiSelectAction?b.multiSelectAction=="forEach"?c.forEachSelection(b,a.args):b.multiSelectAction=="single"?(c.exitMultiSelectMode(),b.exec(c,a.args||{})):b.multiSelectAction(c,a.args||{}):(b.exec(c,a.args||{}),c.multiSelect.addRange(c.multiSelect.toOrientedRange()),c.multiSelect.mergeOverlappingRanges()),a.preventDefault()},this.forEachSelection=function(a,b){if(this.inVirtualSelectionMode)return;var c=this.session,d=this.selection,e=d.rangeList,g=d._eventRegistry;d._eventRegistry={};var h=new f(c);this.inVirtualSelectionMode=!0;for(var i=e.ranges.length;i--;)h.fromOrientedRange(e.ranges[i]),this.selection=c.selection=h,a.exec(this,b||{}),h.toOrientedRange(e.ranges[i]);h.detach(),this.selection=c.selection=d,this.inVirtualSelectionMode=!1,d._eventRegistry=g,d.mergeOverlappingRanges(),this.onCursorChange(),this.onSelectionChange()},this.exitMultiSelectMode=function(){if(this.inVirtualSelectionMode)return;this.multiSelect.toSingleRange()},this.getCopyText=function(){var a="";if(this.inMultiSelectMode){var b=this.multiSelect.rangeList.ranges;a=[];for(var c=0;c0)continue;return f==0?d:(f=this.comparePoints(a,e.start),f>=0?d:-d-1)}return-d-1},this.add=function(a){var b=this.pointIndex(a.start);b<0&&(b=-b-1);var c=this.pointIndex(a.end,b);return c<0?c=-c-1:c++,this.ranges.splice(b,c-b,a)},this.addList=function(a){var b=[];for(var c=a.length;c--;)b.push.call(b,this.add(a[c]));return b},this.substractPoint=function(a){var b=this.pointIndex(a);if(b>=0)return this.ranges.splice(b,1)},this.merge=function(){var a=[],b=this.ranges,c=b[0],d;for(var e=1;e=0},this.containsPoint=function(a){return this.pointIndex(a)>=0},this.rangeAtPoint=function(a){var b=this.pointIndex(a);if(b>=0)return this.ranges[b]},this.clipRows=function(a,b){var c=this.ranges;if(c[0].start.row>b||c[c.length-1].start.rowe)break;l.start.row==e&&l.start.column>=c.column&&(l.start.column+=h,l.start.row+=g),l.end.row==e&&l.end.column>=c.column&&(l.end.column+=h,l.end.row+=g)}if(g!=0&&j=this.pos.column&&c.start.column<=this.pos.column+this.length+1){var f=c.start.column-this.pos.column;this.length+=e;if(!this.session.$fromUndo){if(b.action==="insertText")for(var g=this.others.length-1;g>=0;g--){var h=this.others[g],i={row:h.row,column:h.column+f};h.row===c.start.row&&c.start.column=0;g--){var h=this.others[g],i={row:h.row,column:h.column+f};h.row===c.start.row&&c.start.column=this.pos.column&&b.column<=this.pos.column+this.length?(this.showOtherMarkers(),this._emit("cursorEnter",a)):(this.hideOtherMarkers(),this._emit("cursorLeave",a))},this.detach=function(){this.session.removeMarker(this.markerId),this.hideOtherMarkers(),this.doc.removeEventListener("change",this.$onUpdate),this.session.selection.removeEventListener("changeCursor",this.$onCursorChange),this.pos.detach();for(var a=0;a selection.start.column) { break; @@ -674,19 +675,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -695,7 +696,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -705,7 +706,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -916,13 +918,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-c_cpp.js b/apps/files_texteditor/js/aceeditor/mode-c_cpp.js index c49e93eb937..078afcaa783 100644 --- a/apps/files_texteditor/js/aceeditor/mode-c_cpp.js +++ b/apps/files_texteditor/js/aceeditor/mode-c_cpp.js @@ -1 +1 @@ -define("ace/mode/c_cpp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/c_cpp_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./c_cpp_highlight_rules").c_cppHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/c_cpp_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("and|double|not_eq|throw|and_eq|dynamic_cast|operator|true|asm|else|or|try|auto|enum|or_eq|typedef|bitand|explicit|private|typeid|bitor|extern|protected|typename|bool|false|public|union|break|float|register|unsigned|case|fro|reinterpret-cast|using|catch|friend|return|virtual|char|goto|short|void|class|if|signed|volatile|compl|inline|sizeof|wchar_t|const|int|static|while|const-cast|long|static_cast|xor|continue|mutable|struct|xor_eq|default|namespace|switch|delete|new|template|do|not|this|for".split("|")),b=e.arrayToMap("NULL".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",merge:!0,regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",merge:!0,regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant",regex:"<[a-zA-Z0-9.]+>"},{token:"keyword",regex:"(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.c_cppHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/c_cpp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/c_cpp_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./c_cpp_highlight_rules").c_cppHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/c_cpp_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("and|double|not_eq|throw|and_eq|dynamic_cast|operator|true|asm|else|or|try|auto|enum|or_eq|typedef|bitand|explicit|private|typeid|bitor|extern|protected|typename|bool|false|public|union|break|float|register|unsigned|case|fro|reinterpret-cast|using|catch|friend|return|virtual|char|goto|short|void|class|if|signed|volatile|compl|inline|sizeof|wchar_t|const|int|static|while|const-cast|long|static_cast|xor|continue|mutable|struct|xor_eq|default|namespace|switch|delete|new|template|do|not|this|for".split("|")),b=e.arrayToMap("NULL".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",merge:!0,regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",merge:!0,regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant",regex:"<[a-zA-Z0-9.]+>"},{token:"keyword",regex:"(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.c_cppHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-clojure-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-clojure-uncompressed.js index eb99ceb3eea..cb0081316f0 100755 --- a/apps/files_texteditor/js/aceeditor/mode-clojure-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-clojure-uncompressed.js @@ -259,9 +259,9 @@ var ClojureHighlightRules = function() { token : "comment", regex : ";.*$" }, { - token : "comment", // multi line comment - regex : "^\=begin$", - next : "comment" + token : "comment", // multi line comment + regex : "^=begin$", + next : "comment" }, { token : "keyword", //parens regex : "[\\(|\\)]" @@ -314,17 +314,17 @@ var ClojureHighlightRules = function() { regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // symbol - regex : "[:](?:[a-zA-Z]|\d)+" + regex : "[:](?:[a-zA-Z]|\\d)+" }, { - token : "string.regexp", //Regular Expressions - regex : '/#"(?:\.|(\\\")|[^\""\n])*"/g' + token : "string.regexp", //Regular Expressions + regex : '/#"(?:\\.|(?:\\\")|[^\""\n])*"/g' } - + ], "comment" : [ { token : "comment", // closing comment - regex : "^\=end$", + regex : "^=end$", next : "start" }, { token : "comment", // comment spanning whole line @@ -420,13 +420,3 @@ var MatchingParensOutdent = function() {}; exports.MatchingParensOutdent = MatchingParensOutdent; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-clojure.js b/apps/files_texteditor/js/aceeditor/mode-clojure.js index 74e69fb0086..3afd7673f8e 100644 --- a/apps/files_texteditor/js/aceeditor/mode-clojure.js +++ b/apps/files_texteditor/js/aceeditor/mode-clojure.js @@ -1 +1 @@ -define("ace/mode/clojure",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/clojure_highlight_rules","ace/mode/matching_parens_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./clojure_highlight_rules").ClojureHighlightRules,h=a("./matching_parens_outdent").MatchingParensOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,";")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/[\(\[]/);g&&(d+=" "),g=b.match(/[\)]/),g&&(d="")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/clojure_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - -> -> ->> ->> .. / < < <= <= = == > > >= >= accessor aclone add-classpath add-watch agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq zero? zipmap ".split(" ")),b=e.arrayToMap("def do fn if let loop monitor-enter monitor-exit new quote recur set! throw try var".split(" ")),c=e.arrayToMap("true false nil".split(" "));this.$rules={start:[{token:"comment",regex:";.*$"},{token:"comment",regex:"^=begin$",next:"comment"},{token:"keyword",regex:"[\\(|\\)]"},{token:"keyword",regex:"[\\'\\(]"},{token:"keyword",regex:"[\\[|\\]]"},{token:"keyword",regex:"[\\{|\\}|\\#\\{|\\#\\}]"},{token:"keyword",regex:"[\\&]"},{token:"keyword",regex:"[\\#\\^\\{]"},{token:"keyword",regex:"[\\%]"},{token:"keyword",regex:"[@]"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language",regex:"[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]"},{token:function(d){return b.hasOwnProperty(d)?"keyword":c.hasOwnProperty(d)?"constant.language":a.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"[:](?:[a-zA-Z]|d)+"},{token:"string.regexp",regex:'/#"(?:.|(\\")|[^""\n])*"/g'}],comment:[{token:"comment",regex:"^=end$",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.ClojureHighlightRules=g}),define("ace/mode/matching_parens_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\)/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\))/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingParensOutdent=e}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/clojure",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/clojure_highlight_rules","ace/mode/matching_parens_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./clojure_highlight_rules").ClojureHighlightRules,h=a("./matching_parens_outdent").MatchingParensOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,";")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/[\(\[]/);g&&(d+=" "),g=b.match(/[\)]/),g&&(d="")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/clojure_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - -> -> ->> ->> .. / < < <= <= = == > > >= >= accessor aclone add-classpath add-watch agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq zero? zipmap ".split(" ")),b=e.arrayToMap("def do fn if let loop monitor-enter monitor-exit new quote recur set! throw try var".split(" ")),c=e.arrayToMap("true false nil".split(" "));this.$rules={start:[{token:"comment",regex:";.*$"},{token:"comment",regex:"^=begin$",next:"comment"},{token:"keyword",regex:"[\\(|\\)]"},{token:"keyword",regex:"[\\'\\(]"},{token:"keyword",regex:"[\\[|\\]]"},{token:"keyword",regex:"[\\{|\\}|\\#\\{|\\#\\}]"},{token:"keyword",regex:"[\\&]"},{token:"keyword",regex:"[\\#\\^\\{]"},{token:"keyword",regex:"[\\%]"},{token:"keyword",regex:"[@]"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language",regex:"[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]"},{token:function(d){return b.hasOwnProperty(d)?"keyword":c.hasOwnProperty(d)?"constant.language":a.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"[:](?:[a-zA-Z]|\\d)+"},{token:"string.regexp",regex:'/#"(?:\\.|(?:\\")|[^""\n])*"/g'}],comment:[{token:"comment",regex:"^=end$",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.ClojureHighlightRules=g}),define("ace/mode/matching_parens_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\)/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\))/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingParensOutdent=e}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-coffee-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-coffee-uncompressed.js index 9a06cbfcfe9..de6cbf4137c 100755 --- a/apps/files_texteditor/js/aceeditor/mode-coffee-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-coffee-uncompressed.js @@ -603,202 +603,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i|->|\\s*class [^#]*")}"use strict";var d=a("../tokenizer").Tokenizer,e=a("./coffee_highlight_rules").CoffeeHighlightRules,f=a("./matching_brace_outdent").MatchingBraceOutdent,g=a("./folding/pythonic").FoldMode,h=a("../range").Range,i=a("./text").Mode,j=a("../worker/worker_client").WorkerClient,k=a("../lib/oop");k.inherits(l,i),function(){var a=/(?:[({[=:]|[-=]>|\b(?:else|switch|try|catch(?:\s*[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)?|finally))\s*$/,b=/^(\s*)#/,c=/^\s*###(?!#)/,d=/^\s*/;this.getNextLineIndent=function(b,c,d){var e=this.$getIndent(c),f=this.$tokenizer.getLineTokens(c,b).tokens;return(!f.length||f[f.length-1].type!=="comment")&&b==="start"&&a.test(c)&&(e+=d),e},this.toggleCommentLines=function(a,e,f,g){console.log("toggle");var i=new h(0,0,0,0);for(var j=f;j<=g;++j){var k=e.getLine(j);if(c.test(k))continue;b.test(k)?k=k.replace(b,"$1"):k=k.replace(d,"$&#"),i.end.row=i.start.row=j,i.end.column=k.length+1,e.replace(i,k)}},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-coffee.js","ace/mode/coffee_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("error",function(b){a.setAnnotations([b.data])}),b.on("ok",function(b){a.clearAnnotations()}),b}}.call(l.prototype),b.Mode=l}),define("ace/mode/coffee_highlight_rules",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){function g(){var a="[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*",b={token:"string",merge:!0,regex:".+"},c=d.arrayToMap("this|throw|then|try|typeof|super|switch|return|break|by)|continue|catch|class|in|instanceof|is|isnt|if|else|extends|for|forown|finally|function|while|when|new|no|not|delete|debugger|do|loop|of|off|or|on|unless|until|and|yes".split("|")),e=d.arrayToMap("true|false|null|undefined".split("|")),f=d.arrayToMap("case|const|default|function|var|void|with|enum|export|implements|interface|let|package|private|protected|public|static|yield|__hasProp|extends|slice|bind|indexOf".split("|")),g=d.arrayToMap("Array|Boolean|Date|Function|Number|Object|RegExp|ReferenceError|RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError".split("|")),h=d.arrayToMap("Math|JSON|isNaN|isFinite|parseInt|parseFloat|encodeURI|encodeURIComponent|decodeURI|decodeURIComponent|RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError".split("|"));this.$rules={start:[{token:"identifier",regex:"(?:(?:\\.|::)\\s*)"+a},{token:"variable",regex:"@(?:"+a+")?"},{token:function(a){return c.hasOwnProperty(a)?"keyword":e.hasOwnProperty(a)?"constant.language":f.hasOwnProperty(a)?"invalid.illegal":g.hasOwnProperty(a)?"language.support.class":h.hasOwnProperty(a)?"language.support.function":"identifier"},regex:a},{token:"constant.numeric",regex:"(?:0x[\\da-fA-F]+|(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?)"},{token:"string",merge:!0,regex:"'''",next:"qdoc"},{token:"string",merge:!0,regex:'"""',next:"qqdoc"},{token:"string",merge:!0,regex:"'",next:"qstring"},{token:"string",merge:!0,regex:'"',next:"qqstring"},{token:"string",merge:!0,regex:"`",next:"js"},{token:"string.regex",merge:!0,regex:"///",next:"heregex"},{token:"string.regex",regex:"/(?!\\s)[^[/\\n\\\\]*(?: (?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[/\\n\\\\]*)*/[imgy]{0,4}(?!\\w)"},{token:"comment",merge:!0,regex:"###(?!#)",next:"comment"},{token:"comment",regex:"#.*"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\."},{token:"keyword.operator",regex:"(?:[\\-=]>|[-+*/%<>&|^!?=]=|>>>=?|\\-\\-|\\+\\+|::|&&=|\\|\\|=|<<=|>>=|\\?\\.|\\.{2,3}|\\!)"},{token:"paren.lparen",regex:"[({[]"},{token:"paren.rparen",regex:"[\\]})]"},{token:"text",regex:"\\s+"}],qdoc:[{token:"string",regex:".*?'''",next:"start"},b],qqdoc:[{token:"string",regex:'.*?"""',next:"start"},b],qstring:[{token:"string",regex:"[^\\\\']*(?:\\\\.[^\\\\']*)*'",merge:!0,next:"start"},b],qqstring:[{token:"string",regex:'[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',merge:!0,next:"start"},b],js:[{token:"string",merge:!0,regex:"[^\\\\`]*(?:\\\\.[^\\\\`]*)*`",next:"start"},b],heregex:[{token:"string.regex",regex:".*?///[imgy]{0,4}",next:"start"},{token:"comment.regex",regex:"\\s+(?:#.*)?"},{token:"string.regex",merge:!0,regex:"\\S+"}],comment:[{token:"comment",regex:".*?###",next:"start"},{token:"comment",merge:!0,regex:".+"}]}}"use strict";var d=a("../lib/lang"),e=a("../lib/oop"),f=a("./text_highlight_rules").TextHighlightRules;e.inherits(g,f),b.CoffeeHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a){this.foldingStartMarker=new RegExp("(?:([\\[{])|("+a+"))(?:\\s*)(?:#.*)?$")};d.inherits(f,e),function(){this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),e=d.match(this.foldingStartMarker);if(e)return e[1]?this.openingBracketBlock(a,e[1],c,e.index):e[2]?this.indentationBlock(a,c,e.index+e[2].length):this.indentationBlock(a,c)}}.call(f.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;j|->|\\s*class [^#]*")}"use strict";var d=a("../tokenizer").Tokenizer,e=a("./coffee_highlight_rules").CoffeeHighlightRules,f=a("./matching_brace_outdent").MatchingBraceOutdent,g=a("./folding/pythonic").FoldMode,h=a("../range").Range,i=a("./text").Mode,j=a("../worker/worker_client").WorkerClient,k=a("../lib/oop");k.inherits(l,i),function(){var a=/(?:[({[=:]|[-=]>|\b(?:else|switch|try|catch(?:\s*[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)?|finally))\s*$/,b=/^(\s*)#/,c=/^\s*###(?!#)/,d=/^\s*/;this.getNextLineIndent=function(b,c,d){var e=this.$getIndent(c),f=this.$tokenizer.getLineTokens(c,b).tokens;return(!f.length||f[f.length-1].type!=="comment")&&b==="start"&&a.test(c)&&(e+=d),e},this.toggleCommentLines=function(a,e,f,g){console.log("toggle");var i=new h(0,0,0,0);for(var j=f;j<=g;++j){var k=e.getLine(j);if(c.test(k))continue;b.test(k)?k=k.replace(b,"$1"):k=k.replace(d,"$&#"),i.end.row=i.start.row=j,i.end.column=k.length+1,e.replace(i,k)}},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-coffee.js","ace/mode/coffee_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("error",function(b){a.setAnnotations([b.data])}),b.on("ok",function(b){a.clearAnnotations()}),b}}.call(l.prototype),b.Mode=l}),define("ace/mode/coffee_highlight_rules",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){function g(){var a="[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*",b={token:"string",merge:!0,regex:".+"},c=d.arrayToMap("this|throw|then|try|typeof|super|switch|return|break|by)|continue|catch|class|in|instanceof|is|isnt|if|else|extends|for|forown|finally|function|while|when|new|no|not|delete|debugger|do|loop|of|off|or|on|unless|until|and|yes".split("|")),e=d.arrayToMap("true|false|null|undefined".split("|")),f=d.arrayToMap("case|const|default|function|var|void|with|enum|export|implements|interface|let|package|private|protected|public|static|yield|__hasProp|extends|slice|bind|indexOf".split("|")),g=d.arrayToMap("Array|Boolean|Date|Function|Number|Object|RegExp|ReferenceError|RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError".split("|")),h=d.arrayToMap("Math|JSON|isNaN|isFinite|parseInt|parseFloat|encodeURI|encodeURIComponent|decodeURI|decodeURIComponent|RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError".split("|"));this.$rules={start:[{token:"identifier",regex:"(?:(?:\\.|::)\\s*)"+a},{token:"variable",regex:"@(?:"+a+")?"},{token:function(a){return c.hasOwnProperty(a)?"keyword":e.hasOwnProperty(a)?"constant.language":f.hasOwnProperty(a)?"invalid.illegal":g.hasOwnProperty(a)?"language.support.class":h.hasOwnProperty(a)?"language.support.function":"identifier"},regex:a},{token:"constant.numeric",regex:"(?:0x[\\da-fA-F]+|(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?)"},{token:"string",merge:!0,regex:"'''",next:"qdoc"},{token:"string",merge:!0,regex:'"""',next:"qqdoc"},{token:"string",merge:!0,regex:"'",next:"qstring"},{token:"string",merge:!0,regex:'"',next:"qqstring"},{token:"string",merge:!0,regex:"`",next:"js"},{token:"string.regex",merge:!0,regex:"///",next:"heregex"},{token:"string.regex",regex:"/(?!\\s)[^[/\\n\\\\]*(?: (?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[/\\n\\\\]*)*/[imgy]{0,4}(?!\\w)"},{token:"comment",merge:!0,regex:"###(?!#)",next:"comment"},{token:"comment",regex:"#.*"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\."},{token:"keyword.operator",regex:"(?:[\\-=]>|[-+*/%<>&|^!?=]=|>>>=?|\\-\\-|\\+\\+|::|&&=|\\|\\|=|<<=|>>=|\\?\\.|\\.{2,3}|\\!)"},{token:"paren.lparen",regex:"[({[]"},{token:"paren.rparen",regex:"[\\]})]"},{token:"text",regex:"\\s+"}],qdoc:[{token:"string",regex:".*?'''",next:"start"},b],qqdoc:[{token:"string",regex:'.*?"""',next:"start"},b],qstring:[{token:"string",regex:"[^\\\\']*(?:\\\\.[^\\\\']*)*'",merge:!0,next:"start"},b],qqstring:[{token:"string",regex:'[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',merge:!0,next:"start"},b],js:[{token:"string",merge:!0,regex:"[^\\\\`]*(?:\\\\.[^\\\\`]*)*`",next:"start"},b],heregex:[{token:"string.regex",regex:".*?///[imgy]{0,4}",next:"start"},{token:"comment.regex",regex:"\\s+(?:#.*)?"},{token:"string.regex",merge:!0,regex:"\\S+"}],comment:[{token:"comment",regex:".*?###",next:"start"},{token:"comment",merge:!0,regex:".+"}]}}"use strict";var d=a("../lib/lang"),e=a("../lib/oop"),f=a("./text_highlight_rules").TextHighlightRules;e.inherits(g,f),b.CoffeeHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a){this.foldingStartMarker=new RegExp("(?:([\\[{])|("+a+"))(?:\\s*)(?:#.*)?$")};d.inherits(f,e),function(){this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),e=d.match(this.foldingStartMarker);if(e)return e[1]?this.openingBracketBlock(a,e[1],c,e.index):e[2]?this.indentationBlock(a,c,e.index+e[2].length):this.indentationBlock(a,c)}}.call(f.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-coldfusion-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-coldfusion-uncompressed.js index c9092a5e0c2..af5e3914b56 100755 --- a/apps/files_texteditor/js/aceeditor/mode-coldfusion-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-coldfusion-uncompressed.js @@ -195,6 +195,9 @@ var XmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -202,6 +205,9 @@ var XmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -295,7 +301,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : '["].*', - next : state + "-qqstring" + next : state + "_qqstring" }, { token : "string", regex : "'.*?'" @@ -303,7 +309,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : "['].*", - next : state + "-qstring" + next : state + "_qstring" }]; } @@ -351,18 +357,18 @@ exports.tag = function(states, name, nextState) { } }, merge : true, - regex : "[-_a-zA-Z0-9:!]+", - next : name + "embed-attribute-list" + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" }, { token: "empty", regex: "", - next : name + "embed-attribute-list" + next : name + "_embed_attribute_list" }]; - states[name + "-qstring"] = multiLineString("'", name + "embed-attribute-list"); - states[name + "-qqstring"] = multiLineString("\"", name + "embed-attribute-list"); + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); - states[name + "embed-attribute-list"] = [{ + states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", @@ -528,12 +534,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -545,7 +551,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -563,7 +569,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -588,12 +594,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -605,7 +611,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -624,14 +630,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -652,7 +659,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -661,19 +668,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -682,7 +689,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -692,7 +699,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1329,12 +1337,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -1342,46 +1358,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -1389,7 +1498,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -1404,29 +1513,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -1451,7 +1560,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -1463,10 +1572,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -1478,9 +1587,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -1499,9 +1608,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -1530,28 +1639,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -1736,195 +1849,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; - + var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; + var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; + var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" - },{ + }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { - token : "constant.numeric", - regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : ["constant.numeric"], + regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { @@ -2277,12 +2174,15 @@ var CssHighlightRules = function() { else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } + else if (fonts.hasOwnProperty(value.toLowerCase())) { + return "support.constant.fonts"; + } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" - } + } ]; var ruleset = lang.copyArray(base_ruleset); @@ -2468,7 +2368,7 @@ var ColdfusionHighlightRules = function() { }, { token : "meta.tag", regex : "<(?=\s*style)", - next : "css" + next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -2507,7 +2407,7 @@ var ColdfusionHighlightRules = function() { }; xml_util.tag(this.$rules, "tag", "start"); - xml_util.tag(this.$rules, "css", "css-start"); + xml_util.tag(this.$rules, "style", "css-start"); xml_util.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ @@ -2531,13 +2431,3 @@ oop.inherits(ColdfusionHighlightRules, TextHighlightRules); exports.ColdfusionHighlightRules = ColdfusionHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-coldfusion.js b/apps/files_texteditor/js/aceeditor/mode-coldfusion.js index fa8693e6d1d..7080a63534c 100755 --- a/apps/files_texteditor/js/aceeditor/mode-coldfusion.js +++ b/apps/files_texteditor/js/aceeditor/mode-coldfusion.js @@ -1 +1 @@ -define("ace/mode/coldfusion",["require","exports","module","ace/lib/oop","ace/mode/xml","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/coldfusion_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./coldfusion_highlight_rules").ColdfusionHighlightRules,j=function(){e.call(this);var a=new i;this.$tokenizer=new h(a.getRules()),this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g})};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"-qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"-qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:!]+",next:b+"embed-attribute-list"},{token:"empty",regex:"",next:b+"embed-attribute-list"}],a[b+"-qstring"]=h("'",b+"embed-attribute-list"),a[b+"-qqstring"]=h('"',b+"embed-attribute-list"),a[b+"embed-attribute-list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="f.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;j"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<(?=s*script)",next:"script"},{token:"meta.tag",regex:"<(?=s*style)",next:"css"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},h.tag(this.$rules,"tag","start"),h.tag(this.$rules,"css","css-start"),h.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,g),b.ColdfusionHighlightRules=i}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/coldfusion",["require","exports","module","ace/lib/oop","ace/mode/xml","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/coldfusion_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./coldfusion_highlight_rules").ColdfusionHighlightRules,j=function(){e.call(this);var a=new i;this.$tokenizer=new h(a.getRules()),this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g})};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="g.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f=e.arrayToMap("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace".split("|")),g="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",i="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",j=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+g+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:["constant.numeric"],regex:"([0-9]+)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:i},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":f.hasOwnProperty(e.toLowerCase())?"support.constant.fonts":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],k=e.copyArray(j);k.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var l=e.copyArray(j);l.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var m=[{token:"comment",merge:!0,regex:".+"}],n=e.copyArray(m);n.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var o=e.copyArray(m);o.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var p=e.copyArray(m);p.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:n,ruleset:k,ruleset_comment:p,media_ruleset:l,media_comment:o}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/coldfusion_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/text_highlight_rules","ace/mode/xml_util"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=a("./xml_util"),i=function(){this.$rules={start:[{token:"text",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<(?=s*script)",next:"script"},{token:"meta.tag",regex:"<(?=s*style)",next:"style"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},h.tag(this.$rules,"tag","start"),h.tag(this.$rules,"style","css-start"),h.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,g),b.ColdfusionHighlightRules=i}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-csharp-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-csharp-uncompressed.js index 492e2ff9847..3e83d27d72c 100755 --- a/apps/files_texteditor/js/aceeditor/mode-csharp-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-csharp-uncompressed.js @@ -391,12 +391,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -408,7 +408,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -426,7 +426,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -451,12 +451,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -468,7 +468,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -487,14 +487,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -515,7 +516,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -524,19 +525,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -545,7 +546,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -555,7 +556,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -766,13 +768,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-csharp.js b/apps/files_texteditor/js/aceeditor/mode-csharp.js index b4c06059661..642ee6e7b19 100644 --- a/apps/files_texteditor/js/aceeditor/mode-csharp.js +++ b/apps/files_texteditor/js/aceeditor/mode-csharp.js @@ -1 +1 @@ -define("ace/mode/csharp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/csharp_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./csharp_highlight_rules").CSharpHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/csharp_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string|var|dynamic".split("|")),b=e.arrayToMap("null|true|false".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",merge:!0,next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.CSharpHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/csharp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/csharp_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./csharp_highlight_rules").CSharpHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/csharp_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string|var|dynamic".split("|")),b=e.arrayToMap("null|true|false".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",merge:!0,next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.CSharpHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-css-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-css-uncompressed.js index 17a7738b477..44505d19b62 100755 --- a/apps/files_texteditor/js/aceeditor/mode-css-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-css-uncompressed.js @@ -155,31 +155,7 @@ var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( - ("-moz-appearance|-moz-box-sizing|-webkit-box-sizing|-moz-outline-radius|-moz-transform|-webkit-transform|" + - "appearance|azimuth|background-attachment|background-color|background-image|" + - "background-origin|background-position|background-repeat|background|border-bottom-color|" + - "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + - "border-color|border-left-color|border-left-style|border-left-width|" + - "border-left|border-right-color|border-right-style|border-right-width|" + - "border-right|border-spacing|border-style|border-top-color|" + - "border-top-style|border-top-width|border-top|border-width|border|" + - "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + - "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + - "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + - "font-stretch|font-style|font-variant|font-weight|font|height|left|" + - "letter-spacing|line-height|list-style-image|list-style-position|" + - "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + - "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + - "min-width|-moz-border-radius|opacity|orphans|outline-color|outline-offset|outline-radius|" + - "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + - "padding-left|padding-right|padding-top|padding|page-break-after|" + - "page-break-before|page-break-inside|page|pause-after|pause-before|" + - "pause|pitch-range|pitch|play-during|pointer-events|position|quotes|resize|richness|right|" + - "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + - "stress|table-layout|text-align|text-decoration|text-indent|" + - "text-shadow|text-transform|top|transform|unicode-bidi|vertical-align|" + - "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + - "z-index").split("|") + ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( @@ -187,27 +163,7 @@ var CssHighlightRules = function() { ); var constants = lang.arrayToMap( - ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + - "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + - "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + - "decimal-leading-zero|decimal|default|disabled|disc|" + - "distribute-all-lines|distribute-letter|distribute-space|" + - "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + - "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + - "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + - "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + - "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + - "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + - "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + - "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + - "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + - "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + - "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + - "solid|square|static|strict|super|sw-resize|table-footer-group|" + - "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + - "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + - "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + - "zero").split("|") + ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( @@ -215,32 +171,49 @@ var CssHighlightRules = function() { "purple|red|silver|teal|white|yellow").split("|") ); + var fonts = lang.arrayToMap( + ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + + "serif|monospace").split("|") + ); + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; - + var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; + var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; + var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" - },{ + }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { - token : "constant.numeric", - regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : ["constant.numeric"], + regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { @@ -255,12 +228,15 @@ var CssHighlightRules = function() { else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } + else if (fonts.hasOwnProperty(value.toLowerCase())) { + return "support.constant.fonts"; + } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" - } + } ]; var ruleset = lang.copyArray(base_ruleset); @@ -454,195 +430,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; if){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f=e.arrayToMap("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace".split("|")),g="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",i="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",j=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+g+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:["constant.numeric"],regex:"([0-9]+)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:i},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":f.hasOwnProperty(e.toLowerCase())?"support.constant.fonts":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],k=e.copyArray(j);k.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var l=e.copyArray(j);l.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var m=[{token:"comment",merge:!0,regex:".+"}],n=e.copyArray(m);n.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var o=e.copyArray(m);o.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var p=e.copyArray(m);p.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:n,ruleset:k,ruleset_comment:p,media_ruleset:l,media_comment:o}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-groovy-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-groovy-uncompressed.js index b6067e87773..8fc01d4054c 100755 --- a/apps/files_texteditor/js/aceeditor/mode-groovy-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-groovy-uncompressed.js @@ -281,12 +281,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -294,46 +302,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -341,7 +442,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -356,29 +457,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -403,7 +504,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -415,10 +516,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -430,9 +531,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -451,9 +552,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -482,28 +583,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -688,195 +793,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1065,19 +982,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1086,7 +1003,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1096,7 +1013,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1450,13 +1368,3 @@ oop.inherits(GroovyHighlightRules, TextHighlightRules); exports.GroovyHighlightRules = GroovyHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-groovy.js b/apps/files_texteditor/js/aceeditor/mode-groovy.js index c71ada2bf84..1a036a462c7 100644 --- a/apps/files_texteditor/js/aceeditor/mode-groovy.js +++ b/apps/files_texteditor/js/aceeditor/mode-groovy.js @@ -1 +1 @@ -define("ace/mode/groovy",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/groovy_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./groovy_highlight_rules").GroovyHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/groovy_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("assert|with|abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|def|float|native|super|while".split("|")),b=e.arrayToMap("null|Infinity|NaN|undefined".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\?:|\\?\\.|\\*\\.|<=>|=~|==~|\\.@|\\*\\.@|\\.&|as|in|is|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.GroovyHighlightRules=h}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/groovy",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/groovy_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./groovy_highlight_rules").GroovyHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/groovy_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("assert|with|abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|def|float|native|super|while".split("|")),b=e.arrayToMap("null|Infinity|NaN|undefined".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\?:|\\?\\.|\\*\\.|<=>|=~|==~|\\.@|\\*\\.@|\\.&|as|in|is|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.GroovyHighlightRules=h}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-haxe-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-haxe-uncompressed.js index 5496580ed33..7efa04c5f67 100755 --- a/apps/files_texteditor/js/aceeditor/mode-haxe-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-haxe-uncompressed.js @@ -391,12 +391,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -408,7 +408,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -426,7 +426,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -451,12 +451,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -468,7 +468,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -487,14 +487,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -515,7 +516,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -524,19 +525,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -545,7 +546,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -555,7 +556,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -766,13 +768,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-haxe.js b/apps/files_texteditor/js/aceeditor/mode-haxe.js index 88818b1371a..0c0d15f3935 100755 --- a/apps/files_texteditor/js/aceeditor/mode-haxe.js +++ b/apps/files_texteditor/js/aceeditor/mode-haxe.js @@ -1 +1 @@ -define("ace/mode/haxe",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/haxe_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./haxe_highlight_rules").HaxeHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/haxe_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("break|case|cast|catch|class|continue|default|else|enum|extends|for|function|if|implements|import|in|inline|interface|new|override|package|private|public|return|static|super|switch|this|throw|trace|try|typedef|untyped|var|while|Array|Void|Bool|Int|UInt|Float|Dynamic|String|List|Hash|IntHash|Error|Unknown|Type|Std".split("|")),b=e.arrayToMap("null|true|false".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",merge:!0,next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({<]"},{token:"paren.rparen",regex:"[\\])}>]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.HaxeHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/haxe",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/haxe_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./haxe_highlight_rules").HaxeHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/haxe_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("break|case|cast|catch|class|continue|default|else|enum|extends|for|function|if|implements|import|in|inline|interface|new|override|package|private|public|return|static|super|switch|this|throw|trace|try|typedef|untyped|var|while|Array|Void|Bool|Int|UInt|Float|Dynamic|String|List|Hash|IntHash|Error|Unknown|Type|Std".split("|")),b=e.arrayToMap("null|true|false".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",merge:!0,next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({<]"},{token:"paren.rparen",regex:"[\\])}>]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.HaxeHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-html-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-html-uncompressed.js index e994e2e06ef..62d0ce14393 100755 --- a/apps/files_texteditor/js/aceeditor/mode-html-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-html-uncompressed.js @@ -340,12 +340,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -353,46 +361,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -400,7 +501,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -415,29 +516,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -462,7 +563,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -474,10 +575,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -489,9 +590,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -510,9 +611,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -541,28 +642,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -747,195 +852,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1124,19 +1041,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1145,7 +1062,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1155,7 +1072,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1523,31 +1441,7 @@ var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( - ("-moz-appearance|-moz-box-sizing|-webkit-box-sizing|-moz-outline-radius|-moz-transform|-webkit-transform|" + - "appearance|azimuth|background-attachment|background-color|background-image|" + - "background-origin|background-position|background-repeat|background|border-bottom-color|" + - "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + - "border-color|border-left-color|border-left-style|border-left-width|" + - "border-left|border-right-color|border-right-style|border-right-width|" + - "border-right|border-spacing|border-style|border-top-color|" + - "border-top-style|border-top-width|border-top|border-width|border|" + - "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + - "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + - "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + - "font-stretch|font-style|font-variant|font-weight|font|height|left|" + - "letter-spacing|line-height|list-style-image|list-style-position|" + - "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + - "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + - "min-width|-moz-border-radius|opacity|orphans|outline-color|outline-offset|outline-radius|" + - "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + - "padding-left|padding-right|padding-top|padding|page-break-after|" + - "page-break-before|page-break-inside|page|pause-after|pause-before|" + - "pause|pitch-range|pitch|play-during|pointer-events|position|quotes|resize|richness|right|" + - "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + - "stress|table-layout|text-align|text-decoration|text-indent|" + - "text-shadow|text-transform|top|transform|unicode-bidi|vertical-align|" + - "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + - "z-index").split("|") + ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( @@ -1555,27 +1449,7 @@ var CssHighlightRules = function() { ); var constants = lang.arrayToMap( - ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + - "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + - "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + - "decimal-leading-zero|decimal|default|disabled|disc|" + - "distribute-all-lines|distribute-letter|distribute-space|" + - "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + - "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + - "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + - "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + - "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + - "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + - "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + - "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + - "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + - "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + - "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + - "solid|square|static|strict|super|sw-resize|table-footer-group|" + - "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + - "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + - "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + - "zero").split("|") + ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( @@ -1583,32 +1457,49 @@ var CssHighlightRules = function() { "purple|red|silver|teal|white|yellow").split("|") ); + var fonts = lang.arrayToMap( + ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + + "serif|monospace").split("|") + ); + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; - + var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; + var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; + var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" - },{ + }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { - token : "constant.numeric", - regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : ["constant.numeric"], + regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { @@ -1623,12 +1514,15 @@ var CssHighlightRules = function() { else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } + else if (fonts.hasOwnProperty(value.toLowerCase())) { + return "support.constant.fonts"; + } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" - } + } ]; var ruleset = lang.copyArray(base_ruleset); @@ -1806,6 +1700,9 @@ var HtmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", @@ -1813,7 +1710,7 @@ var HtmlHighlightRules = function() { }, { token : "meta.tag", regex : "<(?=\s*style\\b)", - next : "css" + next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -1821,6 +1718,9 @@ var HtmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -1852,7 +1752,7 @@ var HtmlHighlightRules = function() { }; xmlUtil.tag(this.$rules, "tag", "start"); - xmlUtil.tag(this.$rules, "css", "css-start"); + xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ @@ -1934,7 +1834,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : '["].*', - next : state + "-qqstring" + next : state + "_qqstring" }, { token : "string", regex : "'.*?'" @@ -1942,7 +1842,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : "['].*", - next : state + "-qstring" + next : state + "_qstring" }]; } @@ -1990,18 +1890,18 @@ exports.tag = function(states, name, nextState) { } }, merge : true, - regex : "[-_a-zA-Z0-9:!]+", - next : name + "embed-attribute-list" + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" }, { token: "empty", regex: "", - next : name + "embed-attribute-list" + next : name + "_embed_attribute_list" }]; - states[name + "-qstring"] = multiLineString("'", name + "embed-attribute-list"); - states[name + "-qqstring"] = multiLineString("\"", name + "embed-attribute-list"); + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); - states[name + "embed-attribute-list"] = [{ + states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", @@ -2546,13 +2446,4 @@ oop.inherits(FoldMode, BaseFoldMode); }).call(FoldMode.prototype); -});; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file +}); \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-html.js b/apps/files_texteditor/js/aceeditor/mode-html.js index f4f806059e4..78701813b25 100644 --- a/apps/files_texteditor/js/aceeditor/mode-html.js +++ b/apps/files_texteditor/js/aceeditor/mode-html.js @@ -1 +1 @@ -define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./html_highlight_rules").HtmlHighlightRules,j=a("./behaviour/xml").XmlBehaviour,k=a("./folding/html").FoldMode,l=function(){var a=new i;this.$tokenizer=new h(a.getRules()),this.$behaviour=new j,this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g}),this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){return 0},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)},this.checkOutdent=function(a,b,c){return!1}}.call(l.prototype),b.Mode=l}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("-moz-appearance|-moz-box-sizing|-webkit-box-sizing|-moz-outline-radius|-moz-transform|-webkit-transform|appearance|azimuth|background-attachment|background-color|background-image|background-origin|background-position|background-repeat|background|border-bottom-color|border-bottom-style|border-bottom-width|border-bottom|border-collapse|border-color|border-left-color|border-left-style|border-left-width|border-left|border-right-color|border-right-style|border-right-width|border-right|border-spacing|border-style|border-top-color|border-top-style|border-top-width|border-top|border-width|border|bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|counter-reset|cue-after|cue-before|cue|cursor|direction|display|elevation|empty-cells|float|font-family|font-size-adjust|font-size|font-stretch|font-style|font-variant|font-weight|font|height|left|letter-spacing|line-height|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|marker-offset|margin|marks|max-height|max-width|min-height|min-width|-moz-border-radius|opacity|orphans|outline-color|outline-offset|outline-radius|outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page|pause-after|pause-before|pause|pitch-range|pitch|play-during|pointer-events|position|quotes|resize|richness|right|size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|stress|table-layout|text-align|text-decoration|text-indent|text-shadow|text-transform|top|transform|unicode-bidi|vertical-align|visibility|voice-family|volume|white-space|widows|width|word-spacing|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|decimal-leading-zero|decimal|default|disabled|disc|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|inactive|inherit|inline-block|inline|inset|inside|inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|keep-all|left|lighter|line-edge|line-through|line|list-item|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|solid|square|static|strict|super|sw-resize|table-footer-group|table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",g=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:f+"(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],h=e.copyArray(g);h.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var i=e.copyArray(g);i.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var j=[{token:"comment",merge:!0,regex:".+"}],k=e.copyArray(j);k.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var l=e.copyArray(j);l.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var m=e.copyArray(j);m.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:k,ruleset:h,ruleset_comment:m,media_ruleset:i,media_comment:l}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_util"),h=a("./text_highlight_rules").TextHighlightRules,i=function(){this.$rules={start:[{token:"text",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<(?=s*script\\b)",next:"script"},{token:"meta.tag",regex:"<(?=s*style\\b)",next:"css"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},g.tag(this.$rules,"tag","start"),g.tag(this.$rules,"css","css-start"),g.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,h),b.HtmlHighlightRules=i}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"-qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"-qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:!]+",next:b+"embed-attribute-list"},{token:"empty",regex:"",next:b+"embed-attribute-list"}],a[b+"-qstring"]=h("'",b+"embed-attribute-list"),a[b+"-qqstring"]=h('"',b+"embed-attribute-list"),a[b+"embed-attribute-list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./html_highlight_rules").HtmlHighlightRules,j=a("./behaviour/xml").XmlBehaviour,k=a("./folding/html").FoldMode,l=function(){var a=new i;this.$tokenizer=new h(a.getRules()),this.$behaviour=new j,this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g}),this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){return 0},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)},this.checkOutdent=function(a,b,c){return!1}}.call(l.prototype),b.Mode=l}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f=e.arrayToMap("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace".split("|")),g="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",i="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",j=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+g+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:["constant.numeric"],regex:"([0-9]+)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:i},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":f.hasOwnProperty(e.toLowerCase())?"support.constant.fonts":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],k=e.copyArray(j);k.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var l=e.copyArray(j);l.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var m=[{token:"comment",merge:!0,regex:".+"}],n=e.copyArray(m);n.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var o=e.copyArray(m);o.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var p=e.copyArray(m);p.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:n,ruleset:k,ruleset_comment:p,media_ruleset:l,media_comment:o}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_util"),h=a("./text_highlight_rules").TextHighlightRules,i=function(){this.$rules={start:[{token:"text",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<(?=s*script\\b)",next:"script"},{token:"meta.tag",regex:"<(?=s*style\\b)",next:"style"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},g.tag(this.$rules,"tag","start"),g.tag(this.$rules,"style","css-start"),g.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,h),b.HtmlHighlightRules=i}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-java-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-java-uncompressed.js index 7263df5894c..f241de365d7 100755 --- a/apps/files_texteditor/js/aceeditor/mode-java-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-java-uncompressed.js @@ -282,12 +282,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -295,46 +303,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -342,7 +443,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -357,29 +458,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -404,7 +505,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -416,10 +517,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -431,9 +532,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -452,9 +553,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -483,28 +584,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -689,195 +794,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1066,19 +983,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1087,7 +1004,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1097,7 +1014,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1452,13 +1370,3 @@ oop.inherits(JavaHighlightRules, TextHighlightRules); exports.JavaHighlightRules = JavaHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-java.js b/apps/files_texteditor/js/aceeditor/mode-java.js index 84c21daba22..9398464a18e 100644 --- a/apps/files_texteditor/js/aceeditor/mode-java.js +++ b/apps/files_texteditor/js/aceeditor/mode-java.js @@ -1 +1 @@ -define("ace/mode/java",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/java_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./java_highlight_rules").JavaHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/java_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while".split("|")),b=e.arrayToMap("null|Infinity|NaN|undefined".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.JavaHighlightRules=h}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/java",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/java_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./java_highlight_rules").JavaHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/java_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while".split("|")),b=e.arrayToMap("null|Infinity|NaN|undefined".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.JavaHighlightRules=h}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-javascript-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-javascript-uncompressed.js index ba30b9e438f..8afe93503a9 100755 --- a/apps/files_texteditor/js/aceeditor/mode-javascript-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-javascript-uncompressed.js @@ -257,12 +257,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -270,46 +278,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -317,7 +418,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -332,29 +433,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -379,7 +480,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -391,10 +492,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -406,9 +507,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -427,9 +528,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -458,28 +559,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -664,195 +769,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1041,19 +958,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1062,7 +979,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1072,7 +989,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1283,13 +1201,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-javascript.js b/apps/files_texteditor/js/aceeditor/mode-javascript.js index 2f242387fff..a456dad386b 100644 --- a/apps/files_texteditor/js/aceeditor/mode-javascript.js +++ b/apps/files_texteditor/js/aceeditor/mode-javascript.js @@ -1 +1 @@ -define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-json-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-json-uncompressed.js index 19dc612ab3e..22399889f3e 100755 --- a/apps/files_texteditor/js/aceeditor/mode-json-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-json-uncompressed.js @@ -35,7 +35,7 @@ * * ***** END LICENSE BLOCK ***** */ -define('ace/mode/json', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/json_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { +define('ace/mode/json', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/json_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle', 'ace/worker/worker_client'], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); @@ -45,6 +45,7 @@ var HighlightRules = require("./json_highlight_rules").JsonHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; +var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.$tokenizer = new Tokenizer(new HighlightRules().getRules()); @@ -76,7 +77,23 @@ oop.inherits(Mode, TextMode); this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; - + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], "worker-json.js", "ace/mode/json_worker", "JsonWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("error", function(e) { + session.setAnnotations([e.data]); + }); + + worker.on("ok", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + }).call(Mode.prototype); exports.Mode = Mode; @@ -302,12 +319,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -319,7 +336,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -337,7 +354,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -362,12 +379,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -379,7 +396,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -398,14 +415,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -426,7 +444,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -435,19 +453,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -456,7 +474,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -466,7 +484,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -677,13 +696,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-json.js b/apps/files_texteditor/js/aceeditor/mode-json.js index d0dd59fec3e..05729db5e66 100644 --- a/apps/files_texteditor/js/aceeditor/mode-json.js +++ b/apps/files_texteditor/js/aceeditor/mode-json.js @@ -1 +1 @@ -define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./json_highlight_rules").JsonHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b);if(a=="start"){var e=b.match(/^.*[\{\(\[]\s*$/);e&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(k.prototype),b.Mode=k}),define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:"invalid.illegal",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"invalid.illegal",regex:"\\/\\/.*$"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}]}};d.inherits(f,e),b.JsonHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./json_highlight_rules").JsonHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=a("../worker/worker_client").WorkerClient,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(l,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b);if(a=="start"){var e=b.match(/^.*[\{\(\[]\s*$/);e&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new k(["ace"],"worker-json.js","ace/mode/json_worker","JsonWorker");return b.attachToDocument(a.getDocument()),b.on("error",function(b){a.setAnnotations([b.data])}),b.on("ok",function(){a.clearAnnotations()}),b}}.call(l.prototype),b.Mode=l}),define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:"invalid.illegal",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"invalid.illegal",regex:"\\/\\/.*$"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}]}};d.inherits(f,e),b.JsonHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-latex-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-latex-uncompressed.js index 864f28d96a9..77c42ab3f9e 100755 --- a/apps/files_texteditor/js/aceeditor/mode-latex-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-latex-uncompressed.js @@ -93,13 +93,3 @@ oop.inherits(LatexHighlightRules, TextHighlightRules); exports.LatexHighlightRules = LatexHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-latex.js b/apps/files_texteditor/js/aceeditor/mode-latex.js index 3498213a644..e6cfb7cc2f9 100755 --- a/apps/files_texteditor/js/aceeditor/mode-latex.js +++ b/apps/files_texteditor/js/aceeditor/mode-latex.js @@ -1 +1 @@ -define("ace/mode/latex",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/latex_highlight_rules","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./latex_highlight_rules").LatexHighlightRules,h=a("../range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\%/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var i=new h(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);i.start.row=g,i.end.row=g,i.end.column=k[0].length,b.replace(i,k[1])}}else b.indentRows(c,d,"%")},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(i.prototype),b.Mode=i}),define("ace/mode/latex_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"keyword",regex:"\\\\(?:[^a-zA-Z]|[a-zA-Z]+)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"string",regex:"\\$(?:(?:\\\\.)|(?:[^\\$\\\\]))*?\\$"},{token:"comment",regex:"%.*$"}]}};d.inherits(f,e),b.LatexHighlightRules=f}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/latex",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/latex_highlight_rules","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./latex_highlight_rules").LatexHighlightRules,h=a("../range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\%/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var i=new h(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);i.start.row=g,i.end.row=g,i.end.column=k[0].length,b.replace(i,k[1])}}else b.indentRows(c,d,"%")},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(i.prototype),b.Mode=i}),define("ace/mode/latex_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"keyword",regex:"\\\\(?:[^a-zA-Z]|[a-zA-Z]+)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"string",regex:"\\$(?:(?:\\\\.)|(?:[^\\$\\\\]))*?\\$"},{token:"comment",regex:"%.*$"}]}};d.inherits(f,e),b.LatexHighlightRules=f}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-less-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-less-uncompressed.js new file mode 100755 index 00000000000..b59684dd284 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-less-uncompressed.js @@ -0,0 +1,654 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * John Roepke + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/less', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/less_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var LessHighlightRules = require("./less_highlight_rules").LessHighlightRules; +var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; +var CStyleFoldMode = require("./folding/cstyle").FoldMode; + +var Mode = function() { + this.$tokenizer = new Tokenizer(new LessHighlightRules().getRules(), "i"); + this.$outdent = new MatchingBraceOutdent(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + // ignore braces in comments + var tokens = this.$tokenizer.getLineTokens(line, state).tokens; + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + var match = line.match(/^.*\{\s*$/); + if (match) { + indent += tab; + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * John Roepke + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/less_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var LessHighlightRules = function() { + + var properties = lang.arrayToMap( (function () { + + var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); + + var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + + "background-size|binding|border-bottom-colors|border-left-colors|" + + "border-right-colors|border-top-colors|border-end|border-end-color|" + + "border-end-style|border-end-width|border-image|border-start|" + + "border-start-color|border-start-style|border-start-width|box-align|" + + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + + "font-feature-settings|font-language-override|force-broken-image-icon|" + + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + + "outline-offset|outline-radius|outline-radius-bottomleft|" + + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + + "text-decoration-style|transform|transform-origin|transition|" + + "transition-delay|transition-duration|transition-property|" + + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + + "window-shadow|border-radius").split("|"); + + var properties = ("azimuth|background-attachment|background-color|background-image|" + + "background-position|background-repeat|background|border-bottom-color|" + + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + + "border-color|border-left-color|border-left-style|border-left-width|" + + "border-left|border-right-color|border-right-style|border-right-width|" + + "border-right|border-spacing|border-style|border-top-color|" + + "border-top-style|border-top-width|border-top|border-width|border|" + + "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + + "letter-spacing|line-height|list-style-image|list-style-position|" + + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + + "min-width|opacity|orphans|outline-color|" + + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + + "padding-left|padding-right|padding-top|padding|page-break-after|" + + "page-break-before|page-break-inside|page|pause-after|pause-before|" + + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + + "stress|table-layout|text-align|text-decoration|text-indent|" + + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + + "z-index").split("|"); + + //The return array + var ret = []; + + //All prefixProperties will get the browserPrefix in + //the begning by join the prefixProperties array with the value of browserPrefix + for (var i=0, ln=browserPrefix.length; i the first match is used + + var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; + + // regexp must not have capturing parentheses. Use (?:) instead. + // regexps are ordered -> the first match is used + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "\\/\\/.*$" + }, + { + token : "comment", // multi line comment + merge : true, + regex : "\\/\\*", + next : "comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", + regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" + }, { + token : "constant.numeric", // hex6 color + regex : "#[a-f0-9]{6}" + }, { + token : "constant.numeric", // hex3 color + regex : "#[a-f0-9]{3}" + }, { + token : "constant.numeric", + regex : numRe + }, { + token : function(value) { + if (keywords.hasOwnProperty(value)) + return "keyword"; + else + return "variable"; + }, + regex : "@[a-z0-9_\\-@]*\\b" + }, { + token : function(value) { + if (properties.hasOwnProperty(value.toLowerCase())) + return "support.type"; + else if (keywords.hasOwnProperty(value)) + return "keyword"; + else if (constants.hasOwnProperty(value)) + return "constant.language"; + else if (functions.hasOwnProperty(value)) + return "support.function"; + else if (colors.hasOwnProperty(value.toLowerCase())) + return "support.constant.color"; + else if (tags.hasOwnProperty(value.toLowerCase())) + return "variable.language"; + else + return "text"; + }, + regex : "\\-?[@a-z_][@a-z0-9_\\-]*" + }, { + token: "variable.language", + regex: "#[a-z0-9-_]+" + }, { + token: "variable.language", + regex: "\\.[a-z0-9-_]+" + }, { + token: "variable.language", + regex: ":[a-z0-9-_]+" + }, { + token: "constant", + regex: "[a-z0-9-_]+" + }, { + token : "keyword.operator", + regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ] + }; +}; + +oop.inherits(LessHighlightRules, TextHighlightRules); + +exports.LessHighlightRules = LessHighlightRules; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { +"use strict"; + +var Range = require("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + var match = line.match(/^(\s+)/); + if (match) { + return match[1]; + } + + return ""; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { +"use strict"; + +var oop = require("../../lib/oop"); +var Range = require("../../range").Range; +var BaseFoldMode = require("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var line = session.getLine(row); + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length); + range.end.column -= 2; + return range; + } + + if (foldStyle !== "markbeginend") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[2]) { + var range = session.getCommentFoldRange(row, i); + range.end.column -= 2; + return range; + } + + var end = {row: row, column: i}; + var start = session.$findOpeningBracket(match[1], end); + + if (!start) + return; + + start.column++; + end.column--; + + return Range.fromPoints(start, end); + } + }; + +}).call(FoldMode.prototype); + +});/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { +"use strict"; + +var Range = require("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; + +(function() { + + this.foldingStartMarker = null; + this.foldingStopMarker = null; + + // must return "" if there's no fold, to enable caching + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + if (this.foldingStartMarker.test(line)) + return "start"; + if (foldStyle == "markbeginend" + && this.foldingStopMarker + && this.foldingStopMarker.test(line)) + return "end"; + return ""; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + return null; + }; + + this.indentationBlock = function(session, row, column) { + var re = /^\s*/; + var startRow = row; + var endRow = row; + var line = session.getLine(row); + var startColumn = column || line.length; + var startLevel = line.match(re)[0].length; + var maxRow = session.getLength() + + while (++row < maxRow) { + line = session.getLine(row); + var level = line.match(re)[0].length; + + if (level == line.length) + continue; + + if (level <= startLevel) + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + + this.openingBracketBlock = function(session, bracket, row, column) { + var start = {row: row, column: column + 1}; + var end = session.$findClosingBracket(bracket, start); + if (!end) + return; + + var fw = session.foldWidgets[end.row]; + if (fw == null) + fw = this.getFoldWidget(session, end.row); + + if (fw == "start") { + end.row --; + end.column = session.getLine(end.row).length; + } + return Range.fromPoints(start, end); + }; + +}).call(FoldMode.prototype); + +}); diff --git a/apps/files_texteditor/js/aceeditor/mode-less.js b/apps/files_texteditor/js/aceeditor/mode-less.js new file mode 100755 index 00000000000..8ecd9aad97b --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-less.js @@ -0,0 +1 @@ +define("ace/mode/less",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/less_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./less_highlight_rules").LessHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./folding/cstyle").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/less_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap(function(){var a="-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-".split("|"),b="appearance|background-clip|background-inline-policy|background-origin|background-size|binding|border-bottom-colors|border-left-colors|border-right-colors|border-top-colors|border-end|border-end-color|border-end-style|border-end-width|border-image|border-start|border-start-color|border-start-style|border-start-width|box-align|box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|box-pack|box-sizing|column-count|column-gap|column-width|column-rule|column-rule-width|column-rule-style|column-rule-color|float-edge|font-feature-settings|font-language-override|force-broken-image-icon|image-region|margin-end|margin-start|opacity|outline|outline-color|outline-offset|outline-radius|outline-radius-bottomleft|outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|outline-style|outline-width|padding-end|padding-start|stack-sizing|tab-size|text-blink|text-decoration-color|text-decoration-line|text-decoration-style|transform|transform-origin|transition|transition-delay|transition-duration|transition-property|transition-timing-function|user-focus|user-input|user-modify|user-select|window-shadow|border-radius".split("|"),c="azimuth|background-attachment|background-color|background-image|background-position|background-repeat|background|border-bottom-color|border-bottom-style|border-bottom-width|border-bottom|border-collapse|border-color|border-left-color|border-left-style|border-left-width|border-left|border-right-color|border-right-style|border-right-width|border-right|border-spacing|border-style|border-top-color|border-top-style|border-top-width|border-top|border-width|border|bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|counter-reset|cue-after|cue-before|cue|cursor|direction|display|elevation|empty-cells|float|font-family|font-size-adjust|font-size|font-stretch|font-style|font-variant|font-weight|font|height|left|letter-spacing|line-height|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|marker-offset|margin|marks|max-height|max-width|min-height|min-width|opacity|orphans|outline-color|outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page|pause-after|pause-before|pause|pitch-range|pitch|play-during|position|quotes|richness|right|size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|stress|table-layout|text-align|text-decoration|text-indent|text-shadow|text-transform|top|unicode-bidi|vertical-align|visibility|voice-family|volume|white-space|widows|width|word-spacing|z-index".split("|"),d=[];for(var e=0,f=a.length;e|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.LessHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-liquid-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-liquid-uncompressed.js new file mode 100755 index 00000000000..6e9b689e85c --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-liquid-uncompressed.js @@ -0,0 +1,1332 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/liquid', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/liquid_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var LiquidHighlightRules = require("./liquid_highlight_rules").LiquidHighlightRules; +var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; +var Range = require("../range").Range; + +var Mode = function() { + this.$tokenizer = new Tokenizer(new LiquidHighlightRules().getRules()); + this.$outdent = new MatchingBraceOutdent(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.toggleCommentLines = function(state, doc, startRow, endRow) { + var outdent = true; + var outentedRows = []; + var re = /^(\s*)#/; + + for (var i=startRow; i<= endRow; i++) { + if (!re.test(doc.getLine(i))) { + outdent = false; + break; + } + } + + if (outdent) { + var deleteRange = new Range(0, 0, 0, 0); + for (var i=startRow; i<= endRow; i++) + { + var line = doc.getLine(i); + var m = line.match(re); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = m[0].length; + doc.replace(deleteRange, m[1]); + } + } + else { + doc.indentRows(startRow, endRow, "#"); + } + }; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.$tokenizer.getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + +}).call(Mode.prototype); + +exports.Mode = Mode; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/liquid_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/lib/lang', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; +var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; +var lang = require("../lib/lang"); +var xmlUtil = require("./xml_util"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var LiquidHighlightRules = function() { + + // see: https://developer.mozilla.org/en/Liquid/Reference/Global_Objects + var functions = lang.arrayToMap( + // Standard Filters + ("date|capitalize|downcase|upcase|first|last|join|sort|map|size|escape|" + + "escape_once|strip_html|strip_newlines|newline_to_br|replace|replace_first|" + + "truncate|truncatewords|prepend|append|minus|plus|times|divided_by|split" + ).split("|") + ); + + var keywords = lang.arrayToMap( + // Standard Tags + ("capture|endcapture|case|endcase|when|comment|endcomment|" + + "cycle|for|endfor|in|reversed|if|endif|else|elsif|include|endinclude|unless|endunless|" + + // Commonly used tags + "style|text|image|widget|plugin|marker|endmarker|tablerow|endtablerow").split("|") + ); + + var builtinVariables = lang.arrayToMap( + ['forloop'] + // ("forloop\\.(length|index|index0|rindex|rindex0|first|last)|limit|offset|range" + + // "tablerowloop\\.(length|index|index0|rindex|rindex0|first|last|col|col0|"+ + // "col_first|col_last)").split("|") + ); + + var definitions = lang.arrayToMap(("assign").split("|")); + + // regexp must not have capturing parentheses. Use (?:) instead. + // regexps are ordered -> the first match is used + + this.$rules = { + start : [{ + token : "variable", + regex : "{%", + next : "liquid_start" + }, { + token : "variable", + regex : "{{", + next : "liquid_start" + }, { + token : "meta.tag", + merge : true, + regex : "<\\!\\[CDATA\\[", + next : "cdata" + }, { + token : "xml_pe", + regex : "<\\?.*?\\?>" + }, { + token : "comment", + merge : true, + regex : "<\\!--", + next : "comment" + }, { + token : "meta.tag", + regex : "<(?=\\s*script\\b)", + next : "script" + }, { + token : "meta.tag", + regex : "<(?=\\s*style\\b)", + next : "style" + }, { + token : "meta.tag", // opening tag + regex : "<\\/?", + next : "tag" + }, { + token : "text", + regex : "\\s+" + }, { + token : "text", + regex : "[^<]+" + } ], + + cdata : [ { + token : "text", + regex : "\\]\\]>", + next : "start" + }, { + token : "text", + merge : true, + regex : "\\s+" + }, { + token : "text", + merge : true, + regex : ".+" + } ], + + comment : [ { + token : "comment", + regex : ".*?-->", + next : "start" + }, { + token : "comment", + merge : true, + regex : ".+" + } ] , + + liquid_start : [{ + token: "variable", + regex: "}}", + next: "start" + }, { + token: "variable", + regex: "%}", + next: "start" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "constant.language.boolean", + regex : "(?:true|false)\\b" + }, { + token : function(value) { + if (functions.hasOwnProperty(value)) + return "support.function"; + else if (keywords.hasOwnProperty(value)) + return "keyword"; + else if (builtinVariables.hasOwnProperty(value)) + return "variable.language"; + else if (definitions.hasOwnProperty(value)) + return "keyword.definition"; + else + return "identifier"; + }, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "\/|\\*|\\-|\\+|=|!=|\\?\\:" + }, { + token : "paren.lparen", + regex : /[\[\({]/ + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token : "text", + regex : "\\s+" + }] + }; + + xmlUtil.tag(this.$rules, "tag", "start"); + xmlUtil.tag(this.$rules, "style", "css-start"); + xmlUtil.tag(this.$rules, "script", "js-start"); + + this.embedRules(JavaScriptHighlightRules, "js-", [{ + token: "comment", + regex: "\\/\\/.*(?=<\\/script>)", + next: "tag" + }, { + token: "meta.tag", + regex: "<\\/(?=script)", + next: "tag" + }]); + + this.embedRules(CssHighlightRules, "css-", [{ + token: "meta.tag", + regex: "<\\/(?=style)", + next: "tag" + }]); +}; +oop.inherits(LiquidHighlightRules, TextHighlightRules); + +exports.LiquidHighlightRules = LiquidHighlightRules; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var CssHighlightRules = function() { + + var properties = lang.arrayToMap( + ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") + ); + + var functions = lang.arrayToMap( + ("rgb|rgba|url|attr|counter|counters").split("|") + ); + + var constants = lang.arrayToMap( + ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") + ); + + var colors = lang.arrayToMap( + ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + + "purple|red|silver|teal|white|yellow").split("|") + ); + + var fonts = lang.arrayToMap( + ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + + "serif|monospace").split("|") + ); + + // regexp must not have capturing parentheses. Use (?:) instead. + // regexps are ordered -> the first match is used + + var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; + var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; + var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; + + var base_ruleset = [ + { + token : "comment", // multi line comment + merge : true, + regex : "\\/\\*", + next : "ruleset_comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : ["constant.numeric"], + regex : "([0-9]+)" + }, { + token : "constant.numeric", // hex6 color + regex : "#[a-f0-9]{6}" + }, { + token : "constant.numeric", // hex3 color + regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses + }, { + token : function(value) { + if (properties.hasOwnProperty(value.toLowerCase())) { + return "support.type"; + } + else if (functions.hasOwnProperty(value.toLowerCase())) { + return "support.function"; + } + else if (constants.hasOwnProperty(value.toLowerCase())) { + return "support.constant"; + } + else if (colors.hasOwnProperty(value.toLowerCase())) { + return "support.constant.color"; + } + else if (fonts.hasOwnProperty(value.toLowerCase())) { + return "support.constant.fonts"; + } + else { + return "text"; + } + }, + regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" + } + ]; + + var ruleset = lang.copyArray(base_ruleset); + ruleset.unshift({ + token : "paren.rparen", + regex : "\\}", + next: "start" + }); + + var media_ruleset = lang.copyArray( base_ruleset ); + media_ruleset.unshift({ + token : "paren.rparen", + regex : "\\}", + next: "media" + }); + + var base_comment = [{ + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + }]; + + var comment = lang.copyArray(base_comment); + comment.unshift({ + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }); + + var media_comment = lang.copyArray(base_comment); + media_comment.unshift({ + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "media" + }); + + var ruleset_comment = lang.copyArray(base_comment); + ruleset_comment.unshift({ + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "ruleset" + }); + + this.$rules = { + "start" : [{ + token : "comment", // multi line comment + merge : true, + regex : "\\/\\*", + next : "comment" + }, { + token: "paren.lparen", + regex: "\\{", + next: "ruleset" + }, { + token: "string", + regex: "@.*?{", + next: "media" + },{ + token: "keyword", + regex: "#[a-z0-9-_]+" + },{ + token: "variable", + regex: "\\.[a-z0-9-_]+" + },{ + token: "string", + regex: ":[a-z0-9-_]+" + },{ + token: "constant", + regex: "[a-z0-9-_]+" + }], + + "media" : [ { + token : "comment", // multi line comment + merge : true, + regex : "\\/\\*", + next : "media_comment" + }, { + token: "paren.lparen", + regex: "\\{", + next: "media_ruleset" + },{ + token: "string", + regex: "\\}", + next: "start" + },{ + token: "keyword", + regex: "#[a-z0-9-_]+" + },{ + token: "variable", + regex: "\\.[a-z0-9-_]+" + },{ + token: "string", + regex: ":[a-z0-9-_]+" + },{ + token: "constant", + regex: "[a-z0-9-_]+" + }], + + "comment" : comment, + + "ruleset" : ruleset, + "ruleset_comment" : ruleset_comment, + + "media_ruleset" : media_ruleset, + "media_comment" : media_comment + }; +}; + +oop.inherits(CssHighlightRules, TextHighlightRules); + +exports.CssHighlightRules = CssHighlightRules; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * Mihai Sucan + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var unicode = require("../unicode"); +var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var JavaScriptHighlightRules = function() { + + // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects + var globals = lang.arrayToMap( + // Constructors + ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + + // E4X + "Namespace|QName|XML|XMLList|" + + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + // Errors + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + + "SyntaxError|TypeError|URIError|" + + // Non-constructor functions + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + + "isNaN|parseFloat|parseInt|" + + // Other + "JSON|Math|" + + // Pseudo + "this|arguments|prototype|window|document" + ).split("|") + ); + + var keywords = lang.arrayToMap( + ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + + "const|yield|import|get|set").split("|") + ); + + // keywords which can be followed by regular expressions + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; + + var deprecated = lang.arrayToMap( + ("__parent__|__count__|escape|unescape|with|__proto__").split("|") + ); + + var definitions = lang.arrayToMap(("const|let|var|function").split("|")); + + var buildinConstants = lang.arrayToMap( + ("null|Infinity|NaN|undefined").split("|") + ); + + var futureReserved = lang.arrayToMap( + ("class|enum|extends|super|export|implements|private|" + + "public|interface|package|protected|static").split("|") + ); + + // TODO: Unicode escape sequences + var identifierRe = "[" + unicode.packages.L + "\\$_][" + + unicode.packages.L + + unicode.packages.Mn + unicode.packages.Mc + + unicode.packages.Nd + + unicode.packages.Pc + "\\$_]*\\b"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + // regexp must not have capturing parentheses. Use (?:) instead. + // regexps are ordered -> the first match is used + + this.$rules = { + "start" : [ + { + token : "comment", + regex : /\/\/.*$/ + }, + new DocCommentHighlightRules().getStartRule("doc-start"), + { + token : "comment", // multi line comment + merge : true, + regex : /\/\*/, + next : "comment" + }, { + token : "string", + regex : "'", + next : "qstring" + }, { + token : "string", + regex : '"', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0[xX][0-9a-fA-F]+\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" + }, { + token : "constant.language.boolean", + regex : /(?:true|false)\b/ + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ + }, { + token : function(value) { + if (globals.hasOwnProperty(value)) + return "variable.language"; + else if (deprecated.hasOwnProperty(value)) + return "invalid.deprecated"; + else if (definitions.hasOwnProperty(value)) + return "storage.type"; + else if (keywords.hasOwnProperty(value)) + return "keyword"; + else if (buildinConstants.hasOwnProperty(value)) + return "constant.language"; + else if (futureReserved.hasOwnProperty(value)) + return "invalid.illegal"; + else if (value == "debugger") + return "invalid.deprecated"; + else + return "identifier"; + }, + regex : identifierRe + }, { + token : "keyword.operator", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, + next : "regex_allowed" + }, { + token : "punctuation.operator", + regex : /\?|\:|\,|\;|\./, + next : "regex_allowed" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "regex_allowed" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token : "keyword.operator", + regex : /\/=?/, + next : "regex_allowed" + }, { + token: "comment", + regex: /^#!.*$/ + }, { + token : "text", + regex : /\s+/ + } + ], + // regular expressions are only allowed after certain tokens. This + // makes sure we don't mix up regexps with the divison operator + "regex_allowed": [ + { + token : "comment", // multi line comment + merge : true, + regex : "\\/\\*", + next : "comment_regex_allowed" + }, { + token : "comment", + regex : "\\/\\/.*$" + }, { + token: "string.regexp", + regex: "\\/", + next: "regex", + merge: true + }, { + token : "text", + regex : "\\s+" + }, { + // immediately return to the start mode without matching + // anything + token: "empty", + regex: "", + next: "start" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)", + next: "regex" + }, { + // flag + token: "string.regexp", + regex: "/\\w*", + next: "start", + merge: true + }, { + token: "string.regexp", + regex: "[^\\\\/\\[]+", + next: "regex", + merge: true + }, { + token: "string.regexp.charachterclass", + regex: "\\[", + next: "regex_character_class", + merge: true + }, { + token: "empty", + regex: "", + next: "start" + } + ], + "regex_character_class": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)", + next: "regex_character_class" + }, { + token: "string.regexp.charachterclass", + regex: "]", + next: "regex", + merge: true + }, { + token: "string.regexp.charachterclass", + regex: "[^\\\\\\]]+", + next: "regex_character_class", + merge: true + }, { + token: "empty", + regex: "", + next: "start" + } + ], + "comment_regex_allowed" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + merge : true, + next : "regex_allowed" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + merge : true, + next : "start" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : '[^"\\\\]+' + }, { + token : "string", + regex : '"', + next : "start" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "[^'\\\\]+" + }, { + token : "string", + regex : "'", + next : "start" + } + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", + [ new DocCommentHighlightRules().getEndRule("start") ]); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, { + token : "comment.doc", + merge : true, + regex : "\\s+" + }, { + token : "comment.doc", + merge : true, + regex : "TODO" + }, { + token : "comment.doc", + merge : true, + regex : "[^@\\*]+" + }, { + token : "comment.doc", + merge : true, + regex : "." + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +(function() { + + this.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + merge : true, + regex : "\\/\\*(?=\\*)", + next : start + }; + }; + + this.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + merge : true, + regex : "\\*\\/", + next : start + }; + }; + +}).call(DocCommentHighlightRules.prototype); + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { +"use strict"; + +var lang = require("../lib/lang"); + +var formTags = lang.arrayToMap( + ("button|form|input|label|select|textarea").split("|") +); + +var tableTags = lang.arrayToMap( + ("table|tbody|td|tfoot|th|tr").split("|") +); + +function string(state) { + return [{ + token : "string", + regex : '".*?"' + }, { + token : "string", // multi line string start + merge : true, + regex : '["].*', + next : state + "_qqstring" + }, { + token : "string", + regex : "'.*?'" + }, { + token : "string", // multi line string start + merge : true, + regex : "['].*", + next : state + "_qstring" + }]; +} + +function multiLineString(quote, state) { + return [{ + token : "string", + merge : true, + regex : ".*?" + quote, + next : state + }, { + token : "string", + merge : true, + regex : '.+' + }]; +} + +exports.tag = function(states, name, nextState) { + states[name] = [{ + token : "text", + regex : "\\s+" + }, { + //token : "meta.tag", + + token : function(value) { + if ( value==='a' ) { + return "meta.tag.anchor"; + } + else if ( value==='img' ) { + return "meta.tag.image"; + } + else if ( value==='script' ) { + return "meta.tag.script"; + } + else if ( value==='style' ) { + return "meta.tag.style"; + } + else if (formTags.hasOwnProperty(value.toLowerCase())) { + return "meta.tag.form"; + } + else if (tableTags.hasOwnProperty(value.toLowerCase())) { + return "meta.tag.table"; + } + else { + return "meta.tag"; + } + }, + merge : true, + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" + }, { + token: "empty", + regex: "", + next : name + "_embed_attribute_list" + }]; + + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); + + states[name + "_embed_attribute_list"] = [{ + token : "meta.tag", + merge : true, + regex : "\/?>", + next : nextState + }, { + token : "keyword.operator", + regex : "=" + }, { + token : "entity.other.attribute-name", + regex : "[-_a-zA-Z0-9:]+" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "text", + regex : "\\s+" + }].concat(string(name)); +}; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { +"use strict"; + +var Range = require("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + var match = line.match(/^(\s+)/); + if (match) { + return match[1]; + } + + return ""; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); diff --git a/apps/files_texteditor/js/aceeditor/mode-liquid.js b/apps/files_texteditor/js/aceeditor/mode-liquid.js new file mode 100755 index 00000000000..1a23cc53ab5 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-liquid.js @@ -0,0 +1 @@ +define("ace/mode/liquid",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/liquid_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(a,b,c){var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./liquid_highlight_rules").LiquidHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=[],g=/^(\s*)#/;for(var h=c;h<=d;h++)if(!g.test(b.getLine(h))){e=!1;break}if(e){var j=new i(0,0,0,0);for(var h=c;h<=d;h++){var k=b.getLine(h),l=k.match(g);j.start.row=h,j.end.row=h,j.end.column=l[0].length,b.replace(j,l[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);h&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/liquid_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/lib/lang","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("../lib/lang"),h=a("./xml_util"),i=a("./text_highlight_rules").TextHighlightRules,j=function(){var a=g.arrayToMap("date|capitalize|downcase|upcase|first|last|join|sort|map|size|escape|escape_once|strip_html|strip_newlines|newline_to_br|replace|replace_first|truncate|truncatewords|prepend|append|minus|plus|times|divided_by|split".split("|")),b=g.arrayToMap("capture|endcapture|case|endcase|when|comment|endcomment|cycle|for|endfor|in|reversed|if|endif|else|elsif|include|endinclude|unless|endunless|style|text|image|widget|plugin|marker|endmarker|tablerow|endtablerow".split("|")),c=g.arrayToMap(["forloop"]),d=g.arrayToMap("assign".split("|"));this.$rules={start:[{token:"variable",regex:"{%",next:"liquid_start"},{token:"variable",regex:"{{",next:"liquid_start"},{token:"meta.tag",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<(?=\\s*script\\b)",next:"script"},{token:"meta.tag",regex:"<(?=\\s*style\\b)",next:"style"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}],liquid_start:[{token:"variable",regex:"}}",next:"start"},{token:"variable",regex:"%}",next:"start"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return a.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"variable.language":d.hasOwnProperty(e)?"keyword.definition":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"/|\\*|\\-|\\+|=|!=|\\?\\:"},{token:"paren.lparen",regex:/[\[\({]/},{token:"paren.rparen",regex:/[\])}]/},{token:"text",regex:"\\s+"}]},h.tag(this.$rules,"tag","start"),h.tag(this.$rules,"style","css-start"),h.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(j,i),b.LiquidHighlightRules=j}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f=e.arrayToMap("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace".split("|")),g="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",i="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",j=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+g+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:["constant.numeric"],regex:"([0-9]+)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:i},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":f.hasOwnProperty(e.toLowerCase())?"support.constant.fonts":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],k=e.copyArray(j);k.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var l=e.copyArray(j);l.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var m=[{token:"comment",merge:!0,regex:".+"}],n=e.copyArray(m);n.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var o=e.copyArray(m);o.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var p=e.copyArray(m);p.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:n,ruleset:k,ruleset_comment:p,media_ruleset:l,media_comment:o}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/unicode","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("../unicode"),g=a("./doc_comment_highlight_rules").DocCommentHighlightRules,h=a("./text_highlight_rules").TextHighlightRules,i=function(){var a=e.arrayToMap("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|Namespace|QName|XML|XMLList|ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|SyntaxError|TypeError|URIError|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|isNaN|parseFloat|parseInt|JSON|Math|this|arguments|prototype|window|document".split("|")),b=e.arrayToMap("break|case|catch|continue|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|const|yield|import|get|set".split("|")),c="case|do|else|finally|in|instanceof|return|throw|try|typeof|yield",d=e.arrayToMap("__parent__|__count__|escape|unescape|with|__proto__".split("|")),h=e.arrayToMap("const|let|var|function".split("|")),i=e.arrayToMap("null|Infinity|NaN|undefined".split("|")),j=e.arrayToMap("class|enum|extends|super|export|implements|private|public|interface|package|protected|static".split("|")),k="["+f.packages.L+"\\$_]["+f.packages.L+f.packages.Mn+f.packages.Mc+f.packages.Nd+f.packages.Pc+"\\$_]*\\b",l="\\\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)";this.$rules={start:[{token:"comment",regex:/\/\/.*$/},(new g).getStartRule("doc-start"),{token:"comment",merge:!0,regex:/\/\*/,next:"comment"},{token:"string",regex:"'",next:"qstring"},{token:"string",regex:'"',next:"qqstring"},{token:"constant.numeric",regex:/0[xX][0-9a-fA-F]+\b/},{token:"constant.numeric",regex:/[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/},{token:["storage.type","punctuation.operator","support.function","punctuation.operator","entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen","variable.parameter","paren.rparen"],regex:"("+k+")(\\.)(prototype)(\\.)("+k+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))"},{token:["storage.type","punctuation.operator","support.function","punctuation.operator","entity.name.function","text","keyword.operator","text"],regex:"("+k+")(\\.)(prototype)(\\.)("+k+")(\\s*)(=)(\\s*)"},{token:["storage.type","punctuation.operator","entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen","variable.parameter","paren.rparen"],regex:"("+k+")(\\.)("+k+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))"},{token:["entity.name.function","text","keyword.operator","text","storage.type","text","paren.lparen","variable.parameter","paren.rparen"],regex:"("+k+")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))"},{token:["storage.type","text","entity.name.function","text","paren.lparen","variable.parameter","paren.rparen"],regex:"(function)(\\s+)("+k+")(\\s*)(\\()(.*?)(\\))"},{token:["entity.name.function","text","punctuation.operator","text","storage.type","text","paren.lparen","variable.parameter","paren.rparen"],regex:"("+k+")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))"},{token:["text","text","storage.type","text","paren.lparen","variable.parameter","paren.rparen"],regex:"(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))"},{token:"constant.language.boolean",regex:/(?:true|false)\b/},{token:"keyword",regex:"(?:"+c+")\\b",next:"regex_allowed"},{token:["punctuation.operator","support.function"],regex:/(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/},{token:["punctuation.operator","support.function.dom"],regex:/(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/},{token:["punctuation.operator","support.constant"],regex:/(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/},{token:["storage.type","punctuation.operator","support.function.firebug"],regex:/(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/},{token:function(c){return a.hasOwnProperty(c)?"variable.language":d.hasOwnProperty(c)?"invalid.deprecated":h.hasOwnProperty(c)?"storage.type":b.hasOwnProperty(c)?"keyword":i.hasOwnProperty(c)?"constant.language":j.hasOwnProperty(c)?"invalid.illegal":c=="debugger"?"invalid.deprecated":"identifier"},regex:k},{token:"keyword.operator",regex:/!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-lua-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-lua-uncompressed.js index 454108c6d44..c3f875475e9 100755 --- a/apps/files_texteditor/js/aceeditor/mode-lua-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-lua-uncompressed.js @@ -521,13 +521,3 @@ oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-lua.js b/apps/files_texteditor/js/aceeditor/mode-lua.js index 63b812c6bd7..8f7471e7bf2 100755 --- a/apps/files_texteditor/js/aceeditor/mode-lua.js +++ b/apps/files_texteditor/js/aceeditor/mode-lua.js @@ -1 +1 @@ -define("ace/mode/lua",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/lua_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./lua_highlight_rules").LuaHighlightRules,h=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=["function","then","do","repeat"];if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);if(h)d+=c;else for(var i in f){var j=f[i];if(j.type!="keyword")continue;var k=g.indexOf(j.value);if(k!=-1){d+=c;break}}}return d}}.call(h.prototype),b.Mode=h}),define("ace/mode/lua_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("break|do|else|elseif|end|for|function|if|in|local|repeat|return|then|until|while|or|and|not".split("|")),b=e.arrayToMap("true|false|nil|_G|_VERSION".split("|")),c=e.arrayToMap("string|xpcall|package|tostring|print|os|unpack|require|getfenv|setmetatable|next|assert|tonumber|io|rawequal|collectgarbage|getmetatable|module|rawset|math|debug|pcall|table|newproxy|type|coroutine|_G|select|gcinfo|pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|load|error|loadfile|sub|upper|len|gfind|rep|find|match|char|dump|gmatch|reverse|byte|format|gsub|lower|preload|loadlib|loaded|loaders|cpath|config|path|seeall|exit|setlocale|date|getenv|difftime|remove|time|clock|tmpname|rename|execute|lines|write|close|flush|open|output|type|read|stderr|stdin|input|stdout|popen|tmpfile|log|max|acos|huge|ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|gethook|setmetatable|setlocal|traceback|setfenv|getinfo|setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|foreachi|maxn|foreach|concat|sort|remove|resume|yield|status|wrap|create|running".split("|")),d=e.arrayToMap("string|package|os|io|math|debug|table|coroutine".split("|")),f=e.arrayToMap("__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber".split("|")),g=e.arrayToMap("".split("|")),h=e.arrayToMap("setn|foreach|foreachi|gcinfo|log10|maxn".split("|")),i="",j="(?:(?:[1-9]\\d*)|(?:0))",k="(?:0[xX][\\dA-Fa-f]+)",l="(?:"+j+"|"+k+")",m="(?:\\.\\d+)",n="(?:\\d+)",o="(?:(?:"+n+"?"+m+")|(?:"+n+"\\.))",p="(?:"+o+")",q=[];this.$rules={start:[{token:"comment",regex:i+"\\-\\-\\[\\[.*\\]\\]"},{token:"comment",regex:i+"\\-\\-\\[\\=\\[.*\\]\\=\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={2}\\[.*\\]\\={2}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={3}\\[.*\\]\\={3}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={4}\\[.*\\]\\={4}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]"},{token:"comment",regex:i+"\\-\\-\\[\\[.*$",merge:!0,next:"qcomment"},{token:"comment",regex:i+"\\-\\-\\[\\=\\[.*$",merge:!0,next:"qcomment1"},{token:"comment",regex:i+"\\-\\-\\[\\={2}\\[.*$",merge:!0,next:"qcomment2"},{token:"comment",regex:i+"\\-\\-\\[\\={3}\\[.*$",merge:!0,next:"qcomment3"},{token:"comment",regex:i+"\\-\\-\\[\\={4}\\[.*$",merge:!0,next:"qcomment4"},{token:function(a){var b=/\-\-\[(\=+)\[/,c;return(c=b.exec(a))!=null&&(c=c[1])!=undefined&&q.push(c.length),"comment"},regex:i+"\\-\\-\\[\\={5}\\=*\\[.*$",merge:!0,next:"qcomment5"},{token:"comment",regex:"\\-\\-.*$"},{token:"string",regex:i+"\\[\\[.*\\]\\]"},{token:"string",regex:i+"\\[\\=\\[.*\\]\\=\\]"},{token:"string",regex:i+"\\[\\={2}\\[.*\\]\\={2}\\]"},{token:"string",regex:i+"\\[\\={3}\\[.*\\]\\={3}\\]"},{token:"string",regex:i+"\\[\\={4}\\[.*\\]\\={4}\\]"},{token:"string",regex:i+"\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]"},{token:"string",regex:i+"\\[\\[.*$",merge:!0,next:"qstring"},{token:"string",regex:i+"\\[\\=\\[.*$",merge:!0,next:"qstring1"},{token:"string",regex:i+"\\[\\={2}\\[.*$",merge:!0,next:"qstring2"},{token:"string",regex:i+"\\[\\={3}\\[.*$",merge:!0,next:"qstring3"},{token:"string",regex:i+"\\[\\={4}\\[.*$",merge:!0,next:"qstring4"},{token:function(a){var b=/\[(\=+)\[/,c;return(c=b.exec(a))!=null&&(c=c[1])!=undefined&&q.push(c.length),"string"},regex:i+"\\[\\={5}\\=*\\[.*$",merge:!0,next:"qstring5"},{token:"string",regex:i+'"(?:[^\\\\]|\\\\.)*?"'},{token:"string",regex:i+"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:p},{token:"constant.numeric",regex:l+"\\b"},{token:function(e){return a.hasOwnProperty(e)?"keyword":b.hasOwnProperty(e)?"constant.language":g.hasOwnProperty(e)?"invalid.illegal":d.hasOwnProperty(e)?"constant.library":h.hasOwnProperty(e)?"invalid.deprecated":c.hasOwnProperty(e)?"support.function":f.hasOwnProperty(e)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\."},{token:"paren.lparen",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}],qcomment:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment1:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\=\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment2:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment3:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment4:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment5:[{token:function(a){var b=/\](\=+)\]/,c=this.rules.qcomment5[0],d;c.next="start";if((d=b.exec(a))!=null&&(d=d[1])!=undefined){var e=d.length,f;(f=q.pop())!=e&&(q.push(f),c.next="qcomment5")}return"comment"},regex:"(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring1:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\=\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring2:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring3:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring4:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring5:[{token:function(a){var b=/\](\=+)\]/,c=this.rules.qstring5[0],d;c.next="start";if((d=b.exec(a))!=null&&(d=d[1])!=undefined){var e=d.length,f;(f=q.pop())!=e&&(q.push(f),c.next="qstring5")}return"string"},regex:"(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.LuaHighlightRules=g}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/lua",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/lua_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./lua_highlight_rules").LuaHighlightRules,h=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=["function","then","do","repeat"];if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);if(h)d+=c;else for(var i in f){var j=f[i];if(j.type!="keyword")continue;var k=g.indexOf(j.value);if(k!=-1){d+=c;break}}}return d}}.call(h.prototype),b.Mode=h}),define("ace/mode/lua_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("break|do|else|elseif|end|for|function|if|in|local|repeat|return|then|until|while|or|and|not".split("|")),b=e.arrayToMap("true|false|nil|_G|_VERSION".split("|")),c=e.arrayToMap("string|xpcall|package|tostring|print|os|unpack|require|getfenv|setmetatable|next|assert|tonumber|io|rawequal|collectgarbage|getmetatable|module|rawset|math|debug|pcall|table|newproxy|type|coroutine|_G|select|gcinfo|pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|load|error|loadfile|sub|upper|len|gfind|rep|find|match|char|dump|gmatch|reverse|byte|format|gsub|lower|preload|loadlib|loaded|loaders|cpath|config|path|seeall|exit|setlocale|date|getenv|difftime|remove|time|clock|tmpname|rename|execute|lines|write|close|flush|open|output|type|read|stderr|stdin|input|stdout|popen|tmpfile|log|max|acos|huge|ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|gethook|setmetatable|setlocal|traceback|setfenv|getinfo|setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|foreachi|maxn|foreach|concat|sort|remove|resume|yield|status|wrap|create|running".split("|")),d=e.arrayToMap("string|package|os|io|math|debug|table|coroutine".split("|")),f=e.arrayToMap("__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber".split("|")),g=e.arrayToMap("".split("|")),h=e.arrayToMap("setn|foreach|foreachi|gcinfo|log10|maxn".split("|")),i="",j="(?:(?:[1-9]\\d*)|(?:0))",k="(?:0[xX][\\dA-Fa-f]+)",l="(?:"+j+"|"+k+")",m="(?:\\.\\d+)",n="(?:\\d+)",o="(?:(?:"+n+"?"+m+")|(?:"+n+"\\.))",p="(?:"+o+")",q=[];this.$rules={start:[{token:"comment",regex:i+"\\-\\-\\[\\[.*\\]\\]"},{token:"comment",regex:i+"\\-\\-\\[\\=\\[.*\\]\\=\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={2}\\[.*\\]\\={2}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={3}\\[.*\\]\\={3}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={4}\\[.*\\]\\={4}\\]"},{token:"comment",regex:i+"\\-\\-\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]"},{token:"comment",regex:i+"\\-\\-\\[\\[.*$",merge:!0,next:"qcomment"},{token:"comment",regex:i+"\\-\\-\\[\\=\\[.*$",merge:!0,next:"qcomment1"},{token:"comment",regex:i+"\\-\\-\\[\\={2}\\[.*$",merge:!0,next:"qcomment2"},{token:"comment",regex:i+"\\-\\-\\[\\={3}\\[.*$",merge:!0,next:"qcomment3"},{token:"comment",regex:i+"\\-\\-\\[\\={4}\\[.*$",merge:!0,next:"qcomment4"},{token:function(a){var b=/\-\-\[(\=+)\[/,c;return(c=b.exec(a))!=null&&(c=c[1])!=undefined&&q.push(c.length),"comment"},regex:i+"\\-\\-\\[\\={5}\\=*\\[.*$",merge:!0,next:"qcomment5"},{token:"comment",regex:"\\-\\-.*$"},{token:"string",regex:i+"\\[\\[.*\\]\\]"},{token:"string",regex:i+"\\[\\=\\[.*\\]\\=\\]"},{token:"string",regex:i+"\\[\\={2}\\[.*\\]\\={2}\\]"},{token:"string",regex:i+"\\[\\={3}\\[.*\\]\\={3}\\]"},{token:"string",regex:i+"\\[\\={4}\\[.*\\]\\={4}\\]"},{token:"string",regex:i+"\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]"},{token:"string",regex:i+"\\[\\[.*$",merge:!0,next:"qstring"},{token:"string",regex:i+"\\[\\=\\[.*$",merge:!0,next:"qstring1"},{token:"string",regex:i+"\\[\\={2}\\[.*$",merge:!0,next:"qstring2"},{token:"string",regex:i+"\\[\\={3}\\[.*$",merge:!0,next:"qstring3"},{token:"string",regex:i+"\\[\\={4}\\[.*$",merge:!0,next:"qstring4"},{token:function(a){var b=/\[(\=+)\[/,c;return(c=b.exec(a))!=null&&(c=c[1])!=undefined&&q.push(c.length),"string"},regex:i+"\\[\\={5}\\=*\\[.*$",merge:!0,next:"qstring5"},{token:"string",regex:i+'"(?:[^\\\\]|\\\\.)*?"'},{token:"string",regex:i+"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:p},{token:"constant.numeric",regex:l+"\\b"},{token:function(e){return a.hasOwnProperty(e)?"keyword":b.hasOwnProperty(e)?"constant.language":g.hasOwnProperty(e)?"invalid.illegal":d.hasOwnProperty(e)?"constant.library":h.hasOwnProperty(e)?"invalid.deprecated":c.hasOwnProperty(e)?"support.function":f.hasOwnProperty(e)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\."},{token:"paren.lparen",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}],qcomment:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment1:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\=\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment2:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment3:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment4:[{token:"comment",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qcomment5:[{token:function(a){var b=/\](\=+)\]/,c=this.rules.qcomment5[0],d;c.next="start";if((d=b.exec(a))!=null&&(d=d[1])!=undefined){var e=d.length,f;(f=q.pop())!=e&&(q.push(f),c.next="qcomment5")}return"comment"},regex:"(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",next:"start"},{token:"comment",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring1:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\=\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring2:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring3:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring4:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",next:"start"},{token:"string",merge:!0,regex:".+"}],qstring5:[{token:function(a){var b=/\](\=+)\]/,c=this.rules.qstring5[0],d;c.next="start";if((d=b.exec(a))!=null&&(d=d[1])!=undefined){var e=d.length,f;(f=q.pop())!=e&&(q.push(f),c.next="qstring5")}return"string"},regex:"(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.LuaHighlightRules=g}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-markdown-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-markdown-uncompressed.js index 0ddb789736c..a8edaafeef8 100755 --- a/apps/files_texteditor/js/aceeditor/mode-markdown-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-markdown-uncompressed.js @@ -337,12 +337,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -350,46 +358,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -397,7 +498,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -412,29 +513,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -459,7 +560,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -471,10 +572,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -486,9 +587,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -507,9 +608,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -538,28 +639,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -744,195 +849,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1121,19 +1038,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1142,7 +1059,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1152,7 +1069,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1489,6 +1407,9 @@ var XmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -1496,6 +1417,9 @@ var XmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -1589,7 +1513,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : '["].*', - next : state + "-qqstring" + next : state + "_qqstring" }, { token : "string", regex : "'.*?'" @@ -1597,7 +1521,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : "['].*", - next : state + "-qstring" + next : state + "_qstring" }]; } @@ -1645,18 +1569,18 @@ exports.tag = function(states, name, nextState) { } }, merge : true, - regex : "[-_a-zA-Z0-9:!]+", - next : name + "embed-attribute-list" + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" }, { token: "empty", regex: "", - next : name + "embed-attribute-list" + next : name + "_embed_attribute_list" }]; - states[name + "-qstring"] = multiLineString("'", name + "embed-attribute-list"); - states[name + "-qqstring"] = multiLineString("\"", name + "embed-attribute-list"); + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); - states[name + "embed-attribute-list"] = [{ + states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", @@ -2269,31 +2193,7 @@ var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( - ("-moz-appearance|-moz-box-sizing|-webkit-box-sizing|-moz-outline-radius|-moz-transform|-webkit-transform|" + - "appearance|azimuth|background-attachment|background-color|background-image|" + - "background-origin|background-position|background-repeat|background|border-bottom-color|" + - "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + - "border-color|border-left-color|border-left-style|border-left-width|" + - "border-left|border-right-color|border-right-style|border-right-width|" + - "border-right|border-spacing|border-style|border-top-color|" + - "border-top-style|border-top-width|border-top|border-width|border|" + - "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + - "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + - "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + - "font-stretch|font-style|font-variant|font-weight|font|height|left|" + - "letter-spacing|line-height|list-style-image|list-style-position|" + - "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + - "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + - "min-width|-moz-border-radius|opacity|orphans|outline-color|outline-offset|outline-radius|" + - "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + - "padding-left|padding-right|padding-top|padding|page-break-after|" + - "page-break-before|page-break-inside|page|pause-after|pause-before|" + - "pause|pitch-range|pitch|play-during|pointer-events|position|quotes|resize|richness|right|" + - "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + - "stress|table-layout|text-align|text-decoration|text-indent|" + - "text-shadow|text-transform|top|transform|unicode-bidi|vertical-align|" + - "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + - "z-index").split("|") + ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( @@ -2301,27 +2201,7 @@ var CssHighlightRules = function() { ); var constants = lang.arrayToMap( - ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + - "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + - "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + - "decimal-leading-zero|decimal|default|disabled|disc|" + - "distribute-all-lines|distribute-letter|distribute-space|" + - "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + - "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + - "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + - "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + - "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + - "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + - "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + - "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + - "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + - "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + - "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + - "solid|square|static|strict|super|sw-resize|table-footer-group|" + - "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + - "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + - "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + - "zero").split("|") + ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( @@ -2329,32 +2209,49 @@ var CssHighlightRules = function() { "purple|red|silver|teal|white|yellow").split("|") ); + var fonts = lang.arrayToMap( + ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + + "serif|monospace").split("|") + ); + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; - + var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; + var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; + var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" - },{ + }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { - token : "constant.numeric", - regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : ["constant.numeric"], + regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { @@ -2369,12 +2266,15 @@ var CssHighlightRules = function() { else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } + else if (fonts.hasOwnProperty(value.toLowerCase())) { + return "support.constant.fonts"; + } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" - } + } ]; var ruleset = lang.copyArray(base_ruleset); @@ -2552,6 +2452,9 @@ var HtmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", @@ -2559,7 +2462,7 @@ var HtmlHighlightRules = function() { }, { token : "meta.tag", regex : "<(?=\s*style\\b)", - next : "css" + next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -2567,6 +2470,9 @@ var HtmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -2598,7 +2504,7 @@ var HtmlHighlightRules = function() { }; xmlUtil.tag(this.$rules, "tag", "start"); - xmlUtil.tag(this.$rules, "css", "css-start"); + xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ @@ -2860,7 +2766,7 @@ var MarkdownHighlightRules = function() { token : "empty_line", regex : '^$' }, { // code span ` - token : "support.function", + token : ["support.function", "support.function", "support.function"], regex : "(`+)([^\\r]*?[^`])(\\1)" }, { // code block token : "support.function", @@ -2890,7 +2796,7 @@ var MarkdownHighlightRules = function() { next : "blockquote" }, { // reference token : ["text", "constant", "text", "url", "string", "text"], - regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?\\s*)$" + regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$" }, { // link by reference token : ["text", "string", "text", "constant", "text"], regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])" @@ -2916,10 +2822,10 @@ var MarkdownHighlightRules = function() { regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock" }, { // strong ** __ - token : "string", + token : ["string", "string", "string"], regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)" }, { // emphasis * _ - token : "string", + token : ["string", "string", "string"], regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)" }, { // token : ["text", "url", "text"], @@ -2988,13 +2894,4 @@ var MarkdownHighlightRules = function() { oop.inherits(MarkdownHighlightRules, TextHighlightRules); exports.MarkdownHighlightRules = MarkdownHighlightRules; -});; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file +}); \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-markdown.js b/apps/files_texteditor/js/aceeditor/mode-markdown.js index 4cf7a4a82b4..a45debe0443 100755 --- a/apps/files_texteditor/js/aceeditor/mode-markdown.js +++ b/apps/files_texteditor/js/aceeditor/mode-markdown.js @@ -1 +1 @@ -define("ace/mode/markdown",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/xml","ace/mode/html","ace/tokenizer","ace/mode/markdown_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./xml").Mode,h=a("./html").Mode,i=a("../tokenizer").Tokenizer,j=a("./markdown_highlight_rules").MarkdownHighlightRules,k=function(){var a=new j;this.$tokenizer=new i(a.getRules()),this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"xml-":g,"html-":h})};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){if(a=="listblock"){var d=/^((?:.+)?)([-+*][ ]+)/.exec(b);return d?(new Array(d[1].length+1)).join(" ")+d[2]:""}return this.$getIndent(b)}}.call(k.prototype),b.Mode=k}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"-qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"-qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:!]+",next:b+"embed-attribute-list"},{token:"empty",regex:"",next:b+"embed-attribute-list"}],a[b+"-qstring"]=h("'",b+"embed-attribute-list"),a[b+"-qqstring"]=h('"',b+"embed-attribute-list"),a[b+"embed-attribute-list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./html_highlight_rules").HtmlHighlightRules,j=a("./behaviour/xml").XmlBehaviour,k=a("./folding/html").FoldMode,l=function(){var a=new i;this.$tokenizer=new h(a.getRules()),this.$behaviour=new j,this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g}),this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){return 0},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)},this.checkOutdent=function(a,b,c){return!1}}.call(l.prototype),b.Mode=l}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("-moz-appearance|-moz-box-sizing|-webkit-box-sizing|-moz-outline-radius|-moz-transform|-webkit-transform|appearance|azimuth|background-attachment|background-color|background-image|background-origin|background-position|background-repeat|background|border-bottom-color|border-bottom-style|border-bottom-width|border-bottom|border-collapse|border-color|border-left-color|border-left-style|border-left-width|border-left|border-right-color|border-right-style|border-right-width|border-right|border-spacing|border-style|border-top-color|border-top-style|border-top-width|border-top|border-width|border|bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|counter-reset|cue-after|cue-before|cue|cursor|direction|display|elevation|empty-cells|float|font-family|font-size-adjust|font-size|font-stretch|font-style|font-variant|font-weight|font|height|left|letter-spacing|line-height|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|marker-offset|margin|marks|max-height|max-width|min-height|min-width|-moz-border-radius|opacity|orphans|outline-color|outline-offset|outline-radius|outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page|pause-after|pause-before|pause|pitch-range|pitch|play-during|pointer-events|position|quotes|resize|richness|right|size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|stress|table-layout|text-align|text-decoration|text-indent|text-shadow|text-transform|top|transform|unicode-bidi|vertical-align|visibility|voice-family|volume|white-space|widows|width|word-spacing|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|decimal-leading-zero|decimal|default|disabled|disc|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|inactive|inherit|inline-block|inline|inset|inside|inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|keep-all|left|lighter|line-edge|line-through|line|list-item|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|solid|square|static|strict|super|sw-resize|table-footer-group|table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",g=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:f+"(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],h=e.copyArray(g);h.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var i=e.copyArray(g);i.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var j=[{token:"comment",merge:!0,regex:".+"}],k=e.copyArray(j);k.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var l=e.copyArray(j);l.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var m=e.copyArray(j);m.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:k,ruleset:h,ruleset_comment:m,media_ruleset:i,media_comment:l}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_util"),h=a("./text_highlight_rules").TextHighlightRules,i=function(){this.$rules={start:[{token:"text",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<(?=s*script\\b)",next:"script"},{token:"meta.tag",regex:"<(?=s*style\\b)",next:"css"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},g.tag(this.$rules,"tag","start"),g.tag(this.$rules,"css","css-start"),g.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,h),b.HtmlHighlightRules=i}),define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./mixed").FoldMode,f=a("./xml").FoldMode,g=a("./cstyle").FoldMode,h=b.FoldMode=function(){e.call(this,new f({area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1,li:1,dt:1,dd:1,p:1,rt:1,rp:1,optgroup:1,option:1,colgroup:1,td:1,th:1}),{"js-":new g,"css-":new g})};d.inherits(h,e)}),define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a,b){this.defaultMode=a,this.subModes=b};d.inherits(f,e),function(){this.$getMode=function(a){for(var b in this.subModes)if(a.indexOf(b)===0)return this.subModes[b];return null},this.$tryMode=function(a,b,c,d){var e=this.$getMode(a);return e?e.getFoldWidget(b,c,d):""},this.getFoldWidget=function(a,b,c){return this.$tryMode(a.getState(c-1),a,b,c)||this.$tryMode(a.getState(c),a,b,c)||this.defaultMode.getFoldWidget(a,b,c)},this.getFoldWidgetRange=function(a,b,c){var d=this.$getMode(a.getState(c-1));if(!d||!d.getFoldWidget(a,b,c))d=this.$getMode(a.getState(c));if(!d||!d.getFoldWidget(a,b,c))d=this.defaultMode;return d.getFoldWidgetRange(a,b,c)}}.call(f.prototype)}),define("ace/mode/markdown_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/html_highlight_rules","ace/mode/css_highlight_rules"],function(a,b,c){function j(a,b){return{token:"support.function",regex:"^```"+a+"\\s*$",next:b+"start"}}"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./html_highlight_rules").HtmlHighlightRules,i=a("./css_highlight_rules").CssHighlightRules,k=function(){this.$rules={start:[{token:"empty_line",regex:"^$"},{token:"support.function",regex:"(`+)([^\\r]*?[^`])(\\1)"},{token:"support.function",regex:"^[ ]{4}.+"},{token:"markup.heading.1",regex:"^=+(?=\\s*$)"},{token:"markup.heading.1",regex:"^\\-+(?=\\s*$)"},{token:function(a){return"markup.heading."+a.length},regex:"^#{1,6}"},j("javascript","js-"),j("xml","xml-"),j("html","html-"),j("css","css-"),{token:"support.function",regex:"^```[a-zA-Z]+\\s*$",next:"githubblock"},{token:"string",regex:"^>[ ].+$",next:"blockquote"},{token:["text","constant","text","url","string","text"],regex:'^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:["][^"]+["])?\\s*)$'},{token:["text","string","text","constant","text"],regex:"(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"},{token:["text","string","text","markup.underline","string","text"],regex:'(\\[)(\\[[^\\]]*\\]|[^\\[\\]]*)(\\]\\([ \\t]*)(?)((?:[ \t]*"(?:.*?)"[ \\t]*)?)(\\))'},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"},{token:"markup.list",regex:"^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",next:"listblock"},{token:"string",regex:"([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"},{token:"string",regex:"([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"},{token:["text","url","text"],regex:"(<)((?:https?|ftp|dict):[^'\">\\s]+|(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+)(>)"},{token:"text",regex:"[^\\*_%$`\\[#<>]+"}],listblock:[{token:"empty_line",regex:"^$",next:"start"},{token:"markup.list",regex:".+"}],blockquote:[{token:"empty_line",regex:"^\\s*$",next:"start"},{token:"string",regex:".+"}],githubblock:[{token:"support.function",regex:"^```",next:"start"},{token:"support.function",regex:".+"}]},this.embedRules(f,"js-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(h,"html-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(i,"css-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(g,"xml-",[{token:"support.function",regex:"^```",next:"start"}])};d.inherits(k,e),b.MarkdownHighlightRules=k}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/markdown",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/xml","ace/mode/html","ace/tokenizer","ace/mode/markdown_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./xml").Mode,h=a("./html").Mode,i=a("../tokenizer").Tokenizer,j=a("./markdown_highlight_rules").MarkdownHighlightRules,k=function(){var a=new j;this.$tokenizer=new i(a.getRules()),this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"xml-":g,"html-":h})};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){if(a=="listblock"){var d=/^((?:.+)?)([-+*][ ]+)/.exec(b);return d?(new Array(d[1].length+1)).join(" ")+d[2]:""}return this.$getIndent(b)}}.call(k.prototype),b.Mode=k}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/tokenizer","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("./javascript").Mode,g=a("./css").Mode,h=a("../tokenizer").Tokenizer,i=a("./html_highlight_rules").HtmlHighlightRules,j=a("./behaviour/xml").XmlBehaviour,k=a("./folding/html").FoldMode,l=function(){var a=new i;this.$tokenizer=new h(a.getRules()),this.$behaviour=new j,this.$embeds=a.getEmbeds(),this.createModeDelegates({"js-":f,"css-":g}),this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){return 0},this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)},this.checkOutdent=function(a,b,c){return!1}}.call(l.prototype),b.Mode=l}),define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./css_highlight_rules").CssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../worker/worker_client").WorkerClient,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.foldingRules="cStyle",this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new i(["ace"],"worker-css.js","ace/mode/css_worker","Worker");return b.attachToDocument(a.getDocument()),b.on("csslint",function(b){var c=[];b.data.forEach(function(a){c.push({row:a.line-1,column:a.col-1,text:a.message,type:a.type,lint:a})}),a.setAnnotations(c)}),b}}.call(k.prototype),b.Mode=k}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index".split("|")),b=e.arrayToMap("rgb|rgba|url|attr|counter|counters".split("|")),c=e.arrayToMap("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero".split("|")),d=e.arrayToMap("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow".split("|")),f=e.arrayToMap("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace".split("|")),g="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",i="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",j=[{token:"comment",merge:!0,regex:"\\/\\*",next:"ruleset_comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+g+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:["constant.numeric"],regex:"([0-9]+)"},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:i},{token:function(e){return a.hasOwnProperty(e.toLowerCase())?"support.type":b.hasOwnProperty(e.toLowerCase())?"support.function":c.hasOwnProperty(e.toLowerCase())?"support.constant":d.hasOwnProperty(e.toLowerCase())?"support.constant.color":f.hasOwnProperty(e.toLowerCase())?"support.constant.fonts":"text"},regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"}],k=e.copyArray(j);k.unshift({token:"paren.rparen",regex:"\\}",next:"start"});var l=e.copyArray(j);l.unshift({token:"paren.rparen",regex:"\\}",next:"media"});var m=[{token:"comment",merge:!0,regex:".+"}],n=e.copyArray(m);n.unshift({token:"comment",regex:".*?\\*\\/",next:"start"});var o=e.copyArray(m);o.unshift({token:"comment",regex:".*?\\*\\/",next:"media"});var p=e.copyArray(m);p.unshift({token:"comment",regex:".*?\\*\\/",next:"ruleset"}),this.$rules={start:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"paren.lparen",regex:"\\{",next:"ruleset"},{token:"string",regex:"@.*?{",next:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],media:[{token:"comment",merge:!0,regex:"\\/\\*",next:"media_comment"},{token:"paren.lparen",regex:"\\{",next:"media_ruleset"},{token:"string",regex:"\\}",next:"start"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"}],comment:n,ruleset:k,ruleset_comment:p,media_ruleset:l,media_comment:o}};d.inherits(g,f),b.CssHighlightRules=g}),define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./css_highlight_rules").CssHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_util"),h=a("./text_highlight_rules").TextHighlightRules,i=function(){this.$rules={start:[{token:"text",merge:!0,regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<(?=s*script\\b)",next:"script"},{token:"meta.tag",regex:"<(?=s*style\\b)",next:"style"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",merge:!0,regex:"\\s+"},{token:"text",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},g.tag(this.$rules,"tag","start"),g.tag(this.$rules,"style","css-start"),g.tag(this.$rules,"script","js-start"),this.embedRules(f,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}]),this.embedRules(e,"css-",[{token:"meta.tag",regex:"<\\/(?=style)",next:"tag"}])};d.inherits(i,h),b.HtmlHighlightRules=i}),define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./mixed").FoldMode,f=a("./xml").FoldMode,g=a("./cstyle").FoldMode,h=b.FoldMode=function(){e.call(this,new f({area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1,li:1,dt:1,dd:1,p:1,rt:1,rp:1,optgroup:1,option:1,colgroup:1,td:1,th:1}),{"js-":new g,"css-":new g})};d.inherits(h,e)}),define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a,b){this.defaultMode=a,this.subModes=b};d.inherits(f,e),function(){this.$getMode=function(a){for(var b in this.subModes)if(a.indexOf(b)===0)return this.subModes[b];return null},this.$tryMode=function(a,b,c,d){var e=this.$getMode(a);return e?e.getFoldWidget(b,c,d):""},this.getFoldWidget=function(a,b,c){return this.$tryMode(a.getState(c-1),a,b,c)||this.$tryMode(a.getState(c),a,b,c)||this.defaultMode.getFoldWidget(a,b,c)},this.getFoldWidgetRange=function(a,b,c){var d=this.$getMode(a.getState(c-1));if(!d||!d.getFoldWidget(a,b,c))d=this.$getMode(a.getState(c));if(!d||!d.getFoldWidget(a,b,c))d=this.defaultMode;return d.getFoldWidgetRange(a,b,c)}}.call(f.prototype)}),define("ace/mode/markdown_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/html_highlight_rules","ace/mode/css_highlight_rules"],function(a,b,c){function j(a,b){return{token:"support.function",regex:"^```"+a+"\\s*$",next:b+"start"}}"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=a("./javascript_highlight_rules").JavaScriptHighlightRules,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./html_highlight_rules").HtmlHighlightRules,i=a("./css_highlight_rules").CssHighlightRules,k=function(){this.$rules={start:[{token:"empty_line",regex:"^$"},{token:["support.function","support.function","support.function"],regex:"(`+)([^\\r]*?[^`])(\\1)"},{token:"support.function",regex:"^[ ]{4}.+"},{token:"markup.heading.1",regex:"^=+(?=\\s*$)"},{token:"markup.heading.1",regex:"^\\-+(?=\\s*$)"},{token:function(a){return"markup.heading."+a.length},regex:"^#{1,6}"},j("javascript","js-"),j("xml","xml-"),j("html","html-"),j("css","css-"),{token:"support.function",regex:"^```[a-zA-Z]+\\s*$",next:"githubblock"},{token:"string",regex:"^>[ ].+$",next:"blockquote"},{token:["text","constant","text","url","string","text"],regex:'^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:["][^"]+["])?(\\s*))$'},{token:["text","string","text","constant","text"],regex:"(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"},{token:["text","string","text","markup.underline","string","text"],regex:'(\\[)(\\[[^\\]]*\\]|[^\\[\\]]*)(\\]\\([ \\t]*)(?)((?:[ ]*"(?:.*?)"[ \\t]*)?)(\\))'},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"},{token:"constant",regex:"^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"},{token:"markup.list",regex:"^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",next:"listblock"},{token:["string","string","string"],regex:"([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"},{token:["string","string","string"],regex:"([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"},{token:["text","url","text"],regex:"(<)((?:https?|ftp|dict):[^'\">\\s]+|(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+)(>)"},{token:"text",regex:"[^\\*_%$`\\[#<>]+"}],listblock:[{token:"empty_line",regex:"^$",next:"start"},{token:"markup.list",regex:".+"}],blockquote:[{token:"empty_line",regex:"^\\s*$",next:"start"},{token:"string",regex:".+"}],githubblock:[{token:"support.function",regex:"^```",next:"start"},{token:"support.function",regex:".+"}]},this.embedRules(f,"js-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(h,"html-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(i,"css-",[{token:"support.function",regex:"^```",next:"start"}]),this.embedRules(g,"xml-",[{token:"support.function",regex:"^```",next:"start"}])};d.inherits(k,e),b.MarkdownHighlightRules=k}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-ocaml-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-ocaml-uncompressed.js index b91107dea60..c268a4f8cae 100755 --- a/apps/files_texteditor/js/aceeditor/mode-ocaml-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-ocaml-uncompressed.js @@ -537,13 +537,3 @@ var MatchingBraceOutdent = function() {}; exports.MatchingBraceOutdent = MatchingBraceOutdent; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-ocaml.js b/apps/files_texteditor/js/aceeditor/mode-ocaml.js index 0e3e15f225c..622f817e309 100644 --- a/apps/files_texteditor/js/aceeditor/mode-ocaml.js +++ b/apps/files_texteditor/js/aceeditor/mode-ocaml.js @@ -1 +1 @@ -define("ace/mode/ocaml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/ocaml_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./ocaml_highlight_rules").OcamlHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e);var k=/(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/;((function(){this.toggleCommentLines=function(a,b,c,d){var e,f,g=!0,h=/^\s*\(\*(.*)\*\)/;for(e=c;e<=d;e++)if(!h.test(b.getLine(e))){g=!1;break}var j=new i(0,0,0,0);for(e=c;e<=d;e++)f=b.getLine(e),j.start.row=e,j.end.row=e,j.end.column=f.length,b.replace(j,g?f.match(h)[1]:"(*"+f+"*)")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;return(!e.length||e[e.length-1].type!=="comment")&&a==="start"&&k.test(b)&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}})).call(j.prototype),b.Mode=j}),define("ace/mode/ocaml_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|for|fun|function|functor|if|in|include|inherit|initializer|lazy|let|match|method|module|mutable|new|object|of|open|or|private|rec|sig|struct|then|to|try|type|val|virtual|when|while|with".split("|")),b=e.arrayToMap("true|false".split("|")),c=e.arrayToMap("abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|add_available_units|add_big_int|add_buffer|add_channel|add_char|add_initializer|add_int_big_int|add_interfaces|add_num|add_string|add_substitute|add_substring|alarm|allocated_bytes|allow_only|allow_unsafe_modules|always|append|appname_get|appname_set|approx_num_exp|approx_num_fix|arg|argv|arith_status|array|array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|chown|chr|chroot|classify_float|clear|clear_available_units|clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|close_out|close_out_noerr|close_process|close_process|close_process_full|close_process_in|close_process_out|close_subwindow|close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|combine|combine|command|compact|compare|compare_big_int|compare_num|complex32|complex64|concat|conj|connect|contains|contains_from|contents|copy|cos|cosh|count|count|counters|create|create_alarm|create_image|create_matrix|create_matrix|create_matrix|create_object|create_object_and_run_initializers|create_object_opt|create_process|create_process|create_process_env|create_process_env|create_table|current|current_dir_name|current_point|current_x|current_y|curveto|custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|error_message|escaped|establish_server|executable_name|execv|execve|execvp|execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|float|float32|float64|float_of_big_int|float_of_bits|float_of_int|float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|for_all|for_all2|force|force_newline|force_val|foreground|fork|format_of_string|formatter_of_buffer|formatter_of_out_channel|fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|genarray_of_array1|genarray_of_array2|genarray_of_array3|get|get_all_formatter_output_functions|get_approx_printing|get_copy|get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|get_formatter_output_functions|get_formatter_tag_functions|get_image|get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|global_replace|global_substitute|gmtime|green|grid|group_beginning|group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|marshal|match_beginning|match_end|matched_group|matched_string|max|max_array_length|max_big_int|max_elt|max_float|max_int|max_num|max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|output_char|output_string|output_value|over_max_boxes|pack|params|parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|power_big_int_positive_big_int|power_big_int_positive_int|power_int_positive_big_int|power_int_positive_int|power_num|pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|pp_get_all_formatter_output_functions|pp_get_ellipsis_text|pp_get_formatter_output_functions|pp_get_formatter_tag_functions|pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|pp_set_all_formatter_output_functions|pp_set_ellipsis_text|pp_set_formatter_out_channel|pp_set_formatter_output_functions|pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|print_bool|print_break|print_char|print_cut|print_endline|print_float|print_flush|print_if_newline|print_int|print_newline|print_space|print_stat|print_string|print_tab|print_tbreak|printf|prohibit|public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|regexp_string_case_fold|register|register_exception|rem|remember_mode|remove|remove_assoc|remove_assq|rename|replace|replace_first|replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|run_initializers|run_initializers_opt|scanf|search_backward|search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|set_all_formatter_output_functions|set_approx_printing|set_binary_mode_in|set_binary_mode_out|set_close_on_exec|set_close_on_exec|set_color|set_ellipsis_text|set_error_when_null_denominator|set_field|set_floating_precision|set_font|set_formatter_out_channel|set_formatter_output_functions|set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|str_formatter|string|string_after|string_before|string_match|string_of_big_int|string_of_bool|string_of_float|string_of_format|string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|sub_right|subset|subset|substitute_first|substring|succ|succ|succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|temp_file|text_size|time|time|time|timed_read|timed_write|times|times|tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|wait_timed_read|wait_timed_write|wait_write|waitpid|white|widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak".split("|")),d="(?:(?:[1-9]\\d*)|(?:0))",f="(?:0[oO]?[0-7]+)",g="(?:0[xX][\\dA-Fa-f]+)",h="(?:0[bB][01]+)",i="(?:"+d+"|"+f+"|"+g+"|"+h+")",j="(?:[eE][+-]?\\d+)",k="(?:\\.\\d+)",l="(?:\\d+)",m="(?:(?:"+l+"?"+k+")|(?:"+l+"\\.))",n="(?:(?:"+m+"|"+l+")"+j+")",o="(?:"+n+"|"+m+")";this.$rules={start:[{token:"comment",regex:"\\(\\*.*?\\*\\)\\s*?$"},{token:"comment",merge:!0,regex:"\\(\\*.*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"'.'"},{token:"string",merge:!0,regex:'"',next:"qstring"},{token:"constant.numeric",regex:"(?:"+o+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:o},{token:"constant.numeric",regex:i+"\\b"},{token:function(d){return a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+\\.|\\-\\.|\\*\\.|\\/\\.|#|;;|\\+|\\-|\\*|\\*\\*\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|<-|="},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\)",next:"start"},{token:"comment",merge:!0,regex:".+"}],qstring:[{token:"string",regex:'"',next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.OcamlHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/ocaml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/ocaml_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./ocaml_highlight_rules").OcamlHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e);var k=/(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/;(function(){this.toggleCommentLines=function(a,b,c,d){var e,f,g=!0,h=/^\s*\(\*(.*)\*\)/;for(e=c;e<=d;e++)if(!h.test(b.getLine(e))){g=!1;break}var j=new i(0,0,0,0);for(e=c;e<=d;e++)f=b.getLine(e),j.start.row=e,j.end.row=e,j.end.column=f.length,b.replace(j,g?f.match(h)[1]:"(*"+f+"*)")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;return(!e.length||e[e.length-1].type!=="comment")&&a==="start"&&k.test(b)&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}).call(j.prototype),b.Mode=j}),define("ace/mode/ocaml_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|for|fun|function|functor|if|in|include|inherit|initializer|lazy|let|match|method|module|mutable|new|object|of|open|or|private|rec|sig|struct|then|to|try|type|val|virtual|when|while|with".split("|")),b=e.arrayToMap("true|false".split("|")),c=e.arrayToMap("abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|add_available_units|add_big_int|add_buffer|add_channel|add_char|add_initializer|add_int_big_int|add_interfaces|add_num|add_string|add_substitute|add_substring|alarm|allocated_bytes|allow_only|allow_unsafe_modules|always|append|appname_get|appname_set|approx_num_exp|approx_num_fix|arg|argv|arith_status|array|array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|chown|chr|chroot|classify_float|clear|clear_available_units|clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|close_out|close_out_noerr|close_process|close_process|close_process_full|close_process_in|close_process_out|close_subwindow|close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|combine|combine|command|compact|compare|compare_big_int|compare_num|complex32|complex64|concat|conj|connect|contains|contains_from|contents|copy|cos|cosh|count|count|counters|create|create_alarm|create_image|create_matrix|create_matrix|create_matrix|create_object|create_object_and_run_initializers|create_object_opt|create_process|create_process|create_process_env|create_process_env|create_table|current|current_dir_name|current_point|current_x|current_y|curveto|custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|error_message|escaped|establish_server|executable_name|execv|execve|execvp|execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|float|float32|float64|float_of_big_int|float_of_bits|float_of_int|float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|for_all|for_all2|force|force_newline|force_val|foreground|fork|format_of_string|formatter_of_buffer|formatter_of_out_channel|fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|genarray_of_array1|genarray_of_array2|genarray_of_array3|get|get_all_formatter_output_functions|get_approx_printing|get_copy|get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|get_formatter_output_functions|get_formatter_tag_functions|get_image|get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|global_replace|global_substitute|gmtime|green|grid|group_beginning|group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|marshal|match_beginning|match_end|matched_group|matched_string|max|max_array_length|max_big_int|max_elt|max_float|max_int|max_num|max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|output_char|output_string|output_value|over_max_boxes|pack|params|parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|power_big_int_positive_big_int|power_big_int_positive_int|power_int_positive_big_int|power_int_positive_int|power_num|pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|pp_get_all_formatter_output_functions|pp_get_ellipsis_text|pp_get_formatter_output_functions|pp_get_formatter_tag_functions|pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|pp_set_all_formatter_output_functions|pp_set_ellipsis_text|pp_set_formatter_out_channel|pp_set_formatter_output_functions|pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|print_bool|print_break|print_char|print_cut|print_endline|print_float|print_flush|print_if_newline|print_int|print_newline|print_space|print_stat|print_string|print_tab|print_tbreak|printf|prohibit|public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|regexp_string_case_fold|register|register_exception|rem|remember_mode|remove|remove_assoc|remove_assq|rename|replace|replace_first|replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|run_initializers|run_initializers_opt|scanf|search_backward|search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|set_all_formatter_output_functions|set_approx_printing|set_binary_mode_in|set_binary_mode_out|set_close_on_exec|set_close_on_exec|set_color|set_ellipsis_text|set_error_when_null_denominator|set_field|set_floating_precision|set_font|set_formatter_out_channel|set_formatter_output_functions|set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|str_formatter|string|string_after|string_before|string_match|string_of_big_int|string_of_bool|string_of_float|string_of_format|string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|sub_right|subset|subset|substitute_first|substring|succ|succ|succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|temp_file|text_size|time|time|time|timed_read|timed_write|times|times|tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|wait_timed_read|wait_timed_write|wait_write|waitpid|white|widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak".split("|")),d="(?:(?:[1-9]\\d*)|(?:0))",f="(?:0[oO]?[0-7]+)",g="(?:0[xX][\\dA-Fa-f]+)",h="(?:0[bB][01]+)",i="(?:"+d+"|"+f+"|"+g+"|"+h+")",j="(?:[eE][+-]?\\d+)",k="(?:\\.\\d+)",l="(?:\\d+)",m="(?:(?:"+l+"?"+k+")|(?:"+l+"\\.))",n="(?:(?:"+m+"|"+l+")"+j+")",o="(?:"+n+"|"+m+")";this.$rules={start:[{token:"comment",regex:"\\(\\*.*?\\*\\)\\s*?$"},{token:"comment",merge:!0,regex:"\\(\\*.*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"'.'"},{token:"string",merge:!0,regex:'"',next:"qstring"},{token:"constant.numeric",regex:"(?:"+o+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:o},{token:"constant.numeric",regex:i+"\\b"},{token:function(d){return a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+\\.|\\-\\.|\\*\\.|\\/\\.|#|;;|\\+|\\-|\\*|\\*\\*\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|<-|="},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\)",next:"start"},{token:"comment",merge:!0,regex:".+"}],qstring:[{token:"string",regex:'"',next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.OcamlHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-perl-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-perl-uncompressed.js index c8bf4c47eb5..04796f61aed 100755 --- a/apps/files_texteditor/js/aceeditor/mode-perl-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-perl-uncompressed.js @@ -571,13 +571,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-perl.js b/apps/files_texteditor/js/aceeditor/mode-perl.js index 706bb9362c3..909781418b3 100644 --- a/apps/files_texteditor/js/aceeditor/mode-perl.js +++ b/apps/files_texteditor/js/aceeditor/mode-perl.js @@ -1 +1 @@ -define("ace/mode/perl",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/perl_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./perl_highlight_rules").PerlHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(k.prototype),b.Mode=k}),define("ace/mode/perl_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars".split("|")),b=e.arrayToMap("ARGV|ENV|INC|SIG".split("|")),c=e.arrayToMap("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|getpeername|setpriority|getprotoent|setprotoent|getpriority|endprotoent|getservent|setservent|endservent|sethostent|socketpair|getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|map|die|uc|lc|do".split("|"));this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",merge:!0,regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",merge:!0,regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0x[0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(d){return a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PerlHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/perl",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/perl_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./perl_highlight_rules").PerlHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.foldingRules=new j};d.inherits(k,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(k.prototype),b.Mode=k}),define("ace/mode/perl_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars".split("|")),b=e.arrayToMap("ARGV|ENV|INC|SIG".split("|")),c=e.arrayToMap("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|getpeername|setpriority|getprotoent|setprotoent|getpriority|endprotoent|getservent|setservent|endservent|sethostent|socketpair|getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|map|die|uc|lc|do".split("|"));this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",merge:!0,regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",merge:!0,regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0x[0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(d){return a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PerlHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-pgsql-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-pgsql-uncompressed.js new file mode 100755 index 00000000000..344647c792f --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-pgsql-uncompressed.js @@ -0,0 +1,1107 @@ +/* ***** BEGIN LICENSE BLOCK ***** +* The Original Code is Ajax.org Code Editor (ACE). +* +* Contributor(s): +* Jonathan Camile +* +* Alternatively, the contents of this file may be used under the terms of +* either the GNU General Public License Version 2 or later (the "GPL"), or +* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +* in which case the provisions of the GPL or the LGPL are applicable instead +* of those above. If you wish to allow use of your version of this file only +* under the terms of either the GPL or the LGPL, and not to allow others to +* use your version of this file under the terms of the MPL, indicate your +* decision by deleting the provisions above and replace them with the notice +* and other provisions required by the GPL or the LGPL. If you do not delete +* the provisions above, a recipient may use your version of this file under +* the terms of any one of the MPL, the GPL or the LGPL. +* +* ***** END LICENSE BLOCK ***** */ + +define('ace/mode/pgsql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/pgsql_highlight_rules', 'ace/range'], function(require, exports, module) { + + var oop = require("ace/lib/oop"); + var TextMode = require("ace/mode/text").Mode; + var Tokenizer = require("ace/tokenizer").Tokenizer; + var PgsqlHighlightRules = require("ace/mode/pgsql_highlight_rules").PgsqlHighlightRules; + var Range = require("ace/range").Range; + // var EditSession = require("ace/edit_session").EditSession; + + var Mode = function() { + this.$tokenizer = new Tokenizer(new PgsqlHighlightRules().getRules()); + }; + oop.inherits(Mode, TextMode); + + (function() { + + this.toggleCommentLines = function(state, doc, startRow, endRow) { + var outdent = true; + // var outentedRows = []; + var re = /^(\s*)--/; + + for (var i=startRow; i<= endRow; i++) { + if (!re.test(doc.getLine(i))) { + outdent = false; + break; + } + } + + if (outdent) { + var deleteRange = new Range(0, 0, 0, 0); + for (var i=startRow; i<= endRow; i++) + { + var line = doc.getLine(i); + var m = line.match(re); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = m[0].length; + doc.replace(deleteRange, m[1]); + } + } + else { + doc.indentRows(startRow, endRow, "--"); + } + }; + + + this.getNextLineIndent = function(state, line, tab) { + if (state == "start" || state == "keyword.statementEnd") { + return ""; + } else { + return this.$getIndent(line); // Keep whatever indent the previous line has + } + } + + }).call(Mode.prototype); + + exports.Mode = Mode; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * The Original Code is Ajax.org Code Editor (ACE). + * + * Contributor(s): + * John DeSoi, Ph.D. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** + * + */ + + +define('ace/mode/pgsql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/perl_highlight_rules', 'ace/mode/python_highlight_rules'], function(require, exports, module) { + +var oop = require("ace/lib/oop"); +var lang = require("ace/lib/lang"); +var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; +// Supporting perl and python for now -- both in pg core and ace +var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules; +var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; + +var PgsqlHighlightRules = function() { + + // Keywords, functions, operators last updated for pg 9.1. + var keywords = lang.arrayToMap( + ("abort|absolute|abstime|access|aclitem|action|add|admin|after|aggregate|all|also|alter|always|" + + "analyse|analyze|and|any|anyarray|anyelement|anyenum|anynonarray|array|as|asc|assertion|" + + "assignment|asymmetric|at|attribute|authorization|backward|before|begin|between|bigint|" + + "binary|bit|bool|boolean|both|box|bpchar|by|bytea|cache|called|cascade|cascaded|case|cast|" + + "catalog|chain|char|character|characteristics|check|checkpoint|cid|cidr|circle|class|close|" + + "cluster|coalesce|collate|collation|column|comment|comments|commit|committed|concurrently|" + + "configuration|connection|constraint|constraints|content|continue|conversion|copy|cost|" + + "create|cross|cstring|csv|current|current_catalog|current_date|current_role|" + + "current_schema|current_time|current_timestamp|current_user|cursor|cycle|data|database|" + + "date|day|deallocate|dec|decimal|declare|default|defaults|deferrable|deferred|definer|delete|" + + "delimiter|delimiters|desc|dictionary|disable|discard|distinct|do|document|domain|double|" + + "drop|each|else|enable|encoding|encrypted|end|enum|escape|except|exclude|excluding|exclusive|" + + "execute|exists|explain|extension|external|extract|false|family|fdw_handler|fetch|first|" + + "float|float4|float8|following|for|force|foreign|forward|freeze|from|full|function|functions|" + + "global|grant|granted|greatest|group|gtsvector|handler|having|header|hold|hour|identity|if|" + + "ilike|immediate|immutable|implicit|in|including|increment|index|indexes|inet|inherit|" + + "inherits|initially|inline|inner|inout|input|insensitive|insert|instead|int|int2|int2vector|" + + "int4|int8|integer|internal|intersect|interval|into|invoker|is|isnull|isolation|join|key|label|" + + "language|language_handler|large|last|lc_collate|lc_ctype|leading|least|left|level|like|" + + "limit|line|listen|load|local|localtime|localtimestamp|location|lock|lseg|macaddr|mapping|" + + "match|maxvalue|minute|minvalue|mode|money|month|move|name|names|national|natural|nchar|next|no|" + + "none|not|nothing|notify|notnull|nowait|null|nullif|nulls|numeric|object|of|off|offset|oid|oids|" + + "oidvector|on|only|opaque|operator|option|options|or|order|out|outer|over|overlaps|overlay|" + + "owned|owner|parser|partial|partition|passing|password|path|pg_attribute|pg_auth_members|" + + "pg_authid|pg_class|pg_database|pg_node_tree|pg_proc|pg_type|placing|plans|point|polygon|" + + "position|preceding|precision|prepare|prepared|preserve|primary|prior|privileges|" + + "procedural|procedure|quote|range|read|real|reassign|recheck|record|recursive|ref|refcursor|" + + "references|regclass|regconfig|regdictionary|regoper|regoperator|regproc|regprocedure|" + + "regtype|reindex|relative|release|reltime|rename|repeatable|replace|replica|reset|restart|" + + "restrict|returning|returns|revoke|right|role|rollback|row|rows|rule|savepoint|schema|scroll|" + + "search|second|security|select|sequence|sequences|serializable|server|session|session_user|" + + "set|setof|share|show|similar|simple|smallint|smgr|some|stable|standalone|start|statement|" + + "statistics|stdin|stdout|storage|strict|strip|substring|symmetric|sysid|system|table|tables|" + + "tablespace|temp|template|temporary|text|then|tid|time|timestamp|timestamptz|timetz|" + + "tinterval|to|trailing|transaction|treat|trigger|trim|true|truncate|trusted|tsquery|tsvector|" + + "txid_snapshot|type|unbounded|uncommitted|unencrypted|union|unique|unknown|unlisten|" + + "unlogged|until|update|user|using|uuid|vacuum|valid|validate|validator|value|values|varbit|" + + "varchar|variadic|varying|verbose|version|view|void|volatile|when|where|whitespace|window|" + + "with|without|work|wrapper|write|xid|xml|xmlattributes|xmlconcat|xmlelement|xmlexists|" + + "xmlforest|xmlparse|xmlpi|xmlroot|xmlserialize|year|yes|zone").split("|") + ); + + + var builtinFunctions = lang.arrayToMap( + ("RI_FKey_cascade_del|RI_FKey_cascade_upd|RI_FKey_check_ins|RI_FKey_check_upd|" + + "RI_FKey_noaction_del|RI_FKey_noaction_upd|RI_FKey_restrict_del|RI_FKey_restrict_upd|" + + "RI_FKey_setdefault_del|RI_FKey_setdefault_upd|RI_FKey_setnull_del|" + + "RI_FKey_setnull_upd|abbrev|abs|abstime|abstimeeq|abstimege|abstimegt|abstimein|abstimele|" + + "abstimelt|abstimene|abstimeout|abstimerecv|abstimesend|aclcontains|aclexplode|aclinsert|" + + "aclitemeq|aclitemin|aclitemout|aclremove|acos|age|any_in|any_out|anyarray_in|anyarray_out|" + + "anyarray_recv|anyarray_send|anyelement_in|anyelement_out|anyenum_in|anyenum_out|" + + "anynonarray_in|anynonarray_out|anytextcat|area|areajoinsel|areasel|array_agg|" + + "array_agg_finalfn|array_agg_transfn|array_append|array_cat|array_dims|array_eq|" + + "array_fill|array_ge|array_gt|array_in|array_larger|array_le|array_length|array_lower|" + + "array_lt|array_ndims|array_ne|array_out|array_prepend|array_recv|array_send|" + + "array_smaller|array_to_string|array_upper|arraycontained|arraycontains|arrayoverlap|" + + "ascii|ascii_to_mic|ascii_to_utf8|asin|atan|atan2|avg|big5_to_euc_tw|big5_to_mic|" + + "big5_to_utf8|bit_and|bit_in|bit_length|bit_or|bit_out|bit_recv|bit_send|bitand|bitcat|" + + "bitcmp|biteq|bitge|bitgt|bitle|bitlt|bitne|bitnot|bitor|bitshiftleft|bitshiftright|" + + "bittypmodin|bittypmodout|bitxor|bool|bool_and|bool_or|booland_statefunc|booleq|boolge|" + + "boolgt|boolin|boolle|boollt|boolne|boolor_statefunc|boolout|boolrecv|boolsend|box|" + + "box_above|box_above_eq|box_add|box_below|box_below_eq|box_center|box_contain|" + + "box_contain_pt|box_contained|box_distance|box_div|box_eq|box_ge|box_gt|box_in|" + + "box_intersect|box_le|box_left|box_lt|box_mul|box_out|box_overabove|box_overbelow|" + + "box_overlap|box_overleft|box_overright|box_recv|box_right|box_same|box_send|box_sub|" + + "bpchar_larger|bpchar_pattern_ge|bpchar_pattern_gt|bpchar_pattern_le|" + + "bpchar_pattern_lt|bpchar_smaller|bpcharcmp|bpchareq|bpcharge|bpchargt|bpchariclike|" + + "bpcharicnlike|bpcharicregexeq|bpcharicregexne|bpcharin|bpcharle|bpcharlike|bpcharlt|" + + "bpcharne|bpcharnlike|bpcharout|bpcharrecv|bpcharregexeq|bpcharregexne|bpcharsend|" + + "bpchartypmodin|bpchartypmodout|broadcast|btabstimecmp|btarraycmp|btbeginscan|btboolcmp|" + + "btbpchar_pattern_cmp|btbuild|btbuildempty|btbulkdelete|btcharcmp|btcostestimate|" + + "btendscan|btfloat48cmp|btfloat4cmp|btfloat84cmp|btfloat8cmp|btgetbitmap|btgettuple|" + + "btinsert|btint24cmp|btint28cmp|btint2cmp|btint42cmp|btint48cmp|btint4cmp|btint82cmp|" + + "btint84cmp|btint8cmp|btmarkpos|btnamecmp|btoidcmp|btoidvectorcmp|btoptions|btrecordcmp|" + + "btreltimecmp|btrescan|btrestrpos|btrim|bttext_pattern_cmp|bttextcmp|bttidcmp|" + + "bttintervalcmp|btvacuumcleanup|byteacat|byteacmp|byteaeq|byteage|byteagt|byteain|byteale|" + + "bytealike|bytealt|byteane|byteanlike|byteaout|bytearecv|byteasend|cash_cmp|cash_div_cash|" + + "cash_div_flt4|cash_div_flt8|cash_div_int2|cash_div_int4|cash_eq|cash_ge|cash_gt|cash_in|" + + "cash_le|cash_lt|cash_mi|cash_mul_flt4|cash_mul_flt8|cash_mul_int2|cash_mul_int4|cash_ne|" + + "cash_out|cash_pl|cash_recv|cash_send|cash_words|cashlarger|cashsmaller|cbrt|ceil|ceiling|" + + "center|char|char_length|character_length|chareq|charge|chargt|charin|charle|charlt|charne|" + + "charout|charrecv|charsend|chr|cideq|cidin|cidout|cidr|cidr_in|cidr_out|cidr_recv|cidr_send|" + + "cidrecv|cidsend|circle|circle_above|circle_add_pt|circle_below|circle_center|" + + "circle_contain|circle_contain_pt|circle_contained|circle_distance|circle_div_pt|" + + "circle_eq|circle_ge|circle_gt|circle_in|circle_le|circle_left|circle_lt|circle_mul_pt|" + + "circle_ne|circle_out|circle_overabove|circle_overbelow|circle_overlap|circle_overleft|" + + "circle_overright|circle_recv|circle_right|circle_same|circle_send|circle_sub_pt|" + + "clock_timestamp|close_lb|close_ls|close_lseg|close_pb|close_pl|close_ps|close_sb|" + + "close_sl|col_description|concat|concat_ws|contjoinsel|contsel|convert|convert_from|" + + "convert_to|corr|cos|cot|count|covar_pop|covar_samp|cstring_in|cstring_out|cstring_recv|" + + "cstring_send|cume_dist|current_database|current_query|current_schema|current_schemas|" + + "current_setting|current_user|currtid|currtid2|currval|cursor_to_xml|" + + "cursor_to_xmlschema|database_to_xml|database_to_xml_and_xmlschema|" + + "database_to_xmlschema|date|date_cmp|date_cmp_timestamp|date_cmp_timestamptz|date_eq|" + + "date_eq_timestamp|date_eq_timestamptz|date_ge|date_ge_timestamp|date_ge_timestamptz|" + + "date_gt|date_gt_timestamp|date_gt_timestamptz|date_in|date_larger|date_le|" + + "date_le_timestamp|date_le_timestamptz|date_lt|date_lt_timestamp|date_lt_timestamptz|" + + "date_mi|date_mi_interval|date_mii|date_ne|date_ne_timestamp|date_ne_timestamptz|" + + "date_out|date_part|date_pl_interval|date_pli|date_recv|date_send|date_smaller|" + + "date_trunc|datetime_pl|datetimetz_pl|dcbrt|decode|degrees|dense_rank|dexp|diagonal|" + + "diameter|dispell_init|dispell_lexize|dist_cpoly|dist_lb|dist_pb|dist_pc|dist_pl|" + + "dist_ppath|dist_ps|dist_sb|dist_sl|div|dlog1|dlog10|domain_in|domain_recv|dpow|dround|" + + "dsimple_init|dsimple_lexize|dsnowball_init|dsnowball_lexize|dsqrt|dsynonym_init|" + + "dsynonym_lexize|dtrunc|encode|enum_cmp|enum_eq|enum_first|enum_ge|enum_gt|enum_in|" + + "enum_larger|enum_last|enum_le|enum_lt|enum_ne|enum_out|enum_range|enum_recv|enum_send|" + + "enum_smaller|eqjoinsel|eqsel|euc_cn_to_mic|euc_cn_to_utf8|" + + "euc_jis_2004_to_shift_jis_2004|euc_jis_2004_to_utf8|euc_jp_to_mic|euc_jp_to_sjis|" + + "euc_jp_to_utf8|euc_kr_to_mic|euc_kr_to_utf8|euc_tw_to_big5|euc_tw_to_mic|" + + "euc_tw_to_utf8|every|exp|factorial|family|fdw_handler_in|fdw_handler_out|first_value|" + + "float4|float48div|float48eq|float48ge|float48gt|float48le|float48lt|float48mi|float48mul|" + + "float48ne|float48pl|float4_accum|float4abs|float4div|float4eq|float4ge|float4gt|float4in|" + + "float4larger|float4le|float4lt|float4mi|float4mul|float4ne|float4out|float4pl|float4recv|" + + "float4send|float4smaller|float4um|float4up|float8|float84div|float84eq|float84ge|" + + "float84gt|float84le|float84lt|float84mi|float84mul|float84ne|float84pl|float8_accum|" + + "float8_avg|float8_corr|float8_covar_pop|float8_covar_samp|float8_regr_accum|" + + "float8_regr_avgx|float8_regr_avgy|float8_regr_intercept|float8_regr_r2|" + + "float8_regr_slope|float8_regr_sxx|float8_regr_sxy|float8_regr_syy|float8_stddev_pop|" + + "float8_stddev_samp|float8_var_pop|float8_var_samp|float8abs|float8div|float8eq|" + + "float8ge|float8gt|float8in|float8larger|float8le|float8lt|float8mi|float8mul|float8ne|" + + "float8out|float8pl|float8recv|float8send|float8smaller|float8um|float8up|floor|" + + "flt4_mul_cash|flt8_mul_cash|fmgr_c_validator|fmgr_internal_validator|" + + "fmgr_sql_validator|format|format_type|gb18030_to_utf8|gbk_to_utf8|generate_series|" + + "generate_subscripts|get_bit|get_byte|get_current_ts_config|getdatabaseencoding|" + + "getpgusername|gin_cmp_prefix|gin_cmp_tslexeme|gin_extract_tsquery|" + + "gin_extract_tsvector|gin_tsquery_consistent|ginarrayconsistent|ginarrayextract|" + + "ginbeginscan|ginbuild|ginbuildempty|ginbulkdelete|gincostestimate|ginendscan|" + + "gingetbitmap|gininsert|ginmarkpos|ginoptions|ginqueryarrayextract|ginrescan|" + + "ginrestrpos|ginvacuumcleanup|gist_box_compress|gist_box_consistent|" + + "gist_box_decompress|gist_box_penalty|gist_box_picksplit|gist_box_same|gist_box_union|" + + "gist_circle_compress|gist_circle_consistent|gist_point_compress|" + + "gist_point_consistent|gist_point_distance|gist_poly_compress|gist_poly_consistent|" + + "gistbeginscan|gistbuild|gistbuildempty|gistbulkdelete|gistcostestimate|gistendscan|" + + "gistgetbitmap|gistgettuple|gistinsert|gistmarkpos|gistoptions|gistrescan|gistrestrpos|" + + "gistvacuumcleanup|gtsquery_compress|gtsquery_consistent|gtsquery_decompress|" + + "gtsquery_penalty|gtsquery_picksplit|gtsquery_same|gtsquery_union|gtsvector_compress|" + + "gtsvector_consistent|gtsvector_decompress|gtsvector_penalty|gtsvector_picksplit|" + + "gtsvector_same|gtsvector_union|gtsvectorin|gtsvectorout|has_any_column_privilege|" + + "has_column_privilege|has_database_privilege|has_foreign_data_wrapper_privilege|" + + "has_function_privilege|has_language_privilege|has_schema_privilege|" + + "has_sequence_privilege|has_server_privilege|has_table_privilege|" + + "has_tablespace_privilege|hash_aclitem|hash_array|hash_numeric|hashbeginscan|" + + "hashbpchar|hashbuild|hashbuildempty|hashbulkdelete|hashchar|hashcostestimate|" + + "hashendscan|hashenum|hashfloat4|hashfloat8|hashgetbitmap|hashgettuple|hashinet|" + + "hashinsert|hashint2|hashint2vector|hashint4|hashint8|hashmacaddr|hashmarkpos|hashname|" + + "hashoid|hashoidvector|hashoptions|hashrescan|hashrestrpos|hashtext|hashvacuumcleanup|" + + "hashvarlena|height|host|hostmask|iclikejoinsel|iclikesel|icnlikejoinsel|icnlikesel|" + + "icregexeqjoinsel|icregexeqsel|icregexnejoinsel|icregexnesel|inet_client_addr|" + + "inet_client_port|inet_in|inet_out|inet_recv|inet_send|inet_server_addr|" + + "inet_server_port|inetand|inetmi|inetmi_int8|inetnot|inetor|inetpl|initcap|int2|int24div|" + + "int24eq|int24ge|int24gt|int24le|int24lt|int24mi|int24mul|int24ne|int24pl|int28div|int28eq|" + + "int28ge|int28gt|int28le|int28lt|int28mi|int28mul|int28ne|int28pl|int2_accum|" + + "int2_avg_accum|int2_mul_cash|int2_sum|int2abs|int2and|int2div|int2eq|int2ge|int2gt|int2in|" + + "int2larger|int2le|int2lt|int2mi|int2mod|int2mul|int2ne|int2not|int2or|int2out|int2pl|" + + "int2recv|int2send|int2shl|int2shr|int2smaller|int2um|int2up|int2vectoreq|int2vectorin|" + + "int2vectorout|int2vectorrecv|int2vectorsend|int2xor|int4|int42div|int42eq|int42ge|" + + "int42gt|int42le|int42lt|int42mi|int42mul|int42ne|int42pl|int48div|int48eq|int48ge|int48gt|" + + "int48le|int48lt|int48mi|int48mul|int48ne|int48pl|int4_accum|int4_avg_accum|int4_mul_cash|" + + "int4_sum|int4abs|int4and|int4div|int4eq|int4ge|int4gt|int4in|int4inc|int4larger|int4le|" + + "int4lt|int4mi|int4mod|int4mul|int4ne|int4not|int4or|int4out|int4pl|int4recv|int4send|" + + "int4shl|int4shr|int4smaller|int4um|int4up|int4xor|int8|int82div|int82eq|int82ge|int82gt|" + + "int82le|int82lt|int82mi|int82mul|int82ne|int82pl|int84div|int84eq|int84ge|int84gt|int84le|" + + "int84lt|int84mi|int84mul|int84ne|int84pl|int8_accum|int8_avg|int8_avg_accum|int8_sum|" + + "int8abs|int8and|int8div|int8eq|int8ge|int8gt|int8in|int8inc|int8inc_any|" + + "int8inc_float8_float8|int8larger|int8le|int8lt|int8mi|int8mod|int8mul|int8ne|int8not|" + + "int8or|int8out|int8pl|int8pl_inet|int8recv|int8send|int8shl|int8shr|int8smaller|int8um|" + + "int8up|int8xor|integer_pl_date|inter_lb|inter_sb|inter_sl|internal_in|internal_out|" + + "interval_accum|interval_avg|interval_cmp|interval_div|interval_eq|interval_ge|" + + "interval_gt|interval_hash|interval_in|interval_larger|interval_le|interval_lt|" + + "interval_mi|interval_mul|interval_ne|interval_out|interval_pl|interval_pl_date|" + + "interval_pl_time|interval_pl_timestamp|interval_pl_timestamptz|interval_pl_timetz|" + + "interval_recv|interval_send|interval_smaller|interval_um|intervaltypmodin|" + + "intervaltypmodout|intinterval|isclosed|isfinite|ishorizontal|iso8859_1_to_utf8|" + + "iso8859_to_utf8|iso_to_koi8r|iso_to_mic|iso_to_win1251|iso_to_win866|isopen|isparallel|" + + "isperp|isvertical|johab_to_utf8|justify_days|justify_hours|justify_interval|" + + "koi8r_to_iso|koi8r_to_mic|koi8r_to_utf8|koi8r_to_win1251|koi8r_to_win866|" + + "koi8u_to_utf8|lag|language_handler_in|language_handler_out|last_value|lastval|" + + "latin1_to_mic|latin2_to_mic|latin2_to_win1250|latin3_to_mic|latin4_to_mic|lead|left|" + + "length|like|like_escape|likejoinsel|likesel|line|line_distance|line_eq|line_horizontal|" + + "line_in|line_interpt|line_intersect|line_out|line_parallel|line_perp|line_recv|" + + "line_send|line_vertical|ln|lo_close|lo_creat|lo_create|lo_export|lo_import|lo_lseek|" + + "lo_open|lo_tell|lo_truncate|lo_unlink|log|loread|lower|lowrite|lpad|lseg|lseg_center|" + + "lseg_distance|lseg_eq|lseg_ge|lseg_gt|lseg_horizontal|lseg_in|lseg_interpt|" + + "lseg_intersect|lseg_le|lseg_length|lseg_lt|lseg_ne|lseg_out|lseg_parallel|lseg_perp|" + + "lseg_recv|lseg_send|lseg_vertical|ltrim|macaddr_cmp|macaddr_eq|macaddr_ge|macaddr_gt|" + + "macaddr_in|macaddr_le|macaddr_lt|macaddr_ne|macaddr_out|macaddr_recv|macaddr_send|" + + "makeaclitem|masklen|max|md5|mic_to_ascii|mic_to_big5|mic_to_euc_cn|mic_to_euc_jp|" + + "mic_to_euc_kr|mic_to_euc_tw|mic_to_iso|mic_to_koi8r|mic_to_latin1|mic_to_latin2|" + + "mic_to_latin3|mic_to_latin4|mic_to_sjis|mic_to_win1250|mic_to_win1251|mic_to_win866|" + + "min|mktinterval|mod|money|mul_d_interval|name|nameeq|namege|namegt|nameiclike|nameicnlike|" + + "nameicregexeq|nameicregexne|namein|namele|namelike|namelt|namene|namenlike|nameout|" + + "namerecv|nameregexeq|nameregexne|namesend|neqjoinsel|neqsel|netmask|network|network_cmp|" + + "network_eq|network_ge|network_gt|network_le|network_lt|network_ne|network_sub|" + + "network_subeq|network_sup|network_supeq|nextval|nlikejoinsel|nlikesel|notlike|now|" + + "npoints|nth_value|ntile|numeric_abs|numeric_accum|numeric_add|numeric_avg|" + + "numeric_avg_accum|numeric_cmp|numeric_div|numeric_div_trunc|numeric_eq|numeric_exp|" + + "numeric_fac|numeric_ge|numeric_gt|numeric_in|numeric_inc|numeric_larger|numeric_le|" + + "numeric_ln|numeric_log|numeric_lt|numeric_mod|numeric_mul|numeric_ne|numeric_out|" + + "numeric_power|numeric_recv|numeric_send|numeric_smaller|numeric_sqrt|" + + "numeric_stddev_pop|numeric_stddev_samp|numeric_sub|numeric_uminus|numeric_uplus|" + + "numeric_var_pop|numeric_var_samp|numerictypmodin|numerictypmodout|numnode|" + + "obj_description|octet_length|oid|oideq|oidge|oidgt|oidin|oidlarger|oidle|oidlt|oidne|oidout|" + + "oidrecv|oidsend|oidsmaller|oidvectoreq|oidvectorge|oidvectorgt|oidvectorin|oidvectorle|" + + "oidvectorlt|oidvectorne|oidvectorout|oidvectorrecv|oidvectorsend|oidvectortypes|on_pb|" + + "on_pl|on_ppath|on_ps|on_sb|on_sl|opaque_in|opaque_out|overlaps|overlay|path|path_add|" + + "path_add_pt|path_center|path_contain_pt|path_distance|path_div_pt|path_in|path_inter|" + + "path_length|path_mul_pt|path_n_eq|path_n_ge|path_n_gt|path_n_le|path_n_lt|path_npoints|" + + "path_out|path_recv|path_send|path_sub_pt|pclose|percent_rank|pg_advisory_lock|" + + "pg_advisory_lock_shared|pg_advisory_unlock|pg_advisory_unlock_all|" + + "pg_advisory_unlock_shared|pg_advisory_xact_lock|pg_advisory_xact_lock_shared|" + + "pg_available_extension_versions|pg_available_extensions|pg_backend_pid|" + + "pg_cancel_backend|pg_char_to_encoding|pg_client_encoding|pg_collation_is_visible|" + + "pg_column_size|pg_conf_load_time|pg_conversion_is_visible|pg_create_restore_point|" + + "pg_current_xlog_insert_location|pg_current_xlog_location|pg_cursor|pg_database_size|" + + "pg_describe_object|pg_encoding_max_length|pg_encoding_to_char|" + + "pg_extension_config_dump|pg_extension_update_paths|pg_function_is_visible|" + + "pg_get_constraintdef|pg_get_expr|pg_get_function_arguments|" + + "pg_get_function_identity_arguments|pg_get_function_result|pg_get_functiondef|" + + "pg_get_indexdef|pg_get_keywords|pg_get_ruledef|pg_get_serial_sequence|" + + "pg_get_triggerdef|pg_get_userbyid|pg_get_viewdef|pg_has_role|pg_indexes_size|" + + "pg_is_in_recovery|pg_is_other_temp_schema|pg_is_xlog_replay_paused|" + + "pg_last_xact_replay_timestamp|pg_last_xlog_receive_location|" + + "pg_last_xlog_replay_location|pg_listening_channels|pg_lock_status|pg_ls_dir|" + + "pg_my_temp_schema|pg_node_tree_in|pg_node_tree_out|pg_node_tree_recv|" + + "pg_node_tree_send|pg_notify|pg_opclass_is_visible|pg_operator_is_visible|" + + "pg_options_to_table|pg_postmaster_start_time|pg_prepared_statement|pg_prepared_xact|" + + "pg_read_binary_file|pg_read_file|pg_relation_filenode|pg_relation_filepath|" + + "pg_relation_size|pg_reload_conf|pg_rotate_logfile|pg_sequence_parameters|" + + "pg_show_all_settings|pg_size_pretty|pg_sleep|pg_start_backup|pg_stat_clear_snapshot|" + + "pg_stat_file|pg_stat_get_activity|pg_stat_get_analyze_count|" + + "pg_stat_get_autoanalyze_count|pg_stat_get_autovacuum_count|" + + "pg_stat_get_backend_activity|pg_stat_get_backend_activity_start|" + + "pg_stat_get_backend_client_addr|pg_stat_get_backend_client_port|" + + "pg_stat_get_backend_dbid|pg_stat_get_backend_idset|pg_stat_get_backend_pid|" + + "pg_stat_get_backend_start|pg_stat_get_backend_userid|pg_stat_get_backend_waiting|" + + "pg_stat_get_backend_xact_start|pg_stat_get_bgwriter_buf_written_checkpoints|" + + "pg_stat_get_bgwriter_buf_written_clean|pg_stat_get_bgwriter_maxwritten_clean|" + + "pg_stat_get_bgwriter_requested_checkpoints|pg_stat_get_bgwriter_stat_reset_time|" + + "pg_stat_get_bgwriter_timed_checkpoints|pg_stat_get_blocks_fetched|" + + "pg_stat_get_blocks_hit|pg_stat_get_buf_alloc|pg_stat_get_buf_fsync_backend|" + + "pg_stat_get_buf_written_backend|pg_stat_get_db_blocks_fetched|" + + "pg_stat_get_db_blocks_hit|pg_stat_get_db_conflict_all|" + + "pg_stat_get_db_conflict_bufferpin|pg_stat_get_db_conflict_lock|" + + "pg_stat_get_db_conflict_snapshot|pg_stat_get_db_conflict_startup_deadlock|" + + "pg_stat_get_db_conflict_tablespace|pg_stat_get_db_numbackends|" + + "pg_stat_get_db_stat_reset_time|pg_stat_get_db_tuples_deleted|" + + "pg_stat_get_db_tuples_fetched|pg_stat_get_db_tuples_inserted|" + + "pg_stat_get_db_tuples_returned|pg_stat_get_db_tuples_updated|" + + "pg_stat_get_db_xact_commit|pg_stat_get_db_xact_rollback|pg_stat_get_dead_tuples|" + + "pg_stat_get_function_calls|pg_stat_get_function_self_time|" + + "pg_stat_get_function_time|pg_stat_get_last_analyze_time|" + + "pg_stat_get_last_autoanalyze_time|pg_stat_get_last_autovacuum_time|" + + "pg_stat_get_last_vacuum_time|pg_stat_get_live_tuples|pg_stat_get_numscans|" + + "pg_stat_get_tuples_deleted|pg_stat_get_tuples_fetched|" + + "pg_stat_get_tuples_hot_updated|pg_stat_get_tuples_inserted|" + + "pg_stat_get_tuples_returned|pg_stat_get_tuples_updated|pg_stat_get_vacuum_count|" + + "pg_stat_get_wal_senders|pg_stat_get_xact_blocks_fetched|" + + "pg_stat_get_xact_blocks_hit|pg_stat_get_xact_function_calls|" + + "pg_stat_get_xact_function_self_time|pg_stat_get_xact_function_time|" + + "pg_stat_get_xact_numscans|pg_stat_get_xact_tuples_deleted|" + + "pg_stat_get_xact_tuples_fetched|pg_stat_get_xact_tuples_hot_updated|" + + "pg_stat_get_xact_tuples_inserted|pg_stat_get_xact_tuples_returned|" + + "pg_stat_get_xact_tuples_updated|pg_stat_reset|pg_stat_reset_shared|" + + "pg_stat_reset_single_function_counters|pg_stat_reset_single_table_counters|" + + "pg_stop_backup|pg_switch_xlog|pg_table_is_visible|pg_table_size|" + + "pg_tablespace_databases|pg_tablespace_size|pg_terminate_backend|pg_timezone_abbrevs|" + + "pg_timezone_names|pg_total_relation_size|pg_try_advisory_lock|" + + "pg_try_advisory_lock_shared|pg_try_advisory_xact_lock|" + + "pg_try_advisory_xact_lock_shared|pg_ts_config_is_visible|pg_ts_dict_is_visible|" + + "pg_ts_parser_is_visible|pg_ts_template_is_visible|pg_type_is_visible|pg_typeof|" + + "pg_xlog_replay_pause|pg_xlog_replay_resume|pg_xlogfile_name|pg_xlogfile_name_offset|" + + "pi|plainto_tsquery|plpgsql_call_handler|plpgsql_inline_handler|plpgsql_validator|" + + "point|point_above|point_add|point_below|point_distance|point_div|point_eq|point_horiz|" + + "point_in|point_left|point_mul|point_ne|point_out|point_recv|point_right|point_send|" + + "point_sub|point_vert|poly_above|poly_below|poly_center|poly_contain|poly_contain_pt|" + + "poly_contained|poly_distance|poly_in|poly_left|poly_npoints|poly_out|poly_overabove|" + + "poly_overbelow|poly_overlap|poly_overleft|poly_overright|poly_recv|poly_right|" + + "poly_same|poly_send|polygon|popen|position|positionjoinsel|positionsel|" + + "postgresql_fdw_validator|pow|power|prsd_end|prsd_headline|prsd_lextype|prsd_nexttoken|" + + "prsd_start|pt_contained_circle|pt_contained_poly|query_to_xml|" + + "query_to_xml_and_xmlschema|query_to_xmlschema|querytree|quote_ident|quote_literal|" + + "quote_nullable|radians|radius|random|rank|record_eq|record_ge|record_gt|record_in|" + + "record_le|record_lt|record_ne|record_out|record_recv|record_send|regclass|regclassin|" + + "regclassout|regclassrecv|regclasssend|regconfigin|regconfigout|regconfigrecv|" + + "regconfigsend|regdictionaryin|regdictionaryout|regdictionaryrecv|regdictionarysend|" + + "regexeqjoinsel|regexeqsel|regexnejoinsel|regexnesel|regexp_matches|regexp_replace|" + + "regexp_split_to_array|regexp_split_to_table|regoperatorin|regoperatorout|" + + "regoperatorrecv|regoperatorsend|regoperin|regoperout|regoperrecv|regopersend|" + + "regprocedurein|regprocedureout|regprocedurerecv|regproceduresend|regprocin|regprocout|" + + "regprocrecv|regprocsend|regr_avgx|regr_avgy|regr_count|regr_intercept|regr_r2|" + + "regr_slope|regr_sxx|regr_sxy|regr_syy|regtypein|regtypeout|regtyperecv|regtypesend|" + + "reltime|reltimeeq|reltimege|reltimegt|reltimein|reltimele|reltimelt|reltimene|reltimeout|" + + "reltimerecv|reltimesend|repeat|replace|reverse|right|round|row_number|rpad|rtrim|" + + "scalargtjoinsel|scalargtsel|scalarltjoinsel|scalarltsel|schema_to_xml|" + + "schema_to_xml_and_xmlschema|schema_to_xmlschema|session_user|set_bit|set_byte|" + + "set_config|set_masklen|setseed|setval|setweight|shell_in|shell_out|" + + "shift_jis_2004_to_euc_jis_2004|shift_jis_2004_to_utf8|shobj_description|sign|" + + "similar_escape|sin|sjis_to_euc_jp|sjis_to_mic|sjis_to_utf8|slope|smgreq|smgrin|smgrne|" + + "smgrout|split_part|sqrt|statement_timestamp|stddev|stddev_pop|stddev_samp|string_agg|" + + "string_agg_finalfn|string_agg_transfn|string_to_array|strip|strpos|substr|substring|sum|" + + "suppress_redundant_updates_trigger|table_to_xml|table_to_xml_and_xmlschema|" + + "table_to_xmlschema|tan|text|text_ge|text_gt|text_larger|text_le|text_lt|text_pattern_ge|" + + "text_pattern_gt|text_pattern_le|text_pattern_lt|text_smaller|textanycat|textcat|texteq|" + + "texticlike|texticnlike|texticregexeq|texticregexne|textin|textlen|textlike|textne|" + + "textnlike|textout|textrecv|textregexeq|textregexne|textsend|thesaurus_init|" + + "thesaurus_lexize|tideq|tidge|tidgt|tidin|tidlarger|tidle|tidlt|tidne|tidout|tidrecv|tidsend|" + + "tidsmaller|time_cmp|time_eq|time_ge|time_gt|time_hash|time_in|time_larger|time_le|time_lt|" + + "time_mi_interval|time_mi_time|time_ne|time_out|time_pl_interval|time_recv|time_send|" + + "time_smaller|timedate_pl|timemi|timenow|timeofday|timepl|timestamp_cmp|" + + "timestamp_cmp_date|timestamp_cmp_timestamptz|timestamp_eq|timestamp_eq_date|" + + "timestamp_eq_timestamptz|timestamp_ge|timestamp_ge_date|timestamp_ge_timestamptz|" + + "timestamp_gt|timestamp_gt_date|timestamp_gt_timestamptz|timestamp_hash|timestamp_in|" + + "timestamp_larger|timestamp_le|timestamp_le_date|timestamp_le_timestamptz|" + + "timestamp_lt|timestamp_lt_date|timestamp_lt_timestamptz|timestamp_mi|" + + "timestamp_mi_interval|timestamp_ne|timestamp_ne_date|timestamp_ne_timestamptz|" + + "timestamp_out|timestamp_pl_interval|timestamp_recv|timestamp_send|timestamp_smaller|" + + "timestamptypmodin|timestamptypmodout|timestamptz_cmp|timestamptz_cmp_date|" + + "timestamptz_cmp_timestamp|timestamptz_eq|timestamptz_eq_date|" + + "timestamptz_eq_timestamp|timestamptz_ge|timestamptz_ge_date|" + + "timestamptz_ge_timestamp|timestamptz_gt|timestamptz_gt_date|" + + "timestamptz_gt_timestamp|timestamptz_in|timestamptz_larger|timestamptz_le|" + + "timestamptz_le_date|timestamptz_le_timestamp|timestamptz_lt|timestamptz_lt_date|" + + "timestamptz_lt_timestamp|timestamptz_mi|timestamptz_mi_interval|timestamptz_ne|" + + "timestamptz_ne_date|timestamptz_ne_timestamp|timestamptz_out|" + + "timestamptz_pl_interval|timestamptz_recv|timestamptz_send|timestamptz_smaller|" + + "timestamptztypmodin|timestamptztypmodout|timetypmodin|timetypmodout|timetz_cmp|" + + "timetz_eq|timetz_ge|timetz_gt|timetz_hash|timetz_in|timetz_larger|timetz_le|timetz_lt|" + + "timetz_mi_interval|timetz_ne|timetz_out|timetz_pl_interval|timetz_recv|timetz_send|" + + "timetz_smaller|timetzdate_pl|timetztypmodin|timetztypmodout|timezone|tinterval|" + + "tintervalct|tintervalend|tintervaleq|tintervalge|tintervalgt|tintervalin|tintervalle|" + + "tintervalleneq|tintervallenge|tintervallengt|tintervallenle|tintervallenlt|" + + "tintervallenne|tintervallt|tintervalne|tintervalout|tintervalov|tintervalrecv|" + + "tintervalrel|tintervalsame|tintervalsend|tintervalstart|to_ascii|to_char|to_date|to_hex|" + + "to_number|to_timestamp|to_tsquery|to_tsvector|transaction_timestamp|translate|" + + "trigger_in|trigger_out|trunc|ts_debug|ts_headline|ts_lexize|ts_match_qv|ts_match_tq|" + + "ts_match_tt|ts_match_vq|ts_parse|ts_rank|ts_rank_cd|ts_rewrite|ts_stat|ts_token_type|" + + "ts_typanalyze|tsmatchjoinsel|tsmatchsel|tsq_mcontained|tsq_mcontains|tsquery_and|" + + "tsquery_cmp|tsquery_eq|tsquery_ge|tsquery_gt|tsquery_le|tsquery_lt|tsquery_ne|" + + "tsquery_not|tsquery_or|tsqueryin|tsqueryout|tsqueryrecv|tsquerysend|tsvector_cmp|" + + "tsvector_concat|tsvector_eq|tsvector_ge|tsvector_gt|tsvector_le|tsvector_lt|" + + "tsvector_ne|tsvector_update_trigger|tsvector_update_trigger_column|tsvectorin|" + + "tsvectorout|tsvectorrecv|tsvectorsend|txid_current|txid_current_snapshot|" + + "txid_snapshot_in|txid_snapshot_out|txid_snapshot_recv|txid_snapshot_send|" + + "txid_snapshot_xip|txid_snapshot_xmax|txid_snapshot_xmin|txid_visible_in_snapshot|" + + "uhc_to_utf8|unique_key_recheck|unknownin|unknownout|unknownrecv|unknownsend|unnest|" + + "upper|utf8_to_ascii|utf8_to_big5|utf8_to_euc_cn|utf8_to_euc_jis_2004|utf8_to_euc_jp|" + + "utf8_to_euc_kr|utf8_to_euc_tw|utf8_to_gb18030|utf8_to_gbk|utf8_to_iso8859|" + + "utf8_to_iso8859_1|utf8_to_johab|utf8_to_koi8r|utf8_to_koi8u|utf8_to_shift_jis_2004|" + + "utf8_to_sjis|utf8_to_uhc|utf8_to_win|uuid_cmp|uuid_eq|uuid_ge|uuid_gt|uuid_hash|uuid_in|" + + "uuid_le|uuid_lt|uuid_ne|uuid_out|uuid_recv|uuid_send|var_pop|var_samp|varbit_in|" + + "varbit_out|varbit_recv|varbit_send|varbitcmp|varbiteq|varbitge|varbitgt|varbitle|" + + "varbitlt|varbitne|varbittypmodin|varbittypmodout|varcharin|varcharout|varcharrecv|" + + "varcharsend|varchartypmodin|varchartypmodout|variance|version|void_in|void_out|" + + "void_recv|void_send|width|width_bucket|win1250_to_latin2|win1250_to_mic|win1251_to_iso|" + + "win1251_to_koi8r|win1251_to_mic|win1251_to_win866|win866_to_iso|win866_to_koi8r|" + + "win866_to_mic|win866_to_win1251|win_to_utf8|xideq|xideqint4|xidin|xidout|xidrecv|xidsend|" + + "xml|xml_in|xml_is_well_formed|xml_is_well_formed_content|xml_is_well_formed_document|" + + "xml_out|xml_recv|xml_send|xmlagg|xmlcomment|xmlconcat2|xmlexists|xmlvalidate|xpath|" + + "xpath_exists").split("|") + ); + + var sqlRules = [ + { + token : "string", // single line string -- assume dollar strings if multi-line for now + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "variable.language", // pg identifier + regex : '".*?"' + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : function(value) { + value = value.toLowerCase(); + if (keywords.hasOwnProperty(value)) { + return "keyword"; + } else if (builtinFunctions.hasOwnProperty(value)) { + return "support.function"; + } else { + return "identifier"; + } + }, + regex : "[a-zA-Z_][a-zA-Z0-9_$]*\\b" // TODO - Unicode in identifiers + }, { + token : "keyword.operator", + regex : "!|!!|!~|!~\\*|!~~|!~~\\*|#|##|#<|#<=|#<>|#=|#>|#>=|%|\\&|\\&\\&|\\&<|\\&<\\||\\&>|\\*|\\+|" + + "\\-|/|<|<#>|<\\->|<<|<<=|<<\\||<=|<>|<\\?>|<@|<\\^|=|>|>=|>>|>>=|>\\^|\\?#|\\?\\-|\\?\\-\\||" + + "\\?\\||\\?\\|\\||@|@\\-@|@>|@@|@@@|\\^|\\||\\|\\&>|\\|/|\\|>>|\\|\\||\\|\\|/|~|~\\*|~<=~|~<~|" + + "~=|~>=~|~>~|~~|~~\\*" + }, { + token : "lparen.paren", + regex : "[\\(]" + }, { + token : "paren.rparen", + regex : "[\\)]" + }, { + token : "text", + regex : "\\s+" + } + ]; + + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "--.*$" + }, + new DocCommentHighlightRules().getStartRule("doc-start"), + { + token : "comment", // multi-line comment + merge : true, + regex : "\\/\\*", + next : "comment" + },{ + token : "keyword.statementBegin", + regex : "^[a-zA-Z]+", // Could enumerate starting keywords but this allows things to work when new statements are added. + next : "statement" + },{ + token : "support.buildin", // psql directive + regex : "^\\\\[\\S]+.*$" + } + ], + + "statement" : [ + { + token : "comment", + regex : "--.*$" + }, { + token : "comment", // multi-line comment + merge : true, + regex : "\\/\\*", + next : "commentStatement" + }, { + token : "statementEnd", + regex : ";", + next : "start" + }, { + token : "string", // perl, python, tcl are in the pg default dist (no tcl highlighter) + regex : "\\$perl\\$", + next : "perl-start" + }, { + token : "string", + regex : "\\$python\\$", + next : "python-start" + },{ + token : "string", + regex : "\\$[\\w_0-9]*\\$$", // dollar quote at the end of a line + next : "dollarSql" + }, { + token : "string", + regex : "\\$[\\w_0-9]*\\$", + next : "dollarStatementString" + } + ].concat(sqlRules), + + "dollarSql" : [ + { + token : "comment", + regex : "--.*$" + }, { + token : "comment", // multi-line comment + merge : true, + regex : "\\/\\*", + next : "commentDollarSql" + }, { + token : "string", // end quoting with dollar at the start of a line + regex : "^\\$[\\w_0-9]*\\$", + next : "statement" + }, { + token : "string", + regex : "\\$[\\w_0-9]*\\$", + next : "dollarSqlString" + } + ].concat(sqlRules), + + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ], + + "commentStatement" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "statement" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ], + + "commentDollarSql" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "dollarSql" + }, { + token : "comment", // comment spanning whole line + merge : true, + regex : ".+" + } + ], + + "dollarStatementString" : [ + { + token : "string", // closing dollarstring + regex : ".*?\\$[\\w_0-9]*\\$", + next : "statement" + }, { + token : "string", // dollarstring spanning whole line + merge : true, + regex : ".+" + } + ], + + "dollarSqlString" : [ + { + token : "string", // closing dollarstring + regex : ".*?\\$[\\w_0-9]*\\$", + next : "dollarSql" + }, { + token : "string", // dollarstring spanning whole line + merge : true, + regex : ".+" + } + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); + this.embedRules(PerlHighlightRules, "perl-", [{token : "string", regex : "\\$perl\\$", next : "statement"}]); + this.embedRules(PythonHighlightRules, "python-", [{token : "string", regex : "\\$python\\$", next : "statement"}]); +}; + +oop.inherits(PgsqlHighlightRules, TextHighlightRules); + +exports.PgsqlHighlightRules = PgsqlHighlightRules; +}); + +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, { + token : "comment.doc", + merge : true, + regex : "\\s+" + }, { + token : "comment.doc", + merge : true, + regex : "TODO" + }, { + token : "comment.doc", + merge : true, + regex : "[^@\\*]+" + }, { + token : "comment.doc", + merge : true, + regex : "." + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +(function() { + + this.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + merge : true, + regex : "\\/\\*(?=\\*)", + next : start + }; + }; + + this.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + merge : true, + regex : "\\*\\/", + next : start + }; + }; + +}).call(DocCommentHighlightRules.prototype); + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Panagiotis Astithas + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var PerlHighlightRules = function() { + + var keywords = lang.arrayToMap( + ("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + + "no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars").split("|") + ); + + var buildinConstants = lang.arrayToMap( + ("ARGV|ENV|INC|SIG").split("|") + ); + + var builtinFunctions = lang.arrayToMap( + ("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + + "map|die|uc|lc|do").split("|") + ); + + // regexp must not have capturing parentheses. Use (?:) instead. + // regexps are ordered -> the first match is used + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "#.*$" + }, { + token : "string.regexp", + regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // multi line string start + merge : true, + regex : '["].*\\\\$', + next : "qqstring" + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "string", // multi line string start + merge : true, + regex : "['].*\\\\$", + next : "qstring" + }, { + token : "constant.numeric", // hex + regex : "0x[0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : function(value) { + if (keywords.hasOwnProperty(value)) + return "keyword"; + else if (buildinConstants.hasOwnProperty(value)) + return "constant.language"; + else if (builtinFunctions.hasOwnProperty(value)) + return "support.function"; + else + return "identifier"; + }, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" + }, { + token : "lparen", + regex : "[[({]" + }, { + token : "rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "qqstring" : [ + { + token : "string", + regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', + next : "start" + }, { + token : "string", + merge : true, + regex : '.+' + } + ], + "qstring" : [ + { + token : "string", + regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", + next : "start" + }, { + token : "string", + merge : true, + regex : '.+' + } + ] + }; +}; + +oop.inherits(PerlHighlightRules, TextHighlightRules); + +exports.PerlHighlightRules = PerlHighlightRules; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Fabian Jakobs + * Colin Gourlay + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** + * + * TODO: python delimiters + */ + +define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var PythonHighlightRules = function() { + + var keywords = lang.arrayToMap( + ("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + + "raise|return|try|while|with|yield").split("|") + ); + + var builtinConstants = lang.arrayToMap( + ("True|False|None|NotImplemented|Ellipsis|__debug__").split("|") + ); + + var builtinFunctions = lang.arrayToMap( + ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|") + ); + + var futureReserved = lang.arrayToMap( + ("").split("|") + ); + + var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; + + var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; + var octInteger = "(?:0[oO]?[0-7]+)"; + var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; + var binInteger = "(?:0[bB][01]+)"; + var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; + + var exponent = "(?:[eE][+-]?\\d+)"; + var fraction = "(?:\\.\\d+)"; + var intPart = "(?:\\d+)"; + var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; + var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; + var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; + + this.$rules = { + "start" : [ { + token : "comment", + regex : "#.*$" + }, { + token : "string", // """ string + regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}' + }, { + token : "string", // multi line """ string start + merge : true, + regex : strPre + '"{3}.*$', + next : "qqstring" + }, { + token : "string", // " string + regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' + }, { + token : "string", // ''' string + regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}" + }, { + token : "string", // multi line ''' string start + merge : true, + regex : strPre + "'{3}.*$", + next : "qstring" + }, { + token : "string", // ' string + regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" + }, { + token : "constant.numeric", // imaginary + regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" + }, { + token : "constant.numeric", // float + regex : floatNumber + }, { + token : "constant.numeric", // long integer + regex : integer + "[lL]\\b" + }, { + token : "constant.numeric", // integer + regex : integer + "\\b" + }, { + token : function(value) { + if (keywords.hasOwnProperty(value)) + return "keyword"; + else if (builtinConstants.hasOwnProperty(value)) + return "constant.language"; + else if (futureReserved.hasOwnProperty(value)) + return "invalid.illegal"; + else if (builtinFunctions.hasOwnProperty(value)) + return "support.function"; + else if (value == "debugger") + return "invalid.deprecated"; + else + return "identifier"; + }, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" + }, { + token : "lparen.paren", + regex : "[\\[\\(\\{]" + }, { + token : "paren.rparen", + regex : "[\\]\\)\\}]" + }, { + token : "text", + regex : "\\s+" + } ], + "qqstring" : [ { + token : "string", // multi line """ string end + regex : '(?:[^\\\\]|\\\\.)*?"{3}', + next : "start" + }, { + token : "string", + merge : true, + regex : '.+' + } ], + "qstring" : [ { + token : "string", // multi line ''' string end + regex : "(?:[^\\\\]|\\\\.)*?'{3}", + next : "start" + }, { + token : "string", + merge : true, + regex : '.+' + } ] + }; +}; + +oop.inherits(PythonHighlightRules, TextHighlightRules); + +exports.PythonHighlightRules = PythonHighlightRules; +}); diff --git a/apps/files_texteditor/js/aceeditor/mode-pgsql.js b/apps/files_texteditor/js/aceeditor/mode-pgsql.js new file mode 100755 index 00000000000..12a02277af7 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-pgsql.js @@ -0,0 +1 @@ +define("ace/mode/pgsql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/pgsql_highlight_rules","ace/range"],function(a,b,c){var d=a("ace/lib/oop"),e=a("ace/mode/text").Mode,f=a("ace/tokenizer").Tokenizer,g=a("ace/mode/pgsql_highlight_rules").PgsqlHighlightRules,h=a("ace/range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)--/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var i=new h(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);i.start.row=g,i.end.row=g,i.end.column=k[0].length,b.replace(i,k[1])}}else b.indentRows(c,d,"--")},this.getNextLineIndent=function(a,b,c){return a=="start"||a=="keyword.statementEnd"?"":this.$getIndent(b)}}.call(i.prototype),b.Mode=i}),define("ace/mode/pgsql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules","ace/mode/perl_highlight_rules","ace/mode/python_highlight_rules"],function(a,b,c){var d=a("ace/lib/oop"),e=a("ace/lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=a("./perl_highlight_rules").PerlHighlightRules,i=a("./python_highlight_rules").PythonHighlightRules,j=function(){var a=e.arrayToMap("abort|absolute|abstime|access|aclitem|action|add|admin|after|aggregate|all|also|alter|always|analyse|analyze|and|any|anyarray|anyelement|anyenum|anynonarray|array|as|asc|assertion|assignment|asymmetric|at|attribute|authorization|backward|before|begin|between|bigint|binary|bit|bool|boolean|both|box|bpchar|by|bytea|cache|called|cascade|cascaded|case|cast|catalog|chain|char|character|characteristics|check|checkpoint|cid|cidr|circle|class|close|cluster|coalesce|collate|collation|column|comment|comments|commit|committed|concurrently|configuration|connection|constraint|constraints|content|continue|conversion|copy|cost|create|cross|cstring|csv|current|current_catalog|current_date|current_role|current_schema|current_time|current_timestamp|current_user|cursor|cycle|data|database|date|day|deallocate|dec|decimal|declare|default|defaults|deferrable|deferred|definer|delete|delimiter|delimiters|desc|dictionary|disable|discard|distinct|do|document|domain|double|drop|each|else|enable|encoding|encrypted|end|enum|escape|except|exclude|excluding|exclusive|execute|exists|explain|extension|external|extract|false|family|fdw_handler|fetch|first|float|float4|float8|following|for|force|foreign|forward|freeze|from|full|function|functions|global|grant|granted|greatest|group|gtsvector|handler|having|header|hold|hour|identity|if|ilike|immediate|immutable|implicit|in|including|increment|index|indexes|inet|inherit|inherits|initially|inline|inner|inout|input|insensitive|insert|instead|int|int2|int2vector|int4|int8|integer|internal|intersect|interval|into|invoker|is|isnull|isolation|join|key|label|language|language_handler|large|last|lc_collate|lc_ctype|leading|least|left|level|like|limit|line|listen|load|local|localtime|localtimestamp|location|lock|lseg|macaddr|mapping|match|maxvalue|minute|minvalue|mode|money|month|move|name|names|national|natural|nchar|next|no|none|not|nothing|notify|notnull|nowait|null|nullif|nulls|numeric|object|of|off|offset|oid|oids|oidvector|on|only|opaque|operator|option|options|or|order|out|outer|over|overlaps|overlay|owned|owner|parser|partial|partition|passing|password|path|pg_attribute|pg_auth_members|pg_authid|pg_class|pg_database|pg_node_tree|pg_proc|pg_type|placing|plans|point|polygon|position|preceding|precision|prepare|prepared|preserve|primary|prior|privileges|procedural|procedure|quote|range|read|real|reassign|recheck|record|recursive|ref|refcursor|references|regclass|regconfig|regdictionary|regoper|regoperator|regproc|regprocedure|regtype|reindex|relative|release|reltime|rename|repeatable|replace|replica|reset|restart|restrict|returning|returns|revoke|right|role|rollback|row|rows|rule|savepoint|schema|scroll|search|second|security|select|sequence|sequences|serializable|server|session|session_user|set|setof|share|show|similar|simple|smallint|smgr|some|stable|standalone|start|statement|statistics|stdin|stdout|storage|strict|strip|substring|symmetric|sysid|system|table|tables|tablespace|temp|template|temporary|text|then|tid|time|timestamp|timestamptz|timetz|tinterval|to|trailing|transaction|treat|trigger|trim|true|truncate|trusted|tsquery|tsvector|txid_snapshot|type|unbounded|uncommitted|unencrypted|union|unique|unknown|unlisten|unlogged|until|update|user|using|uuid|vacuum|valid|validate|validator|value|values|varbit|varchar|variadic|varying|verbose|version|view|void|volatile|when|where|whitespace|window|with|without|work|wrapper|write|xid|xml|xmlattributes|xmlconcat|xmlelement|xmlexists|xmlforest|xmlparse|xmlpi|xmlroot|xmlserialize|year|yes|zone".split("|")),b=e.arrayToMap("RI_FKey_cascade_del|RI_FKey_cascade_upd|RI_FKey_check_ins|RI_FKey_check_upd|RI_FKey_noaction_del|RI_FKey_noaction_upd|RI_FKey_restrict_del|RI_FKey_restrict_upd|RI_FKey_setdefault_del|RI_FKey_setdefault_upd|RI_FKey_setnull_del|RI_FKey_setnull_upd|abbrev|abs|abstime|abstimeeq|abstimege|abstimegt|abstimein|abstimele|abstimelt|abstimene|abstimeout|abstimerecv|abstimesend|aclcontains|aclexplode|aclinsert|aclitemeq|aclitemin|aclitemout|aclremove|acos|age|any_in|any_out|anyarray_in|anyarray_out|anyarray_recv|anyarray_send|anyelement_in|anyelement_out|anyenum_in|anyenum_out|anynonarray_in|anynonarray_out|anytextcat|area|areajoinsel|areasel|array_agg|array_agg_finalfn|array_agg_transfn|array_append|array_cat|array_dims|array_eq|array_fill|array_ge|array_gt|array_in|array_larger|array_le|array_length|array_lower|array_lt|array_ndims|array_ne|array_out|array_prepend|array_recv|array_send|array_smaller|array_to_string|array_upper|arraycontained|arraycontains|arrayoverlap|ascii|ascii_to_mic|ascii_to_utf8|asin|atan|atan2|avg|big5_to_euc_tw|big5_to_mic|big5_to_utf8|bit_and|bit_in|bit_length|bit_or|bit_out|bit_recv|bit_send|bitand|bitcat|bitcmp|biteq|bitge|bitgt|bitle|bitlt|bitne|bitnot|bitor|bitshiftleft|bitshiftright|bittypmodin|bittypmodout|bitxor|bool|bool_and|bool_or|booland_statefunc|booleq|boolge|boolgt|boolin|boolle|boollt|boolne|boolor_statefunc|boolout|boolrecv|boolsend|box|box_above|box_above_eq|box_add|box_below|box_below_eq|box_center|box_contain|box_contain_pt|box_contained|box_distance|box_div|box_eq|box_ge|box_gt|box_in|box_intersect|box_le|box_left|box_lt|box_mul|box_out|box_overabove|box_overbelow|box_overlap|box_overleft|box_overright|box_recv|box_right|box_same|box_send|box_sub|bpchar_larger|bpchar_pattern_ge|bpchar_pattern_gt|bpchar_pattern_le|bpchar_pattern_lt|bpchar_smaller|bpcharcmp|bpchareq|bpcharge|bpchargt|bpchariclike|bpcharicnlike|bpcharicregexeq|bpcharicregexne|bpcharin|bpcharle|bpcharlike|bpcharlt|bpcharne|bpcharnlike|bpcharout|bpcharrecv|bpcharregexeq|bpcharregexne|bpcharsend|bpchartypmodin|bpchartypmodout|broadcast|btabstimecmp|btarraycmp|btbeginscan|btboolcmp|btbpchar_pattern_cmp|btbuild|btbuildempty|btbulkdelete|btcharcmp|btcostestimate|btendscan|btfloat48cmp|btfloat4cmp|btfloat84cmp|btfloat8cmp|btgetbitmap|btgettuple|btinsert|btint24cmp|btint28cmp|btint2cmp|btint42cmp|btint48cmp|btint4cmp|btint82cmp|btint84cmp|btint8cmp|btmarkpos|btnamecmp|btoidcmp|btoidvectorcmp|btoptions|btrecordcmp|btreltimecmp|btrescan|btrestrpos|btrim|bttext_pattern_cmp|bttextcmp|bttidcmp|bttintervalcmp|btvacuumcleanup|byteacat|byteacmp|byteaeq|byteage|byteagt|byteain|byteale|bytealike|bytealt|byteane|byteanlike|byteaout|bytearecv|byteasend|cash_cmp|cash_div_cash|cash_div_flt4|cash_div_flt8|cash_div_int2|cash_div_int4|cash_eq|cash_ge|cash_gt|cash_in|cash_le|cash_lt|cash_mi|cash_mul_flt4|cash_mul_flt8|cash_mul_int2|cash_mul_int4|cash_ne|cash_out|cash_pl|cash_recv|cash_send|cash_words|cashlarger|cashsmaller|cbrt|ceil|ceiling|center|char|char_length|character_length|chareq|charge|chargt|charin|charle|charlt|charne|charout|charrecv|charsend|chr|cideq|cidin|cidout|cidr|cidr_in|cidr_out|cidr_recv|cidr_send|cidrecv|cidsend|circle|circle_above|circle_add_pt|circle_below|circle_center|circle_contain|circle_contain_pt|circle_contained|circle_distance|circle_div_pt|circle_eq|circle_ge|circle_gt|circle_in|circle_le|circle_left|circle_lt|circle_mul_pt|circle_ne|circle_out|circle_overabove|circle_overbelow|circle_overlap|circle_overleft|circle_overright|circle_recv|circle_right|circle_same|circle_send|circle_sub_pt|clock_timestamp|close_lb|close_ls|close_lseg|close_pb|close_pl|close_ps|close_sb|close_sl|col_description|concat|concat_ws|contjoinsel|contsel|convert|convert_from|convert_to|corr|cos|cot|count|covar_pop|covar_samp|cstring_in|cstring_out|cstring_recv|cstring_send|cume_dist|current_database|current_query|current_schema|current_schemas|current_setting|current_user|currtid|currtid2|currval|cursor_to_xml|cursor_to_xmlschema|database_to_xml|database_to_xml_and_xmlschema|database_to_xmlschema|date|date_cmp|date_cmp_timestamp|date_cmp_timestamptz|date_eq|date_eq_timestamp|date_eq_timestamptz|date_ge|date_ge_timestamp|date_ge_timestamptz|date_gt|date_gt_timestamp|date_gt_timestamptz|date_in|date_larger|date_le|date_le_timestamp|date_le_timestamptz|date_lt|date_lt_timestamp|date_lt_timestamptz|date_mi|date_mi_interval|date_mii|date_ne|date_ne_timestamp|date_ne_timestamptz|date_out|date_part|date_pl_interval|date_pli|date_recv|date_send|date_smaller|date_trunc|datetime_pl|datetimetz_pl|dcbrt|decode|degrees|dense_rank|dexp|diagonal|diameter|dispell_init|dispell_lexize|dist_cpoly|dist_lb|dist_pb|dist_pc|dist_pl|dist_ppath|dist_ps|dist_sb|dist_sl|div|dlog1|dlog10|domain_in|domain_recv|dpow|dround|dsimple_init|dsimple_lexize|dsnowball_init|dsnowball_lexize|dsqrt|dsynonym_init|dsynonym_lexize|dtrunc|encode|enum_cmp|enum_eq|enum_first|enum_ge|enum_gt|enum_in|enum_larger|enum_last|enum_le|enum_lt|enum_ne|enum_out|enum_range|enum_recv|enum_send|enum_smaller|eqjoinsel|eqsel|euc_cn_to_mic|euc_cn_to_utf8|euc_jis_2004_to_shift_jis_2004|euc_jis_2004_to_utf8|euc_jp_to_mic|euc_jp_to_sjis|euc_jp_to_utf8|euc_kr_to_mic|euc_kr_to_utf8|euc_tw_to_big5|euc_tw_to_mic|euc_tw_to_utf8|every|exp|factorial|family|fdw_handler_in|fdw_handler_out|first_value|float4|float48div|float48eq|float48ge|float48gt|float48le|float48lt|float48mi|float48mul|float48ne|float48pl|float4_accum|float4abs|float4div|float4eq|float4ge|float4gt|float4in|float4larger|float4le|float4lt|float4mi|float4mul|float4ne|float4out|float4pl|float4recv|float4send|float4smaller|float4um|float4up|float8|float84div|float84eq|float84ge|float84gt|float84le|float84lt|float84mi|float84mul|float84ne|float84pl|float8_accum|float8_avg|float8_corr|float8_covar_pop|float8_covar_samp|float8_regr_accum|float8_regr_avgx|float8_regr_avgy|float8_regr_intercept|float8_regr_r2|float8_regr_slope|float8_regr_sxx|float8_regr_sxy|float8_regr_syy|float8_stddev_pop|float8_stddev_samp|float8_var_pop|float8_var_samp|float8abs|float8div|float8eq|float8ge|float8gt|float8in|float8larger|float8le|float8lt|float8mi|float8mul|float8ne|float8out|float8pl|float8recv|float8send|float8smaller|float8um|float8up|floor|flt4_mul_cash|flt8_mul_cash|fmgr_c_validator|fmgr_internal_validator|fmgr_sql_validator|format|format_type|gb18030_to_utf8|gbk_to_utf8|generate_series|generate_subscripts|get_bit|get_byte|get_current_ts_config|getdatabaseencoding|getpgusername|gin_cmp_prefix|gin_cmp_tslexeme|gin_extract_tsquery|gin_extract_tsvector|gin_tsquery_consistent|ginarrayconsistent|ginarrayextract|ginbeginscan|ginbuild|ginbuildempty|ginbulkdelete|gincostestimate|ginendscan|gingetbitmap|gininsert|ginmarkpos|ginoptions|ginqueryarrayextract|ginrescan|ginrestrpos|ginvacuumcleanup|gist_box_compress|gist_box_consistent|gist_box_decompress|gist_box_penalty|gist_box_picksplit|gist_box_same|gist_box_union|gist_circle_compress|gist_circle_consistent|gist_point_compress|gist_point_consistent|gist_point_distance|gist_poly_compress|gist_poly_consistent|gistbeginscan|gistbuild|gistbuildempty|gistbulkdelete|gistcostestimate|gistendscan|gistgetbitmap|gistgettuple|gistinsert|gistmarkpos|gistoptions|gistrescan|gistrestrpos|gistvacuumcleanup|gtsquery_compress|gtsquery_consistent|gtsquery_decompress|gtsquery_penalty|gtsquery_picksplit|gtsquery_same|gtsquery_union|gtsvector_compress|gtsvector_consistent|gtsvector_decompress|gtsvector_penalty|gtsvector_picksplit|gtsvector_same|gtsvector_union|gtsvectorin|gtsvectorout|has_any_column_privilege|has_column_privilege|has_database_privilege|has_foreign_data_wrapper_privilege|has_function_privilege|has_language_privilege|has_schema_privilege|has_sequence_privilege|has_server_privilege|has_table_privilege|has_tablespace_privilege|hash_aclitem|hash_array|hash_numeric|hashbeginscan|hashbpchar|hashbuild|hashbuildempty|hashbulkdelete|hashchar|hashcostestimate|hashendscan|hashenum|hashfloat4|hashfloat8|hashgetbitmap|hashgettuple|hashinet|hashinsert|hashint2|hashint2vector|hashint4|hashint8|hashmacaddr|hashmarkpos|hashname|hashoid|hashoidvector|hashoptions|hashrescan|hashrestrpos|hashtext|hashvacuumcleanup|hashvarlena|height|host|hostmask|iclikejoinsel|iclikesel|icnlikejoinsel|icnlikesel|icregexeqjoinsel|icregexeqsel|icregexnejoinsel|icregexnesel|inet_client_addr|inet_client_port|inet_in|inet_out|inet_recv|inet_send|inet_server_addr|inet_server_port|inetand|inetmi|inetmi_int8|inetnot|inetor|inetpl|initcap|int2|int24div|int24eq|int24ge|int24gt|int24le|int24lt|int24mi|int24mul|int24ne|int24pl|int28div|int28eq|int28ge|int28gt|int28le|int28lt|int28mi|int28mul|int28ne|int28pl|int2_accum|int2_avg_accum|int2_mul_cash|int2_sum|int2abs|int2and|int2div|int2eq|int2ge|int2gt|int2in|int2larger|int2le|int2lt|int2mi|int2mod|int2mul|int2ne|int2not|int2or|int2out|int2pl|int2recv|int2send|int2shl|int2shr|int2smaller|int2um|int2up|int2vectoreq|int2vectorin|int2vectorout|int2vectorrecv|int2vectorsend|int2xor|int4|int42div|int42eq|int42ge|int42gt|int42le|int42lt|int42mi|int42mul|int42ne|int42pl|int48div|int48eq|int48ge|int48gt|int48le|int48lt|int48mi|int48mul|int48ne|int48pl|int4_accum|int4_avg_accum|int4_mul_cash|int4_sum|int4abs|int4and|int4div|int4eq|int4ge|int4gt|int4in|int4inc|int4larger|int4le|int4lt|int4mi|int4mod|int4mul|int4ne|int4not|int4or|int4out|int4pl|int4recv|int4send|int4shl|int4shr|int4smaller|int4um|int4up|int4xor|int8|int82div|int82eq|int82ge|int82gt|int82le|int82lt|int82mi|int82mul|int82ne|int82pl|int84div|int84eq|int84ge|int84gt|int84le|int84lt|int84mi|int84mul|int84ne|int84pl|int8_accum|int8_avg|int8_avg_accum|int8_sum|int8abs|int8and|int8div|int8eq|int8ge|int8gt|int8in|int8inc|int8inc_any|int8inc_float8_float8|int8larger|int8le|int8lt|int8mi|int8mod|int8mul|int8ne|int8not|int8or|int8out|int8pl|int8pl_inet|int8recv|int8send|int8shl|int8shr|int8smaller|int8um|int8up|int8xor|integer_pl_date|inter_lb|inter_sb|inter_sl|internal_in|internal_out|interval_accum|interval_avg|interval_cmp|interval_div|interval_eq|interval_ge|interval_gt|interval_hash|interval_in|interval_larger|interval_le|interval_lt|interval_mi|interval_mul|interval_ne|interval_out|interval_pl|interval_pl_date|interval_pl_time|interval_pl_timestamp|interval_pl_timestamptz|interval_pl_timetz|interval_recv|interval_send|interval_smaller|interval_um|intervaltypmodin|intervaltypmodout|intinterval|isclosed|isfinite|ishorizontal|iso8859_1_to_utf8|iso8859_to_utf8|iso_to_koi8r|iso_to_mic|iso_to_win1251|iso_to_win866|isopen|isparallel|isperp|isvertical|johab_to_utf8|justify_days|justify_hours|justify_interval|koi8r_to_iso|koi8r_to_mic|koi8r_to_utf8|koi8r_to_win1251|koi8r_to_win866|koi8u_to_utf8|lag|language_handler_in|language_handler_out|last_value|lastval|latin1_to_mic|latin2_to_mic|latin2_to_win1250|latin3_to_mic|latin4_to_mic|lead|left|length|like|like_escape|likejoinsel|likesel|line|line_distance|line_eq|line_horizontal|line_in|line_interpt|line_intersect|line_out|line_parallel|line_perp|line_recv|line_send|line_vertical|ln|lo_close|lo_creat|lo_create|lo_export|lo_import|lo_lseek|lo_open|lo_tell|lo_truncate|lo_unlink|log|loread|lower|lowrite|lpad|lseg|lseg_center|lseg_distance|lseg_eq|lseg_ge|lseg_gt|lseg_horizontal|lseg_in|lseg_interpt|lseg_intersect|lseg_le|lseg_length|lseg_lt|lseg_ne|lseg_out|lseg_parallel|lseg_perp|lseg_recv|lseg_send|lseg_vertical|ltrim|macaddr_cmp|macaddr_eq|macaddr_ge|macaddr_gt|macaddr_in|macaddr_le|macaddr_lt|macaddr_ne|macaddr_out|macaddr_recv|macaddr_send|makeaclitem|masklen|max|md5|mic_to_ascii|mic_to_big5|mic_to_euc_cn|mic_to_euc_jp|mic_to_euc_kr|mic_to_euc_tw|mic_to_iso|mic_to_koi8r|mic_to_latin1|mic_to_latin2|mic_to_latin3|mic_to_latin4|mic_to_sjis|mic_to_win1250|mic_to_win1251|mic_to_win866|min|mktinterval|mod|money|mul_d_interval|name|nameeq|namege|namegt|nameiclike|nameicnlike|nameicregexeq|nameicregexne|namein|namele|namelike|namelt|namene|namenlike|nameout|namerecv|nameregexeq|nameregexne|namesend|neqjoinsel|neqsel|netmask|network|network_cmp|network_eq|network_ge|network_gt|network_le|network_lt|network_ne|network_sub|network_subeq|network_sup|network_supeq|nextval|nlikejoinsel|nlikesel|notlike|now|npoints|nth_value|ntile|numeric_abs|numeric_accum|numeric_add|numeric_avg|numeric_avg_accum|numeric_cmp|numeric_div|numeric_div_trunc|numeric_eq|numeric_exp|numeric_fac|numeric_ge|numeric_gt|numeric_in|numeric_inc|numeric_larger|numeric_le|numeric_ln|numeric_log|numeric_lt|numeric_mod|numeric_mul|numeric_ne|numeric_out|numeric_power|numeric_recv|numeric_send|numeric_smaller|numeric_sqrt|numeric_stddev_pop|numeric_stddev_samp|numeric_sub|numeric_uminus|numeric_uplus|numeric_var_pop|numeric_var_samp|numerictypmodin|numerictypmodout|numnode|obj_description|octet_length|oid|oideq|oidge|oidgt|oidin|oidlarger|oidle|oidlt|oidne|oidout|oidrecv|oidsend|oidsmaller|oidvectoreq|oidvectorge|oidvectorgt|oidvectorin|oidvectorle|oidvectorlt|oidvectorne|oidvectorout|oidvectorrecv|oidvectorsend|oidvectortypes|on_pb|on_pl|on_ppath|on_ps|on_sb|on_sl|opaque_in|opaque_out|overlaps|overlay|path|path_add|path_add_pt|path_center|path_contain_pt|path_distance|path_div_pt|path_in|path_inter|path_length|path_mul_pt|path_n_eq|path_n_ge|path_n_gt|path_n_le|path_n_lt|path_npoints|path_out|path_recv|path_send|path_sub_pt|pclose|percent_rank|pg_advisory_lock|pg_advisory_lock_shared|pg_advisory_unlock|pg_advisory_unlock_all|pg_advisory_unlock_shared|pg_advisory_xact_lock|pg_advisory_xact_lock_shared|pg_available_extension_versions|pg_available_extensions|pg_backend_pid|pg_cancel_backend|pg_char_to_encoding|pg_client_encoding|pg_collation_is_visible|pg_column_size|pg_conf_load_time|pg_conversion_is_visible|pg_create_restore_point|pg_current_xlog_insert_location|pg_current_xlog_location|pg_cursor|pg_database_size|pg_describe_object|pg_encoding_max_length|pg_encoding_to_char|pg_extension_config_dump|pg_extension_update_paths|pg_function_is_visible|pg_get_constraintdef|pg_get_expr|pg_get_function_arguments|pg_get_function_identity_arguments|pg_get_function_result|pg_get_functiondef|pg_get_indexdef|pg_get_keywords|pg_get_ruledef|pg_get_serial_sequence|pg_get_triggerdef|pg_get_userbyid|pg_get_viewdef|pg_has_role|pg_indexes_size|pg_is_in_recovery|pg_is_other_temp_schema|pg_is_xlog_replay_paused|pg_last_xact_replay_timestamp|pg_last_xlog_receive_location|pg_last_xlog_replay_location|pg_listening_channels|pg_lock_status|pg_ls_dir|pg_my_temp_schema|pg_node_tree_in|pg_node_tree_out|pg_node_tree_recv|pg_node_tree_send|pg_notify|pg_opclass_is_visible|pg_operator_is_visible|pg_options_to_table|pg_postmaster_start_time|pg_prepared_statement|pg_prepared_xact|pg_read_binary_file|pg_read_file|pg_relation_filenode|pg_relation_filepath|pg_relation_size|pg_reload_conf|pg_rotate_logfile|pg_sequence_parameters|pg_show_all_settings|pg_size_pretty|pg_sleep|pg_start_backup|pg_stat_clear_snapshot|pg_stat_file|pg_stat_get_activity|pg_stat_get_analyze_count|pg_stat_get_autoanalyze_count|pg_stat_get_autovacuum_count|pg_stat_get_backend_activity|pg_stat_get_backend_activity_start|pg_stat_get_backend_client_addr|pg_stat_get_backend_client_port|pg_stat_get_backend_dbid|pg_stat_get_backend_idset|pg_stat_get_backend_pid|pg_stat_get_backend_start|pg_stat_get_backend_userid|pg_stat_get_backend_waiting|pg_stat_get_backend_xact_start|pg_stat_get_bgwriter_buf_written_checkpoints|pg_stat_get_bgwriter_buf_written_clean|pg_stat_get_bgwriter_maxwritten_clean|pg_stat_get_bgwriter_requested_checkpoints|pg_stat_get_bgwriter_stat_reset_time|pg_stat_get_bgwriter_timed_checkpoints|pg_stat_get_blocks_fetched|pg_stat_get_blocks_hit|pg_stat_get_buf_alloc|pg_stat_get_buf_fsync_backend|pg_stat_get_buf_written_backend|pg_stat_get_db_blocks_fetched|pg_stat_get_db_blocks_hit|pg_stat_get_db_conflict_all|pg_stat_get_db_conflict_bufferpin|pg_stat_get_db_conflict_lock|pg_stat_get_db_conflict_snapshot|pg_stat_get_db_conflict_startup_deadlock|pg_stat_get_db_conflict_tablespace|pg_stat_get_db_numbackends|pg_stat_get_db_stat_reset_time|pg_stat_get_db_tuples_deleted|pg_stat_get_db_tuples_fetched|pg_stat_get_db_tuples_inserted|pg_stat_get_db_tuples_returned|pg_stat_get_db_tuples_updated|pg_stat_get_db_xact_commit|pg_stat_get_db_xact_rollback|pg_stat_get_dead_tuples|pg_stat_get_function_calls|pg_stat_get_function_self_time|pg_stat_get_function_time|pg_stat_get_last_analyze_time|pg_stat_get_last_autoanalyze_time|pg_stat_get_last_autovacuum_time|pg_stat_get_last_vacuum_time|pg_stat_get_live_tuples|pg_stat_get_numscans|pg_stat_get_tuples_deleted|pg_stat_get_tuples_fetched|pg_stat_get_tuples_hot_updated|pg_stat_get_tuples_inserted|pg_stat_get_tuples_returned|pg_stat_get_tuples_updated|pg_stat_get_vacuum_count|pg_stat_get_wal_senders|pg_stat_get_xact_blocks_fetched|pg_stat_get_xact_blocks_hit|pg_stat_get_xact_function_calls|pg_stat_get_xact_function_self_time|pg_stat_get_xact_function_time|pg_stat_get_xact_numscans|pg_stat_get_xact_tuples_deleted|pg_stat_get_xact_tuples_fetched|pg_stat_get_xact_tuples_hot_updated|pg_stat_get_xact_tuples_inserted|pg_stat_get_xact_tuples_returned|pg_stat_get_xact_tuples_updated|pg_stat_reset|pg_stat_reset_shared|pg_stat_reset_single_function_counters|pg_stat_reset_single_table_counters|pg_stop_backup|pg_switch_xlog|pg_table_is_visible|pg_table_size|pg_tablespace_databases|pg_tablespace_size|pg_terminate_backend|pg_timezone_abbrevs|pg_timezone_names|pg_total_relation_size|pg_try_advisory_lock|pg_try_advisory_lock_shared|pg_try_advisory_xact_lock|pg_try_advisory_xact_lock_shared|pg_ts_config_is_visible|pg_ts_dict_is_visible|pg_ts_parser_is_visible|pg_ts_template_is_visible|pg_type_is_visible|pg_typeof|pg_xlog_replay_pause|pg_xlog_replay_resume|pg_xlogfile_name|pg_xlogfile_name_offset|pi|plainto_tsquery|plpgsql_call_handler|plpgsql_inline_handler|plpgsql_validator|point|point_above|point_add|point_below|point_distance|point_div|point_eq|point_horiz|point_in|point_left|point_mul|point_ne|point_out|point_recv|point_right|point_send|point_sub|point_vert|poly_above|poly_below|poly_center|poly_contain|poly_contain_pt|poly_contained|poly_distance|poly_in|poly_left|poly_npoints|poly_out|poly_overabove|poly_overbelow|poly_overlap|poly_overleft|poly_overright|poly_recv|poly_right|poly_same|poly_send|polygon|popen|position|positionjoinsel|positionsel|postgresql_fdw_validator|pow|power|prsd_end|prsd_headline|prsd_lextype|prsd_nexttoken|prsd_start|pt_contained_circle|pt_contained_poly|query_to_xml|query_to_xml_and_xmlschema|query_to_xmlschema|querytree|quote_ident|quote_literal|quote_nullable|radians|radius|random|rank|record_eq|record_ge|record_gt|record_in|record_le|record_lt|record_ne|record_out|record_recv|record_send|regclass|regclassin|regclassout|regclassrecv|regclasssend|regconfigin|regconfigout|regconfigrecv|regconfigsend|regdictionaryin|regdictionaryout|regdictionaryrecv|regdictionarysend|regexeqjoinsel|regexeqsel|regexnejoinsel|regexnesel|regexp_matches|regexp_replace|regexp_split_to_array|regexp_split_to_table|regoperatorin|regoperatorout|regoperatorrecv|regoperatorsend|regoperin|regoperout|regoperrecv|regopersend|regprocedurein|regprocedureout|regprocedurerecv|regproceduresend|regprocin|regprocout|regprocrecv|regprocsend|regr_avgx|regr_avgy|regr_count|regr_intercept|regr_r2|regr_slope|regr_sxx|regr_sxy|regr_syy|regtypein|regtypeout|regtyperecv|regtypesend|reltime|reltimeeq|reltimege|reltimegt|reltimein|reltimele|reltimelt|reltimene|reltimeout|reltimerecv|reltimesend|repeat|replace|reverse|right|round|row_number|rpad|rtrim|scalargtjoinsel|scalargtsel|scalarltjoinsel|scalarltsel|schema_to_xml|schema_to_xml_and_xmlschema|schema_to_xmlschema|session_user|set_bit|set_byte|set_config|set_masklen|setseed|setval|setweight|shell_in|shell_out|shift_jis_2004_to_euc_jis_2004|shift_jis_2004_to_utf8|shobj_description|sign|similar_escape|sin|sjis_to_euc_jp|sjis_to_mic|sjis_to_utf8|slope|smgreq|smgrin|smgrne|smgrout|split_part|sqrt|statement_timestamp|stddev|stddev_pop|stddev_samp|string_agg|string_agg_finalfn|string_agg_transfn|string_to_array|strip|strpos|substr|substring|sum|suppress_redundant_updates_trigger|table_to_xml|table_to_xml_and_xmlschema|table_to_xmlschema|tan|text|text_ge|text_gt|text_larger|text_le|text_lt|text_pattern_ge|text_pattern_gt|text_pattern_le|text_pattern_lt|text_smaller|textanycat|textcat|texteq|texticlike|texticnlike|texticregexeq|texticregexne|textin|textlen|textlike|textne|textnlike|textout|textrecv|textregexeq|textregexne|textsend|thesaurus_init|thesaurus_lexize|tideq|tidge|tidgt|tidin|tidlarger|tidle|tidlt|tidne|tidout|tidrecv|tidsend|tidsmaller|time_cmp|time_eq|time_ge|time_gt|time_hash|time_in|time_larger|time_le|time_lt|time_mi_interval|time_mi_time|time_ne|time_out|time_pl_interval|time_recv|time_send|time_smaller|timedate_pl|timemi|timenow|timeofday|timepl|timestamp_cmp|timestamp_cmp_date|timestamp_cmp_timestamptz|timestamp_eq|timestamp_eq_date|timestamp_eq_timestamptz|timestamp_ge|timestamp_ge_date|timestamp_ge_timestamptz|timestamp_gt|timestamp_gt_date|timestamp_gt_timestamptz|timestamp_hash|timestamp_in|timestamp_larger|timestamp_le|timestamp_le_date|timestamp_le_timestamptz|timestamp_lt|timestamp_lt_date|timestamp_lt_timestamptz|timestamp_mi|timestamp_mi_interval|timestamp_ne|timestamp_ne_date|timestamp_ne_timestamptz|timestamp_out|timestamp_pl_interval|timestamp_recv|timestamp_send|timestamp_smaller|timestamptypmodin|timestamptypmodout|timestamptz_cmp|timestamptz_cmp_date|timestamptz_cmp_timestamp|timestamptz_eq|timestamptz_eq_date|timestamptz_eq_timestamp|timestamptz_ge|timestamptz_ge_date|timestamptz_ge_timestamp|timestamptz_gt|timestamptz_gt_date|timestamptz_gt_timestamp|timestamptz_in|timestamptz_larger|timestamptz_le|timestamptz_le_date|timestamptz_le_timestamp|timestamptz_lt|timestamptz_lt_date|timestamptz_lt_timestamp|timestamptz_mi|timestamptz_mi_interval|timestamptz_ne|timestamptz_ne_date|timestamptz_ne_timestamp|timestamptz_out|timestamptz_pl_interval|timestamptz_recv|timestamptz_send|timestamptz_smaller|timestamptztypmodin|timestamptztypmodout|timetypmodin|timetypmodout|timetz_cmp|timetz_eq|timetz_ge|timetz_gt|timetz_hash|timetz_in|timetz_larger|timetz_le|timetz_lt|timetz_mi_interval|timetz_ne|timetz_out|timetz_pl_interval|timetz_recv|timetz_send|timetz_smaller|timetzdate_pl|timetztypmodin|timetztypmodout|timezone|tinterval|tintervalct|tintervalend|tintervaleq|tintervalge|tintervalgt|tintervalin|tintervalle|tintervalleneq|tintervallenge|tintervallengt|tintervallenle|tintervallenlt|tintervallenne|tintervallt|tintervalne|tintervalout|tintervalov|tintervalrecv|tintervalrel|tintervalsame|tintervalsend|tintervalstart|to_ascii|to_char|to_date|to_hex|to_number|to_timestamp|to_tsquery|to_tsvector|transaction_timestamp|translate|trigger_in|trigger_out|trunc|ts_debug|ts_headline|ts_lexize|ts_match_qv|ts_match_tq|ts_match_tt|ts_match_vq|ts_parse|ts_rank|ts_rank_cd|ts_rewrite|ts_stat|ts_token_type|ts_typanalyze|tsmatchjoinsel|tsmatchsel|tsq_mcontained|tsq_mcontains|tsquery_and|tsquery_cmp|tsquery_eq|tsquery_ge|tsquery_gt|tsquery_le|tsquery_lt|tsquery_ne|tsquery_not|tsquery_or|tsqueryin|tsqueryout|tsqueryrecv|tsquerysend|tsvector_cmp|tsvector_concat|tsvector_eq|tsvector_ge|tsvector_gt|tsvector_le|tsvector_lt|tsvector_ne|tsvector_update_trigger|tsvector_update_trigger_column|tsvectorin|tsvectorout|tsvectorrecv|tsvectorsend|txid_current|txid_current_snapshot|txid_snapshot_in|txid_snapshot_out|txid_snapshot_recv|txid_snapshot_send|txid_snapshot_xip|txid_snapshot_xmax|txid_snapshot_xmin|txid_visible_in_snapshot|uhc_to_utf8|unique_key_recheck|unknownin|unknownout|unknownrecv|unknownsend|unnest|upper|utf8_to_ascii|utf8_to_big5|utf8_to_euc_cn|utf8_to_euc_jis_2004|utf8_to_euc_jp|utf8_to_euc_kr|utf8_to_euc_tw|utf8_to_gb18030|utf8_to_gbk|utf8_to_iso8859|utf8_to_iso8859_1|utf8_to_johab|utf8_to_koi8r|utf8_to_koi8u|utf8_to_shift_jis_2004|utf8_to_sjis|utf8_to_uhc|utf8_to_win|uuid_cmp|uuid_eq|uuid_ge|uuid_gt|uuid_hash|uuid_in|uuid_le|uuid_lt|uuid_ne|uuid_out|uuid_recv|uuid_send|var_pop|var_samp|varbit_in|varbit_out|varbit_recv|varbit_send|varbitcmp|varbiteq|varbitge|varbitgt|varbitle|varbitlt|varbitne|varbittypmodin|varbittypmodout|varcharin|varcharout|varcharrecv|varcharsend|varchartypmodin|varchartypmodout|variance|version|void_in|void_out|void_recv|void_send|width|width_bucket|win1250_to_latin2|win1250_to_mic|win1251_to_iso|win1251_to_koi8r|win1251_to_mic|win1251_to_win866|win866_to_iso|win866_to_koi8r|win866_to_mic|win866_to_win1251|win_to_utf8|xideq|xideqint4|xidin|xidout|xidrecv|xidsend|xml|xml_in|xml_is_well_formed|xml_is_well_formed_content|xml_is_well_formed_document|xml_out|xml_recv|xml_send|xmlagg|xmlcomment|xmlconcat2|xmlexists|xmlvalidate|xpath|xpath_exists".split("|")),c=[{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"variable.language",regex:'".*?"'},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(c){return c=c.toLowerCase(),a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"support.function":"identifier"},regex:"[a-zA-Z_][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|!!|!~|!~\\*|!~~|!~~\\*|#|##|#<|#<=|#<>|#=|#>|#>=|%|\\&|\\&\\&|\\&<|\\&<\\||\\&>|\\*|\\+|\\-|/|<|<#>|<\\->|<<|<<=|<<\\||<=|<>|<\\?>|<@|<\\^|=|>|>=|>>|>>=|>\\^|\\?#|\\?\\-|\\?\\-\\||\\?\\||\\?\\|\\||@|@\\-@|@>|@@|@@@|\\^|\\||\\|\\&>|\\|/|\\|>>|\\|\\||\\|\\|/|~|~\\*|~<=~|~<~|~=|~>=~|~>~|~~|~~\\*"},{token:"lparen.paren",regex:"[\\(]"},{token:"paren.rparen",regex:"[\\)]"},{token:"text",regex:"\\s+"}];this.$rules={start:[{token:"comment",regex:"--.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"keyword.statementBegin",regex:"^[a-zA-Z]+",next:"statement"},{token:"support.buildin",regex:"^\\\\[\\S]+.*$"}],statement:[{token:"comment",regex:"--.*$"},{token:"comment",merge:!0,regex:"\\/\\*",next:"commentStatement"},{token:"statementEnd",regex:";",next:"start"},{token:"string",regex:"\\$perl\\$",next:"perl-start"},{token:"string",regex:"\\$python\\$",next:"python-start"},{token:"string",regex:"\\$[\\w_0-9]*\\$$",next:"dollarSql"},{token:"string",regex:"\\$[\\w_0-9]*\\$",next:"dollarStatementString"}].concat(c),dollarSql:[{token:"comment",regex:"--.*$"},{token:"comment",merge:!0,regex:"\\/\\*",next:"commentDollarSql"},{token:"string",regex:"^\\$[\\w_0-9]*\\$",next:"statement"},{token:"string",regex:"\\$[\\w_0-9]*\\$",next:"dollarSqlString"}].concat(c),comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],commentStatement:[{token:"comment",regex:".*?\\*\\/",next:"statement"},{token:"comment",merge:!0,regex:".+"}],commentDollarSql:[{token:"comment",regex:".*?\\*\\/",next:"dollarSql"},{token:"comment",merge:!0,regex:".+"}],dollarStatementString:[{token:"string",regex:".*?\\$[\\w_0-9]*\\$",next:"statement"},{token:"string",merge:!0,regex:".+"}],dollarSqlString:[{token:"string",regex:".*?\\$[\\w_0-9]*\\$",next:"dollarSql"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")]),this.embedRules(h,"perl-",[{token:"string",regex:"\\$perl\\$",next:"statement"}]),this.embedRules(i,"python-",[{token:"string",regex:"\\$python\\$",next:"statement"}])};d.inherits(j,g),b.PgsqlHighlightRules=j}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/perl_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars".split("|")),b=e.arrayToMap("ARGV|ENV|INC|SIG".split("|")),c=e.arrayToMap("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|getpeername|setpriority|getprotoent|setprotoent|getpriority|endprotoent|getservent|setservent|endservent|sethostent|socketpair|getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|map|die|uc|lc|do".split("|"));this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",merge:!0,regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",merge:!0,regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0x[0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(d){return a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PerlHighlightRules=g}),define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("and|as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|raise|return|try|while|with|yield".split("|")),b=e.arrayToMap("True|False|None|NotImplemented|Ellipsis|__debug__".split("|")),c=e.arrayToMap("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|float|list|raw_input|unichr|callable|format|locals|reduce|unicode|chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|__import__|complex|hash|min|set|apply|delattr|help|next|setattr|buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern".split("|")),d=e.arrayToMap("".split("|")),f="(?:r|u|ur|R|U|UR|Ur|uR)?",g="(?:(?:[1-9]\\d*)|(?:0))",h="(?:0[oO]?[0-7]+)",i="(?:0[xX][\\dA-Fa-f]+)",j="(?:0[bB][01]+)",k="(?:"+g+"|"+h+"|"+i+"|"+j+")",l="(?:[eE][+-]?\\d+)",m="(?:\\.\\d+)",n="(?:\\d+)",o="(?:(?:"+n+"?"+m+")|(?:"+n+"\\.))",p="(?:(?:"+o+"|"+n+")"+l+")",q="(?:"+p+"|"+o+")";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:f+'"{3}(?:[^\\\\]|\\\\.)*?"{3}'},{token:"string",merge:!0,regex:f+'"{3}.*$',next:"qqstring"},{token:"string",regex:f+'"(?:[^\\\\]|\\\\.)*?"'},{token:"string",regex:f+"'{3}(?:[^\\\\]|\\\\.)*?'{3}"},{token:"string",merge:!0,regex:f+"'{3}.*$",next:"qstring"},{token:"string",regex:f+"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:"(?:"+q+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:q},{token:"constant.numeric",regex:k+"[lL]\\b"},{token:"constant.numeric",regex:k+"\\b"},{token:function(e){return a.hasOwnProperty(e)?"keyword":b.hasOwnProperty(e)?"constant.language":d.hasOwnProperty(e)?"invalid.illegal":c.hasOwnProperty(e)?"support.function":e=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"lparen.paren",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:[^\\\\]|\\\\.)*?"{3}',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?'{3}",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PythonHighlightRules=g}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-php-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-php-uncompressed.js index 58c9255623d..3b0c2f8de10 100755 --- a/apps/files_texteditor/js/aceeditor/mode-php-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-php-uncompressed.js @@ -1071,14 +1071,14 @@ var PhpHighlightRules = function() { regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start - regex : '["].*\\\\$', + regex : '["][\\s\\S]*', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start - regex : "['].*\\\\$", + regex : "['][\\s\\S]+", next : "qstring" }, { token : "constant.numeric", // hex @@ -1160,21 +1160,21 @@ var PhpHighlightRules = function() { "qqstring" : [ { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', + regex : '"', next : "start" }, { token : "string", - regex : '.+' + regex : '[^"]+' } ], "qstring" : [ { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", + regex : "'", next : "start" }, { token : "string", - regex : '.+' + regex : "[^']+" } ], "htmlcomment" : [ @@ -1213,7 +1213,7 @@ var PhpHighlightRules = function() { next : "htmltag" }, { token : "meta.tag", - regex : ">", + regex : ">" }, { token : 'text', regex : "(?:media|type|href)" @@ -1223,7 +1223,7 @@ var PhpHighlightRules = function() { }, { token : "paren.lparen", regex : "\{", - next : "cssdeclaration", + next : "cssdeclaration" }, { token : "keyword", regex : "#[A-Za-z0-9\-\_\.]+" @@ -1265,7 +1265,7 @@ var PhpHighlightRules = function() { regex : ";", next : "cssdeclaration" } - ], + ] }; this.embedRules(DocCommentHighlightRules, "doc-", @@ -1507,12 +1507,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -1524,7 +1524,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -1542,7 +1542,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -1567,12 +1567,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -1584,7 +1584,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -1603,14 +1603,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -1631,7 +1632,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -1640,19 +1641,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1661,7 +1662,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1671,7 +1672,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1882,13 +1884,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-php.js b/apps/files_texteditor/js/aceeditor/mode-php.js index a60c8df7269..8b156ab98bc 100644 --- a/apps/files_texteditor/js/aceeditor/mode-php.js +++ b/apps/files_texteditor/js/aceeditor/mode-php.js @@ -1 +1 @@ -define("ace/mode/php",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/php_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./php_highlight_rules").PhpHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/php_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=new f,b=e.arrayToMap("abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|m_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|m_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|m_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|m_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type".split("|")),c=e.arrayToMap("abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|public|static|switch|throw|try|use|var|while|xor".split("|")),d=e.arrayToMap("die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset".split("|")),g=e.arrayToMap("true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__".split("|")),h=e.arrayToMap("$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|$http_response_header|$argc|$argv".split("|")),i=e.arrayToMap("key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregisterset_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|sql_regcase".split("|")),j=e.arrayToMap("cfunction|old_function".split("|")),k=e.arrayToMap([]);this.$rules={start:[{token:"support.php_tag",regex:"<\\?(?:php|\\=)"},{token:"support.php_tag",regex:"\\?>"},{token:"comment",regex:"<\\!--",next:"htmlcomment"},{token:"meta.tag",regex:""},{token:"comment",regex:"\\/\\/.*$"},{token:"comment",regex:"#.*$"},a.getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language",regex:"\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|VERSION))|__COMPILER_HALT_OFFSET__)\\b"},{token:"constant.language",regex:"\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b"},{token:function(a){return c.hasOwnProperty(a)?"keyword":g.hasOwnProperty(a)?"constant.language":h.hasOwnProperty(a)?"variable.language":k.hasOwnProperty(a)?"invalid.illegal":b.hasOwnProperty(a)?"support.function":a=="debugger"?"invalid.deprecated":a.match(/^(\$[a-zA-Z][a-zA-Z0-9_]*|self|parent)$/)?"variable":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",regex:".+"}],htmlcomment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",regex:".+"}],htmltag:[{token:"meta.tag",regex:">",next:"start"},{token:"text",regex:"[-_a-zA-Z0-9:]+"},{token:"text",regex:"\\s+"},{token:"string",regex:'".*?"'},{token:"string",regex:"'.*?'"}],css:[{token:"meta.tag",regex:"",next:"htmltag"},{token:"meta.tag",regex:">"},{token:"text",regex:"(?:media|type|href)"},{token:"string",regex:'=".*?"'},{token:"paren.lparen",regex:"{",next:"cssdeclaration"},{token:"keyword",regex:"#[A-Za-z0-9-_.]+"},{token:"variable",regex:"\\.[A-Za-z0-9-_.]+"},{token:"constant",regex:"[A-Za-z0-9]+"}],cssdeclaration:[{token:"support.type",regex:"[-a-zA-Z]+",next:"cssvalue"},{token:"paren.rparen",regex:"}",next:"css"}],cssvalue:[{token:"text",regex:":"},{token:"constant",regex:"#[0-9a-zA-Z]+"},{token:"text",regex:"[-_0-9a-zA-Z\"' ,%]+"},{token:"text",regex:";",next:"cssdeclaration"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.PhpHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/php",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/php_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./php_highlight_rules").PhpHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/php_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=new f,b=e.arrayToMap("abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|m_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|m_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|m_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|m_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type".split("|")),c=e.arrayToMap("abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|public|static|switch|throw|try|use|var|while|xor".split("|")),d=e.arrayToMap("die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset".split("|")),g=e.arrayToMap("true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__".split("|")),h=e.arrayToMap("$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|$http_response_header|$argc|$argv".split("|")),i=e.arrayToMap("key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregisterset_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|sql_regcase".split("|")),j=e.arrayToMap("cfunction|old_function".split("|")),k=e.arrayToMap([]);this.$rules={start:[{token:"support.php_tag",regex:"<\\?(?:php|\\=)"},{token:"support.php_tag",regex:"\\?>"},{token:"comment",regex:"<\\!--",next:"htmlcomment"},{token:"meta.tag",regex:""},{token:"comment",regex:"\\/\\/.*$"},{token:"comment",regex:"#.*$"},a.getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:'["][\\s\\S]*',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"['][\\s\\S]+",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language",regex:"\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|VERSION))|__COMPILER_HALT_OFFSET__)\\b"},{token:"constant.language",regex:"\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b"},{token:function(a){return c.hasOwnProperty(a)?"keyword":g.hasOwnProperty(a)?"constant.language":h.hasOwnProperty(a)?"variable.language":k.hasOwnProperty(a)?"invalid.illegal":b.hasOwnProperty(a)?"support.function":a=="debugger"?"invalid.deprecated":a.match(/^(\$[a-zA-Z][a-zA-Z0-9_]*|self|parent)$/)?"variable":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",regex:".+"}],qqstring:[{token:"string",regex:'"',next:"start"},{token:"string",regex:'[^"]+'}],qstring:[{token:"string",regex:"'",next:"start"},{token:"string",regex:"[^']+"}],htmlcomment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",regex:".+"}],htmltag:[{token:"meta.tag",regex:">",next:"start"},{token:"text",regex:"[-_a-zA-Z0-9:]+"},{token:"text",regex:"\\s+"},{token:"string",regex:'".*?"'},{token:"string",regex:"'.*?'"}],css:[{token:"meta.tag",regex:"",next:"htmltag"},{token:"meta.tag",regex:">"},{token:"text",regex:"(?:media|type|href)"},{token:"string",regex:'=".*?"'},{token:"paren.lparen",regex:"{",next:"cssdeclaration"},{token:"keyword",regex:"#[A-Za-z0-9-_.]+"},{token:"variable",regex:"\\.[A-Za-z0-9-_.]+"},{token:"constant",regex:"[A-Za-z0-9]+"}],cssdeclaration:[{token:"support.type",regex:"[-a-zA-Z]+",next:"cssvalue"},{token:"paren.rparen",regex:"}",next:"css"}],cssvalue:[{token:"text",regex:":"},{token:"constant",regex:"#[0-9a-zA-Z]+"},{token:"text",regex:"[-_0-9a-zA-Z\"' ,%]+"},{token:"text",regex:";",next:"cssdeclaration"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.PhpHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-powershell-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-powershell-uncompressed.js index e5877f62373..e6f9deea014 100755 --- a/apps/files_texteditor/js/aceeditor/mode-powershell-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-powershell-uncompressed.js @@ -329,12 +329,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -346,7 +346,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -364,7 +364,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -389,12 +389,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -406,7 +406,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -425,14 +425,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -453,7 +454,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -462,19 +463,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -483,7 +484,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -493,7 +494,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -704,13 +706,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-powershell.js b/apps/files_texteditor/js/aceeditor/mode-powershell.js index 9bbdef6989b..6ebaeae5201 100755 --- a/apps/files_texteditor/js/aceeditor/mode-powershell.js +++ b/apps/files_texteditor/js/aceeditor/mode-powershell.js @@ -1 +1 @@ -define("ace/mode/powershell",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/powershell_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./powershell_highlight_rules").PowershellHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/powershell_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("function|if|else|elseif|switch|while|default|for|do|until|break|continue|foreach|return|filter|in|trap|throw|param|begin|process|end".split("|")),b=e.arrayToMap("Get-Alias|Import-Alias|New-Alias|Set-Alias|Get-AuthenticodeSignature|Set-AuthenticodeSignature|Set-Location|Get-ChildItem|Clear-Item|Get-Command|Measure-Command|Trace-Command|Add-Computer|Checkpoint-Computer|Remove-Computer|Restart-Computer|Restore-Computer|Stop-Computer|Reset-ComputerMachinePassword|Test-ComputerSecureChannel|Add-Content|Get-Content|Set-Content|Clear-Content|Get-Command|Invoke-Command|Enable-ComputerRestore|Disable-ComputerRestore|Get-ComputerRestorePoint|Test-Connection|ConvertFrom-CSV|ConvertTo-CSV|ConvertTo-Html|ConvertTo-Xml|ConvertFrom-SecureString|ConvertTo-SecureString|Copy-Item|Export-Counter|Get-Counter|Import-Counter|Get-Credential|Get-Culture|Get-ChildItem|Get-Date|Set-Date|Remove-Item|Compare-Object|Get-Event|Get-WinEvent|New-Event|Remove-Event|Unregister-Event|Wait-Event|Clear-EventLog|Get-Eventlog|Limit-EventLog|New-Eventlog|Remove-EventLog|Show-EventLog|Write-EventLog|Get-EventSubscriber|Register-EngineEvent|Register-ObjectEvent|Register-WmiEvent|Get-ExecutionPolicy|Set-ExecutionPolicy|Export-Alias|Export-Clixml|Export-Console|Export-Csv|ForEach-Object|Format-Custom|Format-List|Format-Table|Format-Wide|Export-FormatData|Get-FormatData|Get-Item|Get-ChildItem|Get-Help|Add-History|Clear-History|Get-History|Invoke-History|Get-Host|Read-Host|Write-Host|Get-HotFix|Import-Clixml|Import-Csv|Invoke-Command|Invoke-Expression|Get-Item|Invoke-Item|New-Item|Remove-Item|Set-Item|Clear-ItemProperty|Copy-ItemProperty|Get-ItemProperty|Move-ItemProperty|New-ItemProperty|Remove-ItemProperty|Rename-ItemProperty|Set-ItemProperty|Get-Job|Receive-Job|Remove-Job|Start-Job|Stop-Job|Wait-Job|Stop-Process|Update-List|Get-Location|Pop-Location|Push-Location|Set-Location|Send-MailMessage|Add-Member|Get-Member|Move-Item|Compare-Object|Group-Object|Measure-Object|New-Object|Select-Object|Sort-Object|Where-Object|Out-Default|Out-File|Out-GridView|Out-Host|Out-Null|Out-Printer|Out-String|Convert-Path|Join-Path|Resolve-Path|Split-Path|Test-Path|Get-Pfxcertificate|Pop-Location|Push-Location|Get-Process|Start-Process|Stop-Process|Wait-Process|Enable-PSBreakpoint|Disable-PSBreakpoint|Get-PSBreakpoint|Set-PSBreakpoint|Remove-PSBreakpoint|Get-PSDrive|New-PSDrive|Remove-PSDrive|Get-PSProvider|Set-PSdebug|Enter-PSSession|Exit-PSSession|Export-PSSession|Get-PSSession|Import-PSSession|New-PSSession|Remove-PSSession|Disable-PSSessionConfiguration|Enable-PSSessionConfiguration|Get-PSSessionConfiguration|Register-PSSessionConfiguration|Set-PSSessionConfiguration|Unregister-PSSessionConfiguration|New-PSSessionOption|Add-PsSnapIn|Get-PsSnapin|Remove-PSSnapin|Get-Random|Read-Host|Remove-Item|Rename-Item|Rename-ItemProperty|Select-Object|Select-XML|Send-MailMessage|Get-Service|New-Service|Restart-Service|Resume-Service|Set-Service|Start-Service|Stop-Service|Suspend-Service|Sort-Object|Start-Sleep|ConvertFrom-StringData|Select-String|Tee-Object|New-Timespan|Trace-Command|Get-Tracesource|Set-Tracesource|Start-Transaction|Complete-Transaction|Get-Transaction|Use-Transaction|Undo-Transaction|Start-Transcript|Stop-Transcript|Add-Type|Update-TypeData|Get-Uiculture|Get-Unique|Update-Formatdata|Update-Typedata|Clear-Variable|Get-Variable|New-Variable|Remove-Variable|Set-Variable|New-WebServiceProxy|Where-Object|Write-Debug|Write-Error|Write-Host|Write-Output|Write-Progress|Write-Verbose|Write-Warning|Set-WmiInstance|Invoke-WmiMethod|Get-WmiObject|Remove-WmiObject|Connect-WSMan|Disconnect-WSMan|Test-WSMan|Invoke-WSManAction|Disable-WSManCredSSP|Enable-WSManCredSSP|Get-WSManCredSSP|New-WSManInstance|Get-WSManInstance|Set-WSManInstance|Remove-WSManInstance|Set-WSManQuickConfig|New-WSManSessionOption".split("|")),c="eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains|ieq|ine|ige|igt|ile|ilt|ilike|inotlike|imatch|inotmatch|ireplace|icontains|inotcontains|is|isnot|as|and|or|band|bor|not";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"[$](?:[Tt]rue|[Ff]alse)\\b"},{token:"constant.language",regex:"[$][Nn]ull\\b"},{token:"variable.instance",regex:"[$][a-zA-Z][a-zA-Z0-9_]*\\b"},{token:function(c){return a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b"},{token:"keyword.operator",regex:"\\-(?:"+c+")"},{token:"keyword.operator",regex:"&|\\*|\\+|\\-|\\=|\\+=|\\-="},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PowershellHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/powershell",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/powershell_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./powershell_highlight_rules").PowershellHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./behaviour/cstyle").CstyleBehaviour,j=a("./folding/cstyle").FoldMode,k=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new i,this.foldingRules=new j};d.inherits(k,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){return null}}.call(k.prototype),b.Mode=k}),define("ace/mode/powershell_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("function|if|else|elseif|switch|while|default|for|do|until|break|continue|foreach|return|filter|in|trap|throw|param|begin|process|end".split("|")),b=e.arrayToMap("Get-Alias|Import-Alias|New-Alias|Set-Alias|Get-AuthenticodeSignature|Set-AuthenticodeSignature|Set-Location|Get-ChildItem|Clear-Item|Get-Command|Measure-Command|Trace-Command|Add-Computer|Checkpoint-Computer|Remove-Computer|Restart-Computer|Restore-Computer|Stop-Computer|Reset-ComputerMachinePassword|Test-ComputerSecureChannel|Add-Content|Get-Content|Set-Content|Clear-Content|Get-Command|Invoke-Command|Enable-ComputerRestore|Disable-ComputerRestore|Get-ComputerRestorePoint|Test-Connection|ConvertFrom-CSV|ConvertTo-CSV|ConvertTo-Html|ConvertTo-Xml|ConvertFrom-SecureString|ConvertTo-SecureString|Copy-Item|Export-Counter|Get-Counter|Import-Counter|Get-Credential|Get-Culture|Get-ChildItem|Get-Date|Set-Date|Remove-Item|Compare-Object|Get-Event|Get-WinEvent|New-Event|Remove-Event|Unregister-Event|Wait-Event|Clear-EventLog|Get-Eventlog|Limit-EventLog|New-Eventlog|Remove-EventLog|Show-EventLog|Write-EventLog|Get-EventSubscriber|Register-EngineEvent|Register-ObjectEvent|Register-WmiEvent|Get-ExecutionPolicy|Set-ExecutionPolicy|Export-Alias|Export-Clixml|Export-Console|Export-Csv|ForEach-Object|Format-Custom|Format-List|Format-Table|Format-Wide|Export-FormatData|Get-FormatData|Get-Item|Get-ChildItem|Get-Help|Add-History|Clear-History|Get-History|Invoke-History|Get-Host|Read-Host|Write-Host|Get-HotFix|Import-Clixml|Import-Csv|Invoke-Command|Invoke-Expression|Get-Item|Invoke-Item|New-Item|Remove-Item|Set-Item|Clear-ItemProperty|Copy-ItemProperty|Get-ItemProperty|Move-ItemProperty|New-ItemProperty|Remove-ItemProperty|Rename-ItemProperty|Set-ItemProperty|Get-Job|Receive-Job|Remove-Job|Start-Job|Stop-Job|Wait-Job|Stop-Process|Update-List|Get-Location|Pop-Location|Push-Location|Set-Location|Send-MailMessage|Add-Member|Get-Member|Move-Item|Compare-Object|Group-Object|Measure-Object|New-Object|Select-Object|Sort-Object|Where-Object|Out-Default|Out-File|Out-GridView|Out-Host|Out-Null|Out-Printer|Out-String|Convert-Path|Join-Path|Resolve-Path|Split-Path|Test-Path|Get-Pfxcertificate|Pop-Location|Push-Location|Get-Process|Start-Process|Stop-Process|Wait-Process|Enable-PSBreakpoint|Disable-PSBreakpoint|Get-PSBreakpoint|Set-PSBreakpoint|Remove-PSBreakpoint|Get-PSDrive|New-PSDrive|Remove-PSDrive|Get-PSProvider|Set-PSdebug|Enter-PSSession|Exit-PSSession|Export-PSSession|Get-PSSession|Import-PSSession|New-PSSession|Remove-PSSession|Disable-PSSessionConfiguration|Enable-PSSessionConfiguration|Get-PSSessionConfiguration|Register-PSSessionConfiguration|Set-PSSessionConfiguration|Unregister-PSSessionConfiguration|New-PSSessionOption|Add-PsSnapIn|Get-PsSnapin|Remove-PSSnapin|Get-Random|Read-Host|Remove-Item|Rename-Item|Rename-ItemProperty|Select-Object|Select-XML|Send-MailMessage|Get-Service|New-Service|Restart-Service|Resume-Service|Set-Service|Start-Service|Stop-Service|Suspend-Service|Sort-Object|Start-Sleep|ConvertFrom-StringData|Select-String|Tee-Object|New-Timespan|Trace-Command|Get-Tracesource|Set-Tracesource|Start-Transaction|Complete-Transaction|Get-Transaction|Use-Transaction|Undo-Transaction|Start-Transcript|Stop-Transcript|Add-Type|Update-TypeData|Get-Uiculture|Get-Unique|Update-Formatdata|Update-Typedata|Clear-Variable|Get-Variable|New-Variable|Remove-Variable|Set-Variable|New-WebServiceProxy|Where-Object|Write-Debug|Write-Error|Write-Host|Write-Output|Write-Progress|Write-Verbose|Write-Warning|Set-WmiInstance|Invoke-WmiMethod|Get-WmiObject|Remove-WmiObject|Connect-WSMan|Disconnect-WSMan|Test-WSMan|Invoke-WSManAction|Disable-WSManCredSSP|Enable-WSManCredSSP|Get-WSManCredSSP|New-WSManInstance|Get-WSManInstance|Set-WSManInstance|Remove-WSManInstance|Set-WSManQuickConfig|New-WSManSessionOption".split("|")),c="eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains|ieq|ine|ige|igt|ile|ilt|ilike|inotlike|imatch|inotmatch|ireplace|icontains|inotcontains|is|isnot|as|and|or|band|bor|not";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"[$](?:[Tt]rue|[Ff]alse)\\b"},{token:"constant.language",regex:"[$][Nn]ull\\b"},{token:"variable.instance",regex:"[$][a-zA-Z][a-zA-Z0-9_]*\\b"},{token:function(c){return a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b"},{token:"keyword.operator",regex:"\\-(?:"+c+")"},{token:"keyword.operator",regex:"&|\\*|\\+|\\-|\\=|\\+=|\\-="},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PowershellHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-python-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-python-uncompressed.js index ad0add6d775..9a12decebda 100755 --- a/apps/files_texteditor/js/aceeditor/mode-python-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-python-uncompressed.js @@ -504,13 +504,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-python.js b/apps/files_texteditor/js/aceeditor/mode-python.js index 116f838b1d9..5401407f32b 100644 --- a/apps/files_texteditor/js/aceeditor/mode-python.js +++ b/apps/files_texteditor/js/aceeditor/mode-python.js @@ -1 +1 @@ -define("ace/mode/python",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/python_highlight_rules","ace/mode/folding/pythonic","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./python_highlight_rules").PythonHighlightRules,h=a("./folding/pythonic").FoldMode,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.foldingRules=new h("\\:")};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d};var a={pass:1,"return":1,raise:1,"break":1,"continue":1};this.checkOutdent=function(b,c,d){if(d!=="\r\n"&&d!=="\r"&&d!=="\n")return!1;var e=this.$tokenizer.getLineTokens(c.trim(),b).tokens;if(!e)return!1;do var f=e.pop();while(f&&(f.type=="comment"||f.type=="text"&&f.value.match(/^\s+$/)));return f?f.type=="keyword"&&a[f.value]:!1},this.autoOutdent=function(a,b,c){c+=1;var d=this.$getIndent(b.getLine(c)),e=b.getTabString();d.slice(-e.length)==e&&b.remove(new i(c,d.length-e.length,c,d.length))}}.call(j.prototype),b.Mode=j}),define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("and|as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|raise|return|try|while|with|yield".split("|")),b=e.arrayToMap("True|False|None|NotImplemented|Ellipsis|__debug__".split("|")),c=e.arrayToMap("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|float|list|raw_input|unichr|callable|format|locals|reduce|unicode|chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|__import__|complex|hash|min|set|apply|delattr|help|next|setattr|buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern".split("|")),d=e.arrayToMap("".split("|")),f="(?:r|u|ur|R|U|UR|Ur|uR)?",g="(?:(?:[1-9]\\d*)|(?:0))",h="(?:0[oO]?[0-7]+)",i="(?:0[xX][\\dA-Fa-f]+)",j="(?:0[bB][01]+)",k="(?:"+g+"|"+h+"|"+i+"|"+j+")",l="(?:[eE][+-]?\\d+)",m="(?:\\.\\d+)",n="(?:\\d+)",o="(?:(?:"+n+"?"+m+")|(?:"+n+"\\.))",p="(?:(?:"+o+"|"+n+")"+l+")",q="(?:"+p+"|"+o+")";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:f+'"{3}(?:[^\\\\]|\\\\.)*?"{3}'},{token:"string",merge:!0,regex:f+'"{3}.*$',next:"qqstring"},{token:"string",regex:f+'"(?:[^\\\\]|\\\\.)*?"'},{token:"string",regex:f+"'{3}(?:[^\\\\]|\\\\.)*?'{3}"},{token:"string",merge:!0,regex:f+"'{3}.*$",next:"qstring"},{token:"string",regex:f+"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:"(?:"+q+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:q},{token:"constant.numeric",regex:k+"[lL]\\b"},{token:"constant.numeric",regex:k+"\\b"},{token:function(e){return a.hasOwnProperty(e)?"keyword":b.hasOwnProperty(e)?"constant.language":d.hasOwnProperty(e)?"invalid.illegal":c.hasOwnProperty(e)?"support.function":e=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"lparen.paren",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:[^\\\\]|\\\\.)*?"{3}',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?'{3}",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PythonHighlightRules=g}),define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a){this.foldingStartMarker=new RegExp("(?:([\\[{])|("+a+"))(?:\\s*)(?:#.*)?$")};d.inherits(f,e),function(){this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),e=d.match(this.foldingStartMarker);if(e)return e[1]?this.openingBracketBlock(a,e[1],c,e.index):e[2]?this.indentationBlock(a,c,e.index+e[2].length):this.indentationBlock(a,c)}}.call(f.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/python",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/python_highlight_rules","ace/mode/folding/pythonic","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./python_highlight_rules").PythonHighlightRules,h=a("./folding/pythonic").FoldMode,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.foldingRules=new h("\\:")};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d};var a={pass:1,"return":1,raise:1,"break":1,"continue":1};this.checkOutdent=function(b,c,d){if(d!=="\r\n"&&d!=="\r"&&d!=="\n")return!1;var e=this.$tokenizer.getLineTokens(c.trim(),b).tokens;if(!e)return!1;do var f=e.pop();while(f&&(f.type=="comment"||f.type=="text"&&f.value.match(/^\s+$/)));return f?f.type=="keyword"&&a[f.value]:!1},this.autoOutdent=function(a,b,c){c+=1;var d=this.$getIndent(b.getLine(c)),e=b.getTabString();d.slice(-e.length)==e&&b.remove(new i(c,d.length-e.length,c,d.length))}}.call(j.prototype),b.Mode=j}),define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("and|as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|raise|return|try|while|with|yield".split("|")),b=e.arrayToMap("True|False|None|NotImplemented|Ellipsis|__debug__".split("|")),c=e.arrayToMap("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|float|list|raw_input|unichr|callable|format|locals|reduce|unicode|chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|__import__|complex|hash|min|set|apply|delattr|help|next|setattr|buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern".split("|")),d=e.arrayToMap("".split("|")),f="(?:r|u|ur|R|U|UR|Ur|uR)?",g="(?:(?:[1-9]\\d*)|(?:0))",h="(?:0[oO]?[0-7]+)",i="(?:0[xX][\\dA-Fa-f]+)",j="(?:0[bB][01]+)",k="(?:"+g+"|"+h+"|"+i+"|"+j+")",l="(?:[eE][+-]?\\d+)",m="(?:\\.\\d+)",n="(?:\\d+)",o="(?:(?:"+n+"?"+m+")|(?:"+n+"\\.))",p="(?:(?:"+o+"|"+n+")"+l+")",q="(?:"+p+"|"+o+")";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:f+'"{3}(?:[^\\\\]|\\\\.)*?"{3}'},{token:"string",merge:!0,regex:f+'"{3}.*$',next:"qqstring"},{token:"string",regex:f+'"(?:[^\\\\]|\\\\.)*?"'},{token:"string",regex:f+"'{3}(?:[^\\\\]|\\\\.)*?'{3}"},{token:"string",merge:!0,regex:f+"'{3}.*$",next:"qstring"},{token:"string",regex:f+"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:"(?:"+q+"|\\d+)[jJ]\\b"},{token:"constant.numeric",regex:q},{token:"constant.numeric",regex:k+"[lL]\\b"},{token:"constant.numeric",regex:k+"\\b"},{token:function(e){return a.hasOwnProperty(e)?"keyword":b.hasOwnProperty(e)?"constant.language":d.hasOwnProperty(e)?"invalid.illegal":c.hasOwnProperty(e)?"support.function":e=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"lparen.paren",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}],qqstring:[{token:"string",regex:'(?:[^\\\\]|\\\\.)*?"{3}',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:[^\\\\]|\\\\.)*?'{3}",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.PythonHighlightRules=g}),define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a){this.foldingStartMarker=new RegExp("(?:([\\[{])|("+a+"))(?:\\s*)(?:#.*)?$")};d.inherits(f,e),function(){this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),e=d.match(this.foldingStartMarker);if(e)return e[1]?this.openingBracketBlock(a,e[1],c,e.index):e[2]?this.indentationBlock(a,c,e.index+e[2].length):this.indentationBlock(a,c)}}.call(f.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-ruby-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-ruby-uncompressed.js index 96de75ef8ba..fa2e06a522e 100755 --- a/apps/files_texteditor/js/aceeditor/mode-ruby-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-ruby-uncompressed.js @@ -389,13 +389,3 @@ var MatchingBraceOutdent = function() {}; exports.MatchingBraceOutdent = MatchingBraceOutdent; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-ruby.js b/apps/files_texteditor/js/aceeditor/mode-ruby.js index 2eeb69f5d5a..7b9df32177e 100644 --- a/apps/files_texteditor/js/aceeditor/mode-ruby.js +++ b/apps/files_texteditor/js/aceeditor/mode-ruby.js @@ -1 +1 @@ -define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./ruby_highlight_rules").RubyHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|gsub!|get_via_redirect|h|host!|https?|https!|include|Integer|lambda|link_to|link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|validates_inclusion_of|validates_numericality_of|validates_with|validates_each|authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|translate|localize|extract_locale_from_tld|t|l|caches_page|expire_page|caches_action|expire_action|cache|expire_fragment|expire_cache_for|observe|cache_sweeper|has_many|has_one|belongs_to|has_and_belongs_to_many".split("|")),b=e.arrayToMap("alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield".split("|")),c=e.arrayToMap("true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING".split("|")),d=e.arrayToMap("$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|$!|root_url|flash|session|cookies|params|request|response|logger".split("|"));this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"comment",merge:!0,regex:"^=begin$",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"},{token:"text",regex:"::"},{token:"variable.instancce",regex:"@{1,2}(?:[a-zA-Z_]|d)+"},{token:"variable.class",regex:"[A-Z](?:[a-zA-Z_]|d)+"},{token:"string",regex:"[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"},{token:"constant.numeric",regex:"[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="self"?"variable.language":b.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"constant.language":d.hasOwnProperty(e)?"variable.language":a.hasOwnProperty(e)?"support.function":e=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:"^=end$",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.RubyHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./ruby_highlight_rules").RubyHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(j,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[]\s*$/);g&&(d+=c)}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|gsub!|get_via_redirect|h|host!|https?|https!|include|Integer|lambda|link_to|link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|validates_inclusion_of|validates_numericality_of|validates_with|validates_each|authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|translate|localize|extract_locale_from_tld|t|l|caches_page|expire_page|caches_action|expire_action|cache|expire_fragment|expire_cache_for|observe|cache_sweeper|has_many|has_one|belongs_to|has_and_belongs_to_many".split("|")),b=e.arrayToMap("alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield".split("|")),c=e.arrayToMap("true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING".split("|")),d=e.arrayToMap("$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|$!|root_url|flash|session|cookies|params|request|response|logger".split("|"));this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"comment",merge:!0,regex:"^=begin$",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"},{token:"text",regex:"::"},{token:"variable.instancce",regex:"@{1,2}(?:[a-zA-Z_]|d)+"},{token:"variable.class",regex:"[A-Z](?:[a-zA-Z_]|d)+"},{token:"string",regex:"[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"},{token:"constant.numeric",regex:"[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="self"?"variable.language":b.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"constant.language":d.hasOwnProperty(e)?"variable.language":a.hasOwnProperty(e)?"support.function":e=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:"^=end$",next:"start"},{token:"comment",merge:!0,regex:".+"}]}};d.inherits(g,f),b.RubyHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scad-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-scad-uncompressed.js index 07e368130ef..c944ed17e17 100755 --- a/apps/files_texteditor/js/aceeditor/mode-scad-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-scad-uncompressed.js @@ -529,12 +529,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -546,7 +546,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -564,7 +564,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -589,12 +589,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -606,7 +606,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -625,14 +625,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -653,7 +654,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -662,19 +663,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -683,7 +684,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -693,7 +694,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -904,13 +906,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scad.js b/apps/files_texteditor/js/aceeditor/mode-scad.js index 1deeef11524..eb324e4dc77 100644 --- a/apps/files_texteditor/js/aceeditor/mode-scad.js +++ b/apps/files_texteditor/js/aceeditor/mode-scad.js @@ -1 +1 @@ -define("ace/mode/scad",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/scad_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./scad_highlight_rules").scadHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/scad_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("module|if|else|for".split("|")),b=e.arrayToMap("NULL".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant",regex:"<[a-zA-Z0-9.]+>"},{token:"keyword",regex:"(?:use|include)"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.scadHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);if(g!=="")return{text:'"'+g+'"',selection:!1};var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column-1,h.column);if(j=="\\")return null;var k=d.getTokens(f.start.row,f.start.row)[0].tokens,l=0,m,n=-1;for(var o=0;of.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/scad",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/scad_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./scad_highlight_rules").scadHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("./behaviour/cstyle").CstyleBehaviour,k=a("./folding/cstyle").FoldMode,l=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new j,this.foldingRules=new k};d.inherits(l,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var h=b.match(/^.*[\{\(\[]\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(l.prototype),b.Mode=l}),define("ace/mode/scad_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("module|if|else|for".split("|")),b=e.arrayToMap("NULL".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant",regex:"<[a-zA-Z0-9.]+>"},{token:"keyword",regex:"(?:use|include)"},{token:function(c){return c=="this"?"variable.language":a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.scadHighlightRules=h}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scala-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-scala-uncompressed.js index 098b14e066c..fb6e95f6f68 100755 --- a/apps/files_texteditor/js/aceeditor/mode-scala-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-scala-uncompressed.js @@ -282,12 +282,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -295,46 +303,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -342,7 +443,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -357,29 +458,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -404,7 +505,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -416,10 +517,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -431,9 +532,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -452,9 +553,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -483,28 +584,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -689,195 +794,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i selection.start.column) { break; @@ -1066,19 +983,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -1087,7 +1004,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -1097,7 +1014,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1452,13 +1370,3 @@ oop.inherits(ScalaHighlightRules, TextHighlightRules); exports.ScalaHighlightRules = ScalaHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scala.js b/apps/files_texteditor/js/aceeditor/mode-scala.js index c697fe1781a..e0ba4b537d9 100644 --- a/apps/files_texteditor/js/aceeditor/mode-scala.js +++ b/apps/files_texteditor/js/aceeditor/mode-scala.js @@ -1 +1 @@ -define("ace/mode/scala",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/scala_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./scala_highlight_rules").ScalaHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;jf.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/scala_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("case|default|do|else|for|if|match|while|throw|return|try|catch|finally|yield|abstract|class|def|extends|final|forSome|implicit|implicits|import|lazy|new|object|override|package|private|protected|sealed|super|this|trait|type|val|var|with".split("|")),b=e.arrayToMap("true|false".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object|Unit|Any|AnyVal|AnyRef|Null|ScalaObject|Singleton|Seq|Iterable|List|Option|Array|Char|Byte|Short|Int|Long|Nothing".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.ScalaHighlightRules=h}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/scala",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/tokenizer","ace/mode/scala_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript").Mode,f=a("../tokenizer").Tokenizer,g=a("./scala_highlight_rules").ScalaHighlightRules,h=function(){e.call(this),this.$tokenizer=new f((new g).getRules())};d.inherits(h,e),function(){this.createWorker=function(a){return null}}.call(h.prototype),b.Mode=h}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/scala_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./doc_comment_highlight_rules").DocCommentHighlightRules,g=a("./text_highlight_rules").TextHighlightRules,h=function(){var a=e.arrayToMap("case|default|do|else|for|if|match|while|throw|return|try|catch|finally|yield|abstract|class|def|extends|final|forSome|implicit|implicits|import|lazy|new|object|override|package|private|protected|sealed|super|this|trait|type|val|var|with".split("|")),b=e.arrayToMap("true|false".split("|")),c=e.arrayToMap("AbstractMethodError|AssertionError|ClassCircularityError|ClassFormatError|Deprecated|EnumConstantNotPresentException|ExceptionInInitializerError|IllegalAccessError|IllegalThreadStateException|InstantiationError|InternalError|NegativeArraySizeException|NoSuchFieldError|Override|Process|ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|SuppressWarnings|TypeNotPresentException|UnknownError|UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|InstantiationException|IndexOutOfBoundsException|ArrayIndexOutOfBoundsException|CloneNotSupportedException|NoSuchFieldException|IllegalArgumentException|NumberFormatException|SecurityException|Void|InheritableThreadLocal|IllegalStateException|InterruptedException|NoSuchMethodException|IllegalAccessException|UnsupportedOperationException|Enum|StrictMath|Package|Compiler|Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|Character|Boolean|StackTraceElement|Appendable|StringBuffer|Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|StackOverflowError|OutOfMemoryError|VirtualMachineError|ArrayStoreException|ClassCastException|LinkageError|NoClassDefFoundError|ClassNotFoundException|RuntimeException|Exception|ThreadDeath|Error|Throwable|System|ClassLoader|Cloneable|Class|CharSequence|Comparable|String|Object|Unit|Any|AnyVal|AnyRef|Null|ScalaObject|Singleton|Seq|Iterable|List|Option|Array|Char|Byte|Short|Int|Long|Nothing".split("|")),d=e.arrayToMap("".split("|"));this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},(new f).getStartRule("doc-start"),{token:"comment",merge:!0,regex:"\\/\\*",next:"comment"},{token:"string.regexp",regex:"[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"constant.language.boolean",regex:"(?:true|false)\\b"},{token:function(e){return e=="this"?"variable.language":a.hasOwnProperty(e)?"keyword":c.hasOwnProperty(e)?"support.function":d.hasOwnProperty(e)?"support.function":b.hasOwnProperty(e)?"constant.language":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}]},this.embedRules(f,"doc-",[(new f).getEndRule("start")])};d.inherits(h,g),b.ScalaHighlightRules=h}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scss-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-scss-uncompressed.js index 9639f0d4d2a..fc6d611f261 100755 --- a/apps/files_texteditor/js/aceeditor/mode-scss-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-scss-uncompressed.js @@ -676,13 +676,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-scss.js b/apps/files_texteditor/js/aceeditor/mode-scss.js index 3f63dc4305d..214bfe34859 100644 --- a/apps/files_texteditor/js/aceeditor/mode-scss.js +++ b/apps/files_texteditor/js/aceeditor/mode-scss.js @@ -1 +1 @@ -define("ace/mode/scss",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/scss_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./scss_highlight_rules").ScssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./folding/cstyle").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/scss_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap(function(){var a="-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-".split("|"),b="appearance|background-clip|background-inline-policy|background-origin|background-size|binding|border-bottom-colors|border-left-colors|border-right-colors|border-top-colors|border-end|border-end-color|border-end-style|border-end-width|border-image|border-start|border-start-color|border-start-style|border-start-width|box-align|box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|box-pack|box-sizing|column-count|column-gap|column-width|column-rule|column-rule-width|column-rule-style|column-rule-color|float-edge|font-feature-settings|font-language-override|force-broken-image-icon|image-region|margin-end|margin-start|opacity|outline|outline-color|outline-offset|outline-radius|outline-radius-bottomleft|outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|outline-style|outline-width|padding-end|padding-start|stack-sizing|tab-size|text-blink|text-decoration-color|text-decoration-line|text-decoration-style|transform|transform-origin|transition|transition-delay|transition-duration|transition-property|transition-timing-function|user-focus|user-input|user-modify|user-select|window-shadow|border-radius".split("|"),c="azimuth|background-attachment|background-color|background-image|background-position|background-repeat|background|border-bottom-color|border-bottom-style|border-bottom-width|border-bottom|border-collapse|border-color|border-left-color|border-left-style|border-left-width|border-left|border-right-color|border-right-style|border-right-width|border-right|border-spacing|border-style|border-top-color|border-top-style|border-top-width|border-top|border-width|border|bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|counter-reset|cue-after|cue-before|cue|cursor|direction|display|elevation|empty-cells|float|font-family|font-size-adjust|font-size|font-stretch|font-style|font-variant|font-weight|font|height|left|letter-spacing|line-height|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|marker-offset|margin|marks|max-height|max-width|min-height|min-width|opacity|orphans|outline-color|outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page|pause-after|pause-before|pause|pitch-range|pitch|play-during|position|quotes|richness|right|size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|stress|table-layout|text-align|text-decoration|text-indent|text-shadow|text-transform|top|unicode-bidi|vertical-align|visibility|voice-family|volume|white-space|widows|width|word-spacing|z-index".split("|"),d=[];for(var e=0,f=a.length;e|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.ScssHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/scss",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/scss_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./scss_highlight_rules").ScssHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("./folding/cstyle").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules(),"i"),this.$outdent=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a).tokens;if(e.length&&e[e.length-1].type=="comment")return d;var f=b.match(/^.*\{\s*$/);return f&&(d+=c),d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(j.prototype),b.Mode=j}),define("ace/mode/scss_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap(function(){var a="-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-".split("|"),b="appearance|background-clip|background-inline-policy|background-origin|background-size|binding|border-bottom-colors|border-left-colors|border-right-colors|border-top-colors|border-end|border-end-color|border-end-style|border-end-width|border-image|border-start|border-start-color|border-start-style|border-start-width|box-align|box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|box-pack|box-sizing|column-count|column-gap|column-width|column-rule|column-rule-width|column-rule-style|column-rule-color|float-edge|font-feature-settings|font-language-override|force-broken-image-icon|image-region|margin-end|margin-start|opacity|outline|outline-color|outline-offset|outline-radius|outline-radius-bottomleft|outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|outline-style|outline-width|padding-end|padding-start|stack-sizing|tab-size|text-blink|text-decoration-color|text-decoration-line|text-decoration-style|transform|transform-origin|transition|transition-delay|transition-duration|transition-property|transition-timing-function|user-focus|user-input|user-modify|user-select|window-shadow|border-radius".split("|"),c="azimuth|background-attachment|background-color|background-image|background-position|background-repeat|background|border-bottom-color|border-bottom-style|border-bottom-width|border-bottom|border-collapse|border-color|border-left-color|border-left-style|border-left-width|border-left|border-right-color|border-right-style|border-right-width|border-right|border-spacing|border-style|border-top-color|border-top-style|border-top-width|border-top|border-width|border|bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|counter-reset|cue-after|cue-before|cue|cursor|direction|display|elevation|empty-cells|float|font-family|font-size-adjust|font-size|font-stretch|font-style|font-variant|font-weight|font|height|left|letter-spacing|line-height|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|marker-offset|margin|marks|max-height|max-width|min-height|min-width|opacity|orphans|outline-color|outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page|pause-after|pause-before|pause|pitch-range|pitch|play-during|position|quotes|richness|right|size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|stress|table-layout|text-align|text-decoration|text-indent|text-shadow|text-transform|top|unicode-bidi|vertical-align|visibility|voice-family|volume|white-space|widows|width|word-spacing|z-index".split("|"),d=[];for(var e=0,f=a.length;e|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*"},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]}};d.inherits(g,f),b.ScssHighlightRules=g}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-sh-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-sh-uncompressed.js new file mode 100755 index 00000000000..c341067efb9 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-sh-uncompressed.js @@ -0,0 +1,281 @@ +/* ***** BEGIN LICENSE BLOCK ***** +* Version: MPL 1.1/GPL 2.0/LGPL 2.1 +* +* The contents of this file are subject to the Mozilla Public License Version +* 1.1 (the "License"); you may not use this file except in compliance with +* the License. You may obtain a copy of the License at +* http://www.mozilla.org/MPL/ +* +* Software distributed under the License is distributed on an "AS IS" basis, +* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +* for the specific language governing rights and limitations under the +* License. +* +* The Original Code is Ajax.org Code Editor (ACE). +* +* The Initial Developer of the Original Code is +* Ajax.org B.V. +* Portions created by the Initial Developer are Copyright (C) 2010 +* the Initial Developer. All Rights Reserved. +* +* Contributor(s): +* Rich Healey +* +* Alternatively, the contents of this file may be used under the terms of +* either the GNU General Public License Version 2 or later (the "GPL"), or +* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +* in which case the provisions of the GPL or the LGPL are applicable instead +* of those above. If you wish to allow use of your version of this file only +* under the terms of either the GPL or the LGPL, and not to allow others to +* use your version of this file under the terms of the MPL, indicate your +* decision by deleting the provisions above and replace them with the notice +* and other provisions required by the GPL or the LGPL. If you do not delete +* the provisions above, a recipient may use your version of this file under +* the terms of any one of the MPL, the GPL or the LGPL. +* +* ***** END LICENSE BLOCK ***** */ + +define('ace/mode/sh', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sh_highlight_rules', 'ace/range'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules; +var Range = require("../range").Range; + +var Mode = function() { + this.$tokenizer = new Tokenizer(new ShHighlightRules().getRules()); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.toggleCommentLines = function(state, doc, startRow, endRow) { + var outdent = true; + var re = /^(\s*)#/; + + for (var i=startRow; i<= endRow; i++) { + if (!re.test(doc.getLine(i))) { + outdent = false; + break; + } + } + + if (outdent) { + var deleteRange = new Range(0, 0, 0, 0); + for (var i=startRow; i<= endRow; i++) + { + var line = doc.getLine(i); + var m = line.match(re); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = m[0].length; + doc.replace(deleteRange, m[1]); + } + } + else { + doc.indentRows(startRow, endRow, "#"); + } + }; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.$tokenizer.getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[\:]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + var outdents = { + "pass": 1, + "return": 1, + "raise": 1, + "break": 1, + "continue": 1 + }; + + this.checkOutdent = function(state, line, input) { + if (input !== "\r\n" && input !== "\r" && input !== "\n") + return false; + + var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; + + if (!tokens) + return false; + + // ignore trailing comments + do { + var last = tokens.pop(); + } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); + + if (!last) + return false; + + return (last.type == "keyword" && outdents[last.value]); + }; + + this.autoOutdent = function(state, doc, row) { + // outdenting in sh is slightly different because it always applies + // to the next line and only of a new line is inserted + + row += 1; + var indent = this.$getIndent(doc.getLine(row)); + var tab = doc.getTabString(); + if (indent.slice(-tab.length) == tab) + doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); + }; + +}).call(Mode.prototype); + +exports.Mode = Mode; +}); +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Rich Healey + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** + */ +define('ace/mode/sh_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var ShHighlightRules = function() { + + var reservedKeywords = lang.arrayToMap( + ('!|{|}|case|do|done|elif|else|'+ + 'esac|fi|for|if|in|then|until|while|'+ + '&|;' + ).split('|') + ); + + var languageConstructs = lang.arrayToMap( + // TODO + ('echo|exit|eval|source|[|]|test|'+ + 'true|false|read' + ).split('|') + ); + + var integer = "(?:(?:[1-9]\\d*)|(?:0))"; + // var integer = "(?:" + decimalInteger + ")"; + + var fraction = "(?:\\.\\d+)"; + var intPart = "(?:\\d+)"; + var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; + var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")"; + var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; + var fileDescriptor = "(?:&" + intPart + ")"; + + var variableName = "[a-zA-Z][a-zA-Z0-9_]*"; + var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))"; + + var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))"; + + var func = "(?:" + variableName + "\\s*\\(\\))"; + + this.$rules = { + "start" : [ { + token : "comment", + regex : "#.*$" + }, { + token : "string", // " string + regex : '"(?:[^\\\\]|\\\\.)*?"' + }, { + token : "variable.language", + regex : builtinVariable + }, { + token : "variable", + regex : variable + }, { + token : "support.function", + regex : func, + }, { + token : "support.function", + regex : fileDescriptor + }, { + token : "string", // ' string + regex : "'(?:[^\\\\]|\\\\.)*?'" + }, { + token : "constant.numeric", // float + regex : floatNumber + }, { + token : "constant.numeric", // integer + regex : integer + "\\b" + }, { + token : function(value) { + if (reservedKeywords.hasOwnProperty(value)) + return "keyword"; + else if (languageConstructs.hasOwnProperty(value)) + return "constant.language"; + else if (value == "debugger") + return "invalid.deprecated"; + else + return "identifier"; + }, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!=" + }, { + token : "lparen.paren", + regex : "[\\[\\(\\{]" + }, { + token : "paren.rparen", + regex : "[\\]\\)\\}]" + }, { + token : "text", + regex : "\\s+" + } ] + }; +}; + +oop.inherits(ShHighlightRules, TextHighlightRules); + +exports.ShHighlightRules = ShHighlightRules; +}); diff --git a/apps/files_texteditor/js/aceeditor/mode-sh.js b/apps/files_texteditor/js/aceeditor/mode-sh.js new file mode 100755 index 00000000000..272aaccc850 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-sh.js @@ -0,0 +1 @@ +define("ace/mode/sh",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/sh_highlight_rules","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./sh_highlight_rules").ShHighlightRules,h=a("../range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)#/;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var i=new h(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);i.start.row=g,i.end.row=g,i.end.column=k[0].length,b.replace(i,k[1])}}else b.indentRows(c,d,"#")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"){var g=b.match(/^.*[\{\(\[\:]\s*$/);g&&(d+=c)}return d};var a={pass:1,"return":1,raise:1,"break":1,"continue":1};this.checkOutdent=function(b,c,d){if(d!=="\r\n"&&d!=="\r"&&d!=="\n")return!1;var e=this.$tokenizer.getLineTokens(c.trim(),b).tokens;if(!e)return!1;do var f=e.pop();while(f&&(f.type=="comment"||f.type=="text"&&f.value.match(/^\s+$/)));return f?f.type=="keyword"&&a[f.value]:!1},this.autoOutdent=function(a,b,c){c+=1;var d=this.$getIndent(b.getLine(c)),e=b.getTabString();d.slice(-e.length)==e&&b.remove(new h(c,d.length-e.length,c,d.length))}}.call(i.prototype),b.Mode=i}),define("ace/mode/sh_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("!|{|}|case|do|done|elif|else|esac|fi|for|if|in|then|until|while|&|;".split("|")),b=e.arrayToMap("echo|exit|eval|source|[|]|test|true|false|read".split("|")),c="(?:(?:[1-9]\\d*)|(?:0))",d="(?:\\.\\d+)",f="(?:\\d+)",g="(?:(?:"+f+"?"+d+")|(?:"+f+"\\.))",h="(?:(?:"+g+"|"+f+")"+")",i="(?:"+h+"|"+g+")",j="(?:&"+f+")",k="[a-zA-Z][a-zA-Z0-9_]*",l="(?:(?:\\$"+k+")|(?:"+k+"=))",m="(?:\\$(?:SHLVL|\\$|\\!|\\?))",n="(?:"+k+"\\s*\\(\\))";this.$rules={start:[{token:"comment",regex:"#.*$"},{token:"string",regex:'"(?:[^\\\\]|\\\\.)*?"'},{token:"variable.language",regex:m},{token:"variable",regex:l},{token:"support.function",regex:n},{token:"support.function",regex:j},{token:"string",regex:"'(?:[^\\\\]|\\\\.)*?'"},{token:"constant.numeric",regex:i},{token:"constant.numeric",regex:c+"\\b"},{token:function(c){return a.hasOwnProperty(c)?"keyword":b.hasOwnProperty(c)?"constant.language":c=="debugger"?"invalid.deprecated":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!="},{token:"lparen.paren",regex:"[\\[\\(\\{]"},{token:"paren.rparen",regex:"[\\]\\)\\}]"},{token:"text",regex:"\\s+"}]}};d.inherits(g,f),b.ShHighlightRules=g}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-sql-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-sql-uncompressed.js index 61195988d98..e56ac4cb119 100755 --- a/apps/files_texteditor/js/aceeditor/mode-sql-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-sql-uncompressed.js @@ -157,13 +157,3 @@ oop.inherits(SqlHighlightRules, TextHighlightRules); exports.SqlHighlightRules = SqlHighlightRules; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-sql.js b/apps/files_texteditor/js/aceeditor/mode-sql.js index 3ca95359086..e81fadfb369 100755 --- a/apps/files_texteditor/js/aceeditor/mode-sql.js +++ b/apps/files_texteditor/js/aceeditor/mode-sql.js @@ -1 +1 @@ -define("ace/mode/sql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/sql_highlight_rules","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./sql_highlight_rules").SqlHighlightRules,h=a("../range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=[],g=/^(\s*)--/;for(var i=c;i<=d;i++)if(!g.test(b.getLine(i))){e=!1;break}if(e){var j=new h(0,0,0,0);for(var i=c;i<=d;i++){var k=b.getLine(i),l=k.match(g);j.start.row=i,j.end.row=i,j.end.column=l[0].length,b.replace(j,l[1])}}else b.indentRows(c,d,"--")}}.call(i.prototype),b.Mode=i}),define("ace/mode/sql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("select|from|where|and|or|group|by|order|limit|offset|having|as|case|when|else|end|type|left|right|join|on|outer|desc|asc".split("|")),b=e.arrayToMap("true|false|null".split("|")),c=e.arrayToMap("count|min|max|avg|sum|rank|now|coalesce".split("|"));this.$rules={start:[{token:"comment",regex:"--.*$"},{token:"string",regex:'".*"'},{token:"string",regex:"'.*'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(d){return d=d.toLowerCase(),a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"lparen.paren",regex:"[\\(]"},{token:"paren.rparen",regex:"[\\)]"},{token:"text",regex:"\\s+"}]}};d.inherits(g,f),b.SqlHighlightRules=g}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/sql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/sql_highlight_rules","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./sql_highlight_rules").SqlHighlightRules,h=a("../range").Range,i=function(){this.$tokenizer=new f((new g).getRules())};d.inherits(i,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=[],g=/^(\s*)--/;for(var i=c;i<=d;i++)if(!g.test(b.getLine(i))){e=!1;break}if(e){var j=new h(0,0,0,0);for(var i=c;i<=d;i++){var k=b.getLine(i),l=k.match(g);j.start.row=i,j.end.row=i,j.end.column=l[0].length,b.replace(j,l[1])}}else b.indentRows(c,d,"--")}}.call(i.prototype),b.Mode=i}),define("ace/mode/sql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("select|from|where|and|or|group|by|order|limit|offset|having|as|case|when|else|end|type|left|right|join|on|outer|desc|asc".split("|")),b=e.arrayToMap("true|false|null".split("|")),c=e.arrayToMap("count|min|max|avg|sum|rank|now|coalesce".split("|"));this.$rules={start:[{token:"comment",regex:"--.*$"},{token:"string",regex:'".*"'},{token:"string",regex:"'.*'"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:function(d){return d=d.toLowerCase(),a.hasOwnProperty(d)?"keyword":b.hasOwnProperty(d)?"constant.language":c.hasOwnProperty(d)?"support.function":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="},{token:"lparen.paren",regex:"[\\(]"},{token:"paren.rparen",regex:"[\\)]"},{token:"text",regex:"\\s+"}]}};d.inherits(g,f),b.SqlHighlightRules=g}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-svg-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-svg-uncompressed.js index 8d3bb3b873a..1025d99bd3c 100755 --- a/apps/files_texteditor/js/aceeditor/mode-svg-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-svg-uncompressed.js @@ -202,6 +202,9 @@ var XmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -209,6 +212,9 @@ var XmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -302,7 +308,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : '["].*', - next : state + "-qqstring" + next : state + "_qqstring" }, { token : "string", regex : "'.*?'" @@ -310,7 +316,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : "['].*", - next : state + "-qstring" + next : state + "_qstring" }]; } @@ -358,18 +364,18 @@ exports.tag = function(states, name, nextState) { } }, merge : true, - regex : "[-_a-zA-Z0-9:!]+", - next : name + "embed-attribute-list" + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" }, { token: "empty", regex: "", - next : name + "embed-attribute-list" + next : name + "_embed_attribute_list" }]; - states[name + "-qstring"] = multiLineString("'", name + "embed-attribute-list"); - states[name + "-qqstring"] = multiLineString("\"", name + "embed-attribute-list"); + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); - states[name + "embed-attribute-list"] = [{ + states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", @@ -535,12 +541,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -552,7 +558,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -570,7 +576,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -595,12 +601,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -612,7 +618,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -631,14 +637,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -659,7 +666,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -668,19 +675,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -689,7 +696,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -699,7 +706,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -1336,12 +1344,20 @@ var JavaScriptHighlightRules = function() { ); // TODO: Unicode escape sequences - var identifierRe = "[" + unicode.packages.L + "\\$_][" + var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; - + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-6][0-7]?|" + // oct + "37[0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used @@ -1349,46 +1365,139 @@ var JavaScriptHighlightRules = function() { "start" : [ { token : "comment", - regex : "\\/\\/.*$" + regex : /\/\/.*$/ }, new DocCommentHighlightRules().getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, - regex : "\\/\\*", + regex : /\/\*/, next : "comment" }, { - token : "string", // single line - regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' - }, { - token : "string", // multi line string start - merge : true, - regex : '["].*\\\\$', - next : "qqstring" - }, { - token : "string", // single line - regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + token : "string", + regex : "'", + next : "qstring" }, { - token : "string", // multi line string start - merge : true, - regex : "['].*\\\\$", - next : "qstring" + token : "string", + regex : '"', + next : "qqstring" }, { token : "constant.numeric", // hex - regex : "0[xX][0-9a-fA-F]+\\b" + regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float - regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" - }, { - token : ["keyword.definition", "text", "entity.name.function"], - regex : "(function)(\\s+)(" + identifierRe + ")" + regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { // match stuff like: Sound.prototype.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: Sound.prototype.play = myfunc + token : [ + "storage.type", + "punctuation.operator", + "support.function", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)" + }, { // match stuff like: Sound.play = function() { } + token : [ + "storage.type", + "punctuation.operator", + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: play = function() { } + token : [ + "entity.name.function", + "text", + "keyword.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // match regular function like: function myFunc(arg) { } + token : [ + "storage.type", + "text", + "entity.name.function", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()(.*?)(\\))" + }, { // match stuff like: foobar: function() { } + token : [ + "entity.name.function", + "text", + "punctuation.operator", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()(.*?)(\\))" + }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) + token : [ + "text", + "text", + "storage.type", + "text", + "paren.lparen", + "variable.parameter", + "paren.rparen" + ], + regex : "(:)(\\s*)(function)?(\\s*)(\\()([^)]*)(\\))" }, { token : "constant.language.boolean", - regex : "(?:true|false)\\b" + regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" + }, { + token : ["punctuation.operator", "support.function"], + regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : ["punctuation.operator", "support.function.dom"], + regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : ["punctuation.operator", "support.constant"], + regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) @@ -1396,7 +1505,7 @@ var JavaScriptHighlightRules = function() { else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) - return "keyword.definition"; + return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) @@ -1411,29 +1520,29 @@ var JavaScriptHighlightRules = function() { regex : identifierRe }, { token : "keyword.operator", - regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)", + regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\;|\\.", + regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", - regex : "[[({]", + regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", - regex : "[\\])}]" + regex : /[\])}]/ }, { token : "keyword.operator", - regex : "\\/=?", + regex : /\/=?/, next : "regex_allowed" }, { token: "comment", - regex: "^#!.*$" + regex: /^#!.*$/ }, { token : "text", - regex : "\\s+" + regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This @@ -1458,7 +1567,7 @@ var JavaScriptHighlightRules = function() { }, { // immediately return to the start mode without matching // anything - token: "empty", + token: "empty", regex: "", next: "start" } @@ -1470,10 +1579,10 @@ var JavaScriptHighlightRules = function() { next: "regex" }, { // flag - token: "string.regexp", + token: "string.regexp", regex: "/\\w*", next: "start", - merge: true + merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", @@ -1485,9 +1594,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "regex_character_class": [ @@ -1506,9 +1615,9 @@ var JavaScriptHighlightRules = function() { next: "regex_character_class", merge: true }, { - token: "empty", + token: "empty", regex: "", - next: "start" + next: "start" } ], "comment_regex_allowed" : [ @@ -1537,28 +1646,32 @@ var JavaScriptHighlightRules = function() { ], "qqstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', - next : "start" + regex : '[^"\\\\]+' }, { token : "string", - merge : true, - regex : '.+' + regex : '"', + next : "start" } ], "qstring" : [ { + token : "constant.language.escape", + regex : escapedRe + }, { token : "string", - regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", - next : "start" + regex : "[^'\\\\]+" }, { token : "string", - merge : true, - regex : '.+' + regex : "'", + next : "start" } ] }; - + this.embedRules(DocCommentHighlightRules, "doc-", [ new DocCommentHighlightRules().getEndRule("start") ]); }; @@ -1743,195 +1856,6 @@ var MatchingBraceOutdent = function() {}; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Fabian Jakobs - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { -"use strict"; - -var oop = require("../lib/oop"); -var EventEmitter = require("../lib/event_emitter").EventEmitter; - -var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { - - this.changeListener = this.changeListener.bind(this); - - if (module.packaged) { - var base = this.$guessBasePath(); - this.$worker = new Worker(base + packagedJs); - } - else { - var workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); - this.$worker = new Worker(workerUrl); - - var tlns = {}; - for (var i=0; i"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"-qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"-qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:!]+",next:b+"embed-attribute-list"},{token:"empty",regex:"",next:b+"embed-attribute-list"}],a[b+"-qstring"]=h("'",b+"embed-attribute-list"),a[b+"-qqstring"]=h('"',b+"embed-attribute-list"),a[b+"embed-attribute-list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="f.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)",next:"regex_allowed"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\.",next:"regex_allowed"},{token:"paren.lparen",regex:"[[({]",next:"regex_allowed"},{token:"paren.rparen",regex:"[\\])}]"},{token:"keyword.operator",regex:"\\/=?",next:"regex_allowed"},{token:"comment",regex:"^#!.*$"},{token:"text",regex:"\\s+"}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",merge:!0,regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",merge:!0,regex:".+"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/event_emitter").EventEmitter,f=function(b,d,e,f){this.changeListener=this.changeListener.bind(this);if(c.packaged){var g=this.$guessBasePath();this.$worker=new Worker(g+d)}else{var h=this.$normalizePath(a.nameToUrl("ace/worker/worker",null,"_"));this.$worker=new Worker(h);var i={};for(var j=0;j)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}])};d.inherits(h,f),b.SvgHighlightRules=h}),define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a,b){this.defaultMode=a,this.subModes=b};d.inherits(f,e),function(){this.$getMode=function(a){for(var b in this.subModes)if(a.indexOf(b)===0)return this.subModes[b];return null},this.$tryMode=function(a,b,c,d){var e=this.$getMode(a);return e?e.getFoldWidget(b,c,d):""},this.getFoldWidget=function(a,b,c){return this.$tryMode(a.getState(c-1),a,b,c)||this.$tryMode(a.getState(c),a,b,c)||this.defaultMode.getFoldWidget(a,b,c)},this.getFoldWidgetRange=function(a,b,c){var d=this.$getMode(a.getState(c-1));if(!d||!d.getFoldWidget(a,b,c))d=this.$getMode(a.getState(c));if(!d||!d.getFoldWidget(a,b,c))d=this.defaultMode;return d.getFoldWidgetRange(a,b,c)}}.call(f.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/svg",["require","exports","module","ace/lib/oop","ace/mode/xml","ace/mode/javascript","ace/tokenizer","ace/mode/svg_highlight_rules","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml").Mode,f=a("./javascript").Mode,g=a("../tokenizer").Tokenizer,h=a("./svg_highlight_rules").SvgHighlightRules,i=a("./folding/mixed").FoldMode,j=a("./folding/xml").FoldMode,k=a("./folding/cstyle").FoldMode,l=function(){e.call(this),this.highlighter=new h,this.$tokenizer=new g(this.highlighter.getRules()),this.$embeds=this.highlighter.getEmbeds(),this.createModeDelegates({"js-":f}),this.foldingRules=new i(new j({}),{"js-":new k})};d.inherits(l,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(l.prototype),b.Mode=l}),define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="g.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}),define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./javascript_highlight_rules").JavaScriptHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=a("../range").Range,j=a("../worker/worker_client").WorkerClient,k=a("./behaviour/cstyle").CstyleBehaviour,l=a("./folding/cstyle").FoldMode,m=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h,this.$behaviour=new k,this.foldingRules=new l};d.inherits(m,e),function(){this.toggleCommentLines=function(a,b,c,d){var e=!0,f=/^(\s*)\/\//;for(var g=c;g<=d;g++)if(!f.test(b.getLine(g))){e=!1;break}if(e){var h=new i(0,0,0,0);for(var g=c;g<=d;g++){var j=b.getLine(g),k=j.match(f);h.start.row=g,h.end.row=g,h.end.column=k[0].length,b.replace(h,k[1])}}else b.indentRows(c,d,"//")},this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=this.$tokenizer.getLineTokens(b,a),f=e.tokens,g=e.state;if(f.length&&f[f.length-1].type=="comment")return d;if(a=="start"||a=="regex_allowed"){var h=b.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);h&&(d+=c)}else if(a=="doc-start"){if(g=="start"||a=="regex_allowed")return"";var h=b.match(/^\s*(\/?)\*/);h&&(h[1]&&(d+=" "),d+="* ")}return d},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)},this.createWorker=function(a){var b=new j(["ace"],"worker-javascript.js","ace/mode/javascript_worker","JavaScriptWorker");return b.attachToDocument(a.getDocument()),b.on("jslint",function(b){var c=[];for(var d=0;d=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,next:"regex_allowed"},{token:"punctuation.operator",regex:/\?|\:|\,|\;|\./,next:"regex_allowed"},{token:"paren.lparen",regex:/[\[({]/,next:"regex_allowed"},{token:"paren.rparen",regex:/[\])}]/},{token:"keyword.operator",regex:/\/=?/,next:"regex_allowed"},{token:"comment",regex:/^#!.*$/},{token:"text",regex:/\s+/}],regex_allowed:[{token:"comment",merge:!0,regex:"\\/\\*",next:"comment_regex_allowed"},{token:"comment",regex:"\\/\\/.*$"},{token:"string.regexp",regex:"\\/",next:"regex",merge:!0},{token:"text",regex:"\\s+"},{token:"empty",regex:"",next:"start"}],regex:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex"},{token:"string.regexp",regex:"/\\w*",next:"start",merge:!0},{token:"string.regexp",regex:"[^\\\\/\\[]+",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"\\[",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],regex_character_class:[{token:"regexp.keyword.operator",regex:"\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)",next:"regex_character_class"},{token:"string.regexp.charachterclass",regex:"]",next:"regex",merge:!0},{token:"string.regexp.charachterclass",regex:"[^\\\\\\]]+",next:"regex_character_class",merge:!0},{token:"empty",regex:"",next:"start"}],comment_regex_allowed:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"regex_allowed"},{token:"comment",merge:!0,regex:".+"}],comment:[{token:"comment",regex:".*?\\*\\/",merge:!0,next:"start"},{token:"comment",merge:!0,regex:".+"}],qqstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:'[^"\\\\]+'},{token:"string",regex:'"',next:"start"}],qstring:[{token:"constant.language.escape",regex:l},{token:"string",regex:"[^'\\\\]+"},{token:"string",regex:"'",next:"start"}]},this.embedRules(g,"doc-",[(new g).getEndRule("start")])};d.inherits(i,h),b.JavaScriptHighlightRules=i}),define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc",merge:!0,regex:"\\s+"},{token:"comment.doc",merge:!0,regex:"TODO"},{token:"comment.doc",merge:!0,regex:"[^@\\*]+"},{token:"comment.doc",merge:!0,regex:"."}]}};d.inherits(f,e),function(){this.getStartRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\/\\*(?=\\*)",next:a}},this.getEndRule=function(a){return{token:"comment.doc",merge:!0,regex:"\\*\\/",next:a}}}.call(f.prototype),b.DocCommentHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../range").Range,f=a("./fold_mode").FoldMode,g=b.FoldMode=function(){};d.inherits(g,f),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(a,b,c){var d=a.getLine(c),f=d.match(this.foldingStartMarker);if(f){var g=f.index;if(f[1])return this.openingBracketBlock(a,f[1],c,g);var h=a.getCommentFoldRange(c,g+f[0].length);return h.end.column-=2,h}if(b!=="markbeginend")return;var f=d.match(this.foldingStopMarker);if(f){var g=f.index+f[0].length;if(f[2]){var h=a.getCommentFoldRange(c,g);return h.end.column-=2,h}var i={row:c,column:g},j=a.$findOpeningBracket(f[1],i);if(!j)return;return j.column++,i.column--,e.fromPoints(j,i)}}}.call(g.prototype)}),define("ace/mode/svg_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/xml_util"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./javascript_highlight_rules").JavaScriptHighlightRules,f=a("./xml_highlight_rules").XmlHighlightRules,g=a("./xml_util"),h=function(){f.call(this),this.$rules.start.splice(3,0,{token:"meta.tag",regex:"<(?=s*script)",next:"script"}),g.tag(this.$rules,"script","js-start"),this.embedRules(e,"js-",[{token:"comment",regex:"\\/\\/.*(?=<\\/script>)",next:"tag"},{token:"meta.tag",regex:"<\\/(?=script)",next:"tag"}])};d.inherits(h,f),b.SvgHighlightRules=h}),define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("./fold_mode").FoldMode,f=b.FoldMode=function(a,b){this.defaultMode=a,this.subModes=b};d.inherits(f,e),function(){this.$getMode=function(a){for(var b in this.subModes)if(a.indexOf(b)===0)return this.subModes[b];return null},this.$tryMode=function(a,b,c,d){var e=this.$getMode(a);return e?e.getFoldWidget(b,c,d):""},this.getFoldWidget=function(a,b,c){return this.$tryMode(a.getState(c-1),a,b,c)||this.$tryMode(a.getState(c),a,b,c)||this.defaultMode.getFoldWidget(a,b,c)},this.getFoldWidgetRange=function(a,b,c){var d=this.$getMode(a.getState(c-1));if(!d||!d.getFoldWidget(a,b,c))d=this.$getMode(a.getState(c));if(!d||!d.getFoldWidget(a,b,c))d=this.defaultMode;return d.getFoldWidgetRange(a,b,c)}}.call(f.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-text-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-text-uncompressed.js new file mode 100755 index 00000000000..e69de29bb2d diff --git a/apps/files_texteditor/js/aceeditor/mode-text.js b/apps/files_texteditor/js/aceeditor/mode-text.js new file mode 100755 index 00000000000..e69de29bb2d diff --git a/apps/files_texteditor/js/aceeditor/mode-textile-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-textile-uncompressed.js index 8512479596e..37a85c316ec 100755 --- a/apps/files_texteditor/js/aceeditor/mode-textile-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-textile-uncompressed.js @@ -252,13 +252,3 @@ var MatchingBraceOutdent = function() {}; exports.MatchingBraceOutdent = MatchingBraceOutdent; }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-textile.js b/apps/files_texteditor/js/aceeditor/mode-textile.js index ad30c2d579e..3b36437c493 100644 --- a/apps/files_texteditor/js/aceeditor/mode-textile.js +++ b/apps/files_texteditor/js/aceeditor/mode-textile.js @@ -1 +1 @@ -define("ace/mode/textile",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/textile_highlight_rules","ace/mode/matching_brace_outdent"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./textile_highlight_rules").TextileHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(i,e),function(){this.getNextLineIndent=function(a,b,c){return a=="intag"?c:""},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(i.prototype),b.Mode=i}),define("ace/mode/textile_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:function(a){return a.match(/^h\d$/)?"markup.heading."+a.charAt(1):"markup.heading"},regex:"h1|h2|h3|h4|h5|h6|bq|p|bc|pre",next:"blocktag"},{token:"keyword",regex:"[\\*]+|[#]+"},{token:"text",regex:".+"}],blocktag:[{token:"keyword",regex:"\\. ",next:"start"},{token:"keyword",regex:"\\(",next:"blocktagproperties"}],blocktagproperties:[{token:"keyword",regex:"\\)",next:"blocktag"},{token:"string",regex:"[a-zA-Z0-9\\-_]+"},{token:"keyword",regex:"#"}]}};d.inherits(f,e),b.TextileHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};((function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}})).call(e.prototype),b.MatchingBraceOutdent=e}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/textile",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/textile_highlight_rules","ace/mode/matching_brace_outdent"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./textile_highlight_rules").TextileHighlightRules,h=a("./matching_brace_outdent").MatchingBraceOutdent,i=function(){this.$tokenizer=new f((new g).getRules()),this.$outdent=new h};d.inherits(i,e),function(){this.getNextLineIndent=function(a,b,c){return a=="intag"?c:""},this.checkOutdent=function(a,b,c){return this.$outdent.checkOutdent(b,c)},this.autoOutdent=function(a,b,c){this.$outdent.autoOutdent(b,c)}}.call(i.prototype),b.Mode=i}),define("ace/mode/textile_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text_highlight_rules").TextHighlightRules,f=function(){this.$rules={start:[{token:function(a){return a.match(/^h\d$/)?"markup.heading."+a.charAt(1):"markup.heading"},regex:"h1|h2|h3|h4|h5|h6|bq|p|bc|pre",next:"blocktag"},{token:"keyword",regex:"[\\*]+|[#]+"},{token:"text",regex:".+"}],blocktag:[{token:"keyword",regex:"\\. ",next:"start"},{token:"keyword",regex:"\\(",next:"blocktagproperties"}],blocktagproperties:[{token:"keyword",regex:"\\)",next:"blocktag"},{token:"string",regex:"[a-zA-Z0-9\\-_]+"},{token:"keyword",regex:"#"}]}};d.inherits(f,e),b.TextileHighlightRules=f}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../range").Range,e=function(){};(function(){this.checkOutdent=function(a,b){return/^\s+$/.test(a)?/^\s*\}/.test(b):!1},this.autoOutdent=function(a,b){var c=a.getLine(b),e=c.match(/^(\s*\})/);if(!e)return 0;var f=e[1].length,g=a.findMatchingBracket({row:b,column:f});if(!g||g.row==b)return 0;var h=this.$getIndent(a.getLine(g.row));a.replace(new d(b,0,b,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""}}).call(e.prototype),b.MatchingBraceOutdent=e}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-xml-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-xml-uncompressed.js index bc27c17f55b..e1af69123b2 100755 --- a/apps/files_texteditor/js/aceeditor/mode-xml-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/mode-xml-uncompressed.js @@ -124,6 +124,9 @@ var XmlHighlightRules = function() { merge : true, regex : "<\\!--", next : "comment" + }, { + token : "xml_pe", + regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", @@ -131,6 +134,9 @@ var XmlHighlightRules = function() { }, { token : "text", regex : "\\s+" + }, { + token : "constant.character.entity", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" @@ -224,7 +230,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : '["].*', - next : state + "-qqstring" + next : state + "_qqstring" }, { token : "string", regex : "'.*?'" @@ -232,7 +238,7 @@ function string(state) { token : "string", // multi line string start merge : true, regex : "['].*", - next : state + "-qstring" + next : state + "_qstring" }]; } @@ -280,18 +286,18 @@ exports.tag = function(states, name, nextState) { } }, merge : true, - regex : "[-_a-zA-Z0-9:!]+", - next : name + "embed-attribute-list" + regex : "[-_a-zA-Z0-9:]+", + next : name + "_embed_attribute_list" }, { token: "empty", regex: "", - next : name + "embed-attribute-list" + next : name + "_embed_attribute_list" }]; - states[name + "-qstring"] = multiLineString("'", name + "embed-attribute-list"); - states[name + "-qqstring"] = multiLineString("\"", name + "embed-attribute-list"); + states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); + states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); - states[name + "embed-attribute-list"] = [{ + states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", @@ -457,12 +463,12 @@ var CstyleBehaviour = function () { return { text: '{' + selected + '}', selection: false - } + }; } else { return { text: '{}', selection: [1, 1] - } + }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); @@ -474,7 +480,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } else if (text == "\n") { @@ -492,7 +498,7 @@ var CstyleBehaviour = function () { return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] - } + }; } } }); @@ -517,12 +523,12 @@ var CstyleBehaviour = function () { return { text: '(' + selected + ')', selection: false - } + }; } else { return { text: '()', selection: [1, 1] - } + }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); @@ -534,7 +540,7 @@ var CstyleBehaviour = function () { return { text: '', selection: [1, 1] - } + }; } } } @@ -553,14 +559,15 @@ var CstyleBehaviour = function () { }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { - if (text == '"') { + if (text == '"' || text == "'") { + var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { - text: '"' + selected + '"', + text: quote + selected + quote, selection: false - } + }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); @@ -581,7 +588,7 @@ var CstyleBehaviour = function () { if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { - quotepos = token.value.indexOf('"'); + quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; @@ -590,19 +597,19 @@ var CstyleBehaviour = function () { } // Try and be smart about when we auto insert. - if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf('"') === token.value.length-1)))) { + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { - text: '""', + text: quote + quote, selection: [1,1] - } + }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); - if (rightChar == '"') { + if (rightChar == quote) { return { text: '', selection: [1, 1] - } + }; } } } @@ -611,7 +618,7 @@ var CstyleBehaviour = function () { this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '"') { + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { @@ -621,7 +628,8 @@ var CstyleBehaviour = function () { } }); -} +}; + oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; @@ -999,13 +1007,3 @@ var FoldMode = exports.FoldMode = function() {}; }).call(FoldMode.prototype); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-xml.js b/apps/files_texteditor/js/aceeditor/mode-xml.js index 236ab2430eb..27c038a13b9 100644 --- a/apps/files_texteditor/js/aceeditor/mode-xml.js +++ b/apps/files_texteditor/js/aceeditor/mode-xml.js @@ -1 +1 @@ -define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"-qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"-qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:!]+",next:b+"embed-attribute-list"},{token:"empty",regex:"",next:b+"embed-attribute-list"}],a[b+"-qstring"]=h("'",b+"embed-attribute-list"),a[b+"-qqstring"]=h('"',b+"embed-attribute-list"),a[b+"embed-attribute-list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="f.start.column)break;l+=k[o].value.length}if(!m||n<0&&m.type!=="comment"&&(m.type!=="string"||f.start.column!==m.value.length+l-1&&m.value.lastIndexOf('"')===m.value.length-1))return{text:'""',selection:[1,1]};if(m&&m.type==="string"){var p=i.substring(h.column,h.column+1);if(p=='"')return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=='"'){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};((function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}})).call(e.prototype)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xml_highlight_rules").XmlHighlightRules,h=a("./behaviour/xml").XmlBehaviour,i=a("./folding/xml").FoldMode,j=function(){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h,this.foldingRules=new i};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){return this.$getIndent(b)}}.call(j.prototype),b.Mode=j}),define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/xml_util","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./xml_util"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",merge:!0,regex:"<\\!--",next:"comment"},{token:"xml_pe",regex:"<\\!.*?>"},{token:"meta.tag",regex:"<\\/?",next:"tag"},{token:"text",regex:"\\s+"},{token:"constant.character.entity",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"text",regex:"[^<]+"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",merge:!0,regex:".+"}]},e.tag(this.$rules,"tag","start")};d.inherits(g,f),b.XmlHighlightRules=g}),define("ace/mode/xml_util",["require","exports","module","ace/lib/lang"],function(a,b,c){function g(a){return[{token:"string",regex:'".*?"'},{token:"string",merge:!0,regex:'["].*',next:a+"_qqstring"},{token:"string",regex:"'.*?'"},{token:"string",merge:!0,regex:"['].*",next:a+"_qstring"}]}function h(a,b){return[{token:"string",merge:!0,regex:".*?"+a,next:b},{token:"string",merge:!0,regex:".+"}]}"use strict";var d=a("../lib/lang"),e=d.arrayToMap("button|form|input|label|select|textarea".split("|")),f=d.arrayToMap("table|tbody|td|tfoot|th|tr".split("|"));b.tag=function(a,b,c){a[b]=[{token:"text",regex:"\\s+"},{token:function(a){return a==="a"?"meta.tag.anchor":a==="img"?"meta.tag.image":a==="script"?"meta.tag.script":a==="style"?"meta.tag.style":e.hasOwnProperty(a.toLowerCase())?"meta.tag.form":f.hasOwnProperty(a.toLowerCase())?"meta.tag.table":"meta.tag"},merge:!0,regex:"[-_a-zA-Z0-9:]+",next:b+"_embed_attribute_list"},{token:"empty",regex:"",next:b+"_embed_attribute_list"}],a[b+"_qstring"]=h("'",b+"_embed_attribute_list"),a[b+"_qqstring"]=h('"',b+"_embed_attribute_list"),a[b+"_embed_attribute_list"]=[{token:"meta.tag",merge:!0,regex:"/?>",next:c},{token:"keyword.operator",regex:"="},{token:"entity.other.attribute-name",regex:"[-_a-zA-Z0-9:]+"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"text",regex:"\\s+"}].concat(g(b))}}),define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(){this.inherit(f,["string_dquotes"]),this.add("brackets","insertion",function(a,b,c,d,e){if(e=="<"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?!1:{text:"<>",selection:[1,1]}}if(e==">"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==">")return{text:"",selection:[1,1]}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),k=i.substring(h.column,h.column+2);if(k=="g.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}),define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../../lib/lang"),f=a("../../range").Range,g=a("./fold_mode").FoldMode,h=a("../../token_iterator").TokenIterator,i=b.FoldMode=function(a){g.call(this),this.voidElements=a||{}};d.inherits(i,g),function(){this.getFoldWidget=function(a,b,c){var d=this._getFirstTagInLine(a,c);return d.closing?b=="markbeginend"?"end":"":!d.tagName||this.voidElements[d.tagName.toLowerCase()]?"":d.selfClosing?"":d.value.indexOf("/"+d.tagName)!==-1?"":"start"},this._getFirstTagInLine=function(a,b){var c=a.getTokens(b,b)[0].tokens,d="";for(var f=0;f?)/,this._parseTag=function(a){var b=this.tagRe.exec(a),c=this.tagRe.lastIndex||0;return this.tagRe.lastIndex=0,{value:a,match:b?b[2]:"",closing:b?!!b[3]:!1,selfClosing:b?!!b[5]||b[2]=="/>":!1,tagName:b?b[4]:"",column:b[1]?c+b[1].length:c}},this._readTagForward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){if(!d)var d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()};c+=b.value;if(c.indexOf(">")!==-1){var e=this._parseTag(c);return e.start=d,e.end={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length},a.stepForward(),e}}while(b=a.stepForward());return null},this._readTagBackward=function(a){var b=a.getCurrentToken();if(!b)return null;var c="",d;do if(b.type.indexOf("meta.tag")===0){d||(d={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()+b.value.length}),c=b.value+c;if(c.indexOf("<")!==-1){var e=this._parseTag(c);return e.end=d,e.start={row:a.getCurrentTokenRow(),column:a.getCurrentTokenColumn()},a.stepBackward(),e}}while(b=a.stepBackward());return null},this._pop=function(a,b){while(a.length){var c=a[a.length-1];if(!b||c.tagName==b.tagName)return a.pop();if(this.voidElements[b.tagName])return;if(this.voidElements[c.tagName]){a.pop();continue}return null}},this.getFoldWidgetRange=function(a,b,c){var d=this._getFirstTagInLine(a,c);if(!d.match)return null;var e=d.closing||d.selfClosing,g=[],i;if(!e){var j=new h(a,c,d.column),k={row:c,column:d.column+d.tagName.length+2};while(i=this._readTagForward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(i.closing){this._pop(g,i);if(g.length==0)return f.fromPoints(k,i.start)}else g.push(i)}}else{var j=new h(a,c,d.column+d.match.length),l={row:c,column:d.column};while(i=this._readTagBackward(j)){if(i.selfClosing){if(!g.length)return i.start.column+=i.tagName.length+2,i.end.column-=2,f.fromPoints(i.start,i.end);continue}if(!i.closing){this._pop(g,i);if(g.length==0)return i.start.column+=i.tagName.length+2,f.fromPoints(i.start,l)}else g.push(i)}}}}.call(i.prototype)}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(a,b,c){"use strict";var d=a("../../range").Range,e=b.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(a,b,c){var d=a.getLine(c);return this.foldingStartMarker.test(d)?"start":b=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(d)?"end":""},this.getFoldWidgetRange=function(a,b,c){return null},this.indentationBlock=function(a,b,c){var e=/^\s*/,f=b,g=b,h=a.getLine(b),i=c||h.length,j=h.match(e)[0].length,k=a.getLength();while(++bf){var m=a.getLine(g).length;return new d(f,i,g,m)}},this.openingBracketBlock=function(a,b,c,e){var f={row:c,column:e+1},g=a.$findClosingBracket(b,f);if(!g)return;var h=a.foldWidgets[g.row];return h==null&&(h=this.getFoldWidget(a,g.row)),h=="start"&&(g.row--,g.column=a.getLine(g.row).length),d.fromPoints(f,g)}}).call(e.prototype)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-xquery-uncompressed.js b/apps/files_texteditor/js/aceeditor/mode-xquery-uncompressed.js new file mode 100755 index 00000000000..69effad6e21 --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-xquery-uncompressed.js @@ -0,0 +1,540 @@ +/* + * eXide - web-based XQuery IDE + * + * Copyright (C) 2011 Wolfgang Meier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +define('ace/mode/xquery', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xquery_highlight_rules', 'ace/mode/behaviour/xquery', 'ace/range'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var XQueryHighlightRules = require("./xquery_highlight_rules").XQueryHighlightRules; +var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour; +var Range = require("../range").Range; + +var Mode = function(parent) { + this.$tokenizer = new Tokenizer(new XQueryHighlightRules().getRules()); + this.$behaviour = new XQueryBehaviour(parent); +}; + +oop.inherits(Mode, TextMode); + +(function() { + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/); + if (match) + indent += tab; + return indent; + }; + + this.checkOutdent = function(state, line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*[\}\)]/.test(input); + }; + + this.autoOutdent = function(state, doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*[\}\)])/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + var match = line.match(/^(\s+)/); + if (match) { + return match[1]; + } + + return ""; + }; + + this.toggleCommentLines = function(state, doc, startRow, endRow) { + var i, line; + var outdent = true; + var re = /^\s*\(:(.*):\)/; + + for (i=startRow; i<= endRow; i++) { + if (!re.test(doc.getLine(i))) { + outdent = false; + break; + } + } + + var range = new Range(0, 0, 0, 0); + for (i=startRow; i<= endRow; i++) { + line = doc.getLine(i); + range.start.row = i; + range.end.row = i; + range.end.column = line.length; + + doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)"); + } + }; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); +/* + * eXide - web-based XQuery IDE + * + * Copyright (C) 2011 Wolfgang Meier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +define('ace/mode/xquery_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var lang = require("../lib/lang"); +var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; + +var XQueryHighlightRules = function() { + + var keywords = lang.arrayToMap( + ("return|for|let|where|order|by|declare|function|variable|xquery|version|option|namespace|import|module|when|encoding|" + + "switch|default|try|catch|group|tumbling|sliding|window|start|end|at|only|" + + "using|stemming|" + + "while|" + + "external|" + + "if|then|else|as|and|or|typeswitch|case|ascending|descending|empty|in|count|updating|insert|delete|replace|value|node|attribute|text|element|into|of|with|contains").split("|") + ); + + // regexp must not have capturing parentheses + // regexps are ordered -> the first match is used + + this.$rules = { + start : [ { + token : "text", + regex : "<\\!\\[CDATA\\[", + next : "cdata" + }, { + token : "xml_pe", + regex : "<\\?.*?\\?>" + }, { + token : "comment", + regex : "<\\!--", + next : "comment" + }, { + token : "comment", + regex : "\\(:", + next : "comment" + }, { + token : "text", // opening tag + regex : "<\\/?", + next : "tag" + }, { + token : "constant", // number + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "variable", // variable + regex : "\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b" + }, { + token: "string", + regex : '".*?"' + }, { + token: "string", + regex : "'.*?'" + }, { + token : "text", + regex : "\\s+" + }, { + token: "support.function", + regex: "\\w[\\w+_\\-:]+(?=\\()" + }, { + token : function(value) { + if (keywords[value]) + return "keyword"; + else + return "identifier"; + }, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token: "keyword.operator", + regex: "\\*|=|<|>|\\-|\\+|and|or|eq|ne|lt|gt" + }, { + token: "lparen", + regex: "[[({]" + }, { + token: "rparen", + regex: "[\\])}]" + } ], + + tag : [ { + token : "text", + regex : ">", + next : "start" + }, { + token : "meta.tag", + regex : "[-_a-zA-Z0-9:]+" + }, { + token : "text", + regex : "\\s+" + }, { + token : "string", + regex : '".*?"' + }, { + token : "string", + regex : "'.*?'" + } ], + + cdata : [ { + token : "text", + regex : "\\]\\]>", + next : "start" + }, { + token : "text", + regex : "\\s+" + }, { + token : "text", + regex : "(?:[^\\]]|\\](?!\\]>))+" + } ], + + comment : [ { + token : "comment", + regex : ".*?-->", + next : "start" + }, { + token: "comment", + regex : ".*:\\)", + next : "start" + }, { + token : "comment", + regex : ".+" + } ] + }; +}; + +oop.inherits(XQueryHighlightRules, TextHighlightRules); + +exports.XQueryHighlightRules = XQueryHighlightRules; +}); +/* +* eXide - web-based XQuery IDE +* +* Copyright (C) 2011 Wolfgang Meier +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 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 General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ +define('ace/mode/behaviour/xquery', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { +"use strict"; + + var oop = require("../../lib/oop"); + var Behaviour = require('../behaviour').Behaviour; + var CstyleBehaviour = require('./cstyle').CstyleBehaviour; + + var XQueryBehaviour = function (parent) { + + this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour + this.parent = parent; + + this.add("brackets", "insertion", function (state, action, editor, session, text) { + if (text == "\n") { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChars = line.substring(cursor.column, cursor.column + 2); + if (rightChars == ' 0 && line.charAt(cursor.column - 1) == "<") { + line = line.substring(0, cursor.column) + "/" + line.substring(cursor.column); + var lines = session.doc.getAllLines(); + lines[cursor.row] = line; + // call mode helper to close the tag if possible + parent.exec("closeTag", lines.join(session.doc.getNewLineCharacter()), cursor.row); + } + } + return false; + }); + } + oop.inherits(XQueryBehaviour, Behaviour); + + exports.XQueryBehaviour = XQueryBehaviour; +}); +/* vim:ts=4:sts=4:sw=4: + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Ajax.org Code Editor (ACE). + * + * The Initial Developer of the Original Code is + * Ajax.org B.V. + * Portions created by the Initial Developer are Copyright (C) 2010 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Chris Spencer + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { +"use strict"; + +var oop = require("../../lib/oop"); +var Behaviour = require('../behaviour').Behaviour; + +var CstyleBehaviour = function () { + + this.add("braces", "insertion", function (state, action, editor, session, text) { + if (text == '{') { + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "") { + return { + text: '{' + selected + '}', + selection: false + }; + } else { + return { + text: '{}', + selection: [1, 1] + }; + } + } else if (text == '}') { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == '}') { + var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null) { + return { + text: '', + selection: [1, 1] + }; + } + } + } else if (text == "\n") { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == '}') { + var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); + if (!openBracePos) + return null; + + var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); + var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); + + return { + text: '\n' + indent + '\n' + next_indent, + selection: [1, indent.length, 1, indent.length] + }; + } + } + }); + + this.add("braces", "deletion", function (state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '{') { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.end.column, range.end.column + 1); + if (rightChar == '}') { + range.end.column++; + return range; + } + } + }); + + this.add("parens", "insertion", function (state, action, editor, session, text) { + if (text == '(') { + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "") { + return { + text: '(' + selected + ')', + selection: false + }; + } else { + return { + text: '()', + selection: [1, 1] + }; + } + } else if (text == ')') { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == ')') { + var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null) { + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("parens", "deletion", function (state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '(') { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == ')') { + range.end.column++; + return range; + } + } + }); + + this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { + if (text == '"' || text == "'") { + var quote = text; + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "") { + return { + text: quote + selected + quote, + selection: false + }; + } else { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var leftChar = line.substring(cursor.column-1, cursor.column); + + // We're escaped. + if (leftChar == '\\') { + return null; + } + + // Find what token we're inside. + var tokens = session.getTokens(selection.start.row, selection.start.row)[0].tokens; + var col = 0, token; + var quotepos = -1; // Track whether we're inside an open quote. + + for (var x = 0; x < tokens.length; x++) { + token = tokens[x]; + if (token.type == "string") { + quotepos = -1; + } else if (quotepos < 0) { + quotepos = token.value.indexOf(quote); + } + if ((token.value.length + col) > selection.start.column) { + break; + } + col += tokens[x].value.length; + } + + // Try and be smart about when we auto insert. + if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { + return { + text: quote + quote, + selection: [1,1] + }; + } else if (token && token.type === "string") { + // Ignore input and move right one if we're typing over the closing quote. + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == quote) { + return { + text: '', + selection: [1, 1] + }; + } + } + } + } + }); + + this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == '"') { + range.end.column++; + return range; + } + } + }); + +}; + +oop.inherits(CstyleBehaviour, Behaviour); + +exports.CstyleBehaviour = CstyleBehaviour; +}); \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/mode-xquery.js b/apps/files_texteditor/js/aceeditor/mode-xquery.js new file mode 100755 index 00000000000..cb6fb87cc6a --- /dev/null +++ b/apps/files_texteditor/js/aceeditor/mode-xquery.js @@ -0,0 +1 @@ +define("ace/mode/xquery",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/xquery_highlight_rules","ace/mode/behaviour/xquery","ace/range"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("./text").Mode,f=a("../tokenizer").Tokenizer,g=a("./xquery_highlight_rules").XQueryHighlightRules,h=a("./behaviour/xquery").XQueryBehaviour,i=a("../range").Range,j=function(a){this.$tokenizer=new f((new g).getRules()),this.$behaviour=new h(a)};d.inherits(j,e),function(){this.getNextLineIndent=function(a,b,c){var d=this.$getIndent(b),e=b.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/);return e&&(d+=c),d},this.checkOutdent=function(a,b,c){return/^\s+$/.test(b)?/^\s*[\}\)]/.test(c):!1},this.autoOutdent=function(a,b,c){var d=b.getLine(c),e=d.match(/^(\s*[\}\)])/);if(!e)return 0;var f=e[1].length,g=b.findMatchingBracket({row:c,column:f});if(!g||g.row==c)return 0;var h=this.$getIndent(b.getLine(g.row));b.replace(new i(c,0,c,f-1),h)},this.$getIndent=function(a){var b=a.match(/^(\s+)/);return b?b[1]:""},this.toggleCommentLines=function(a,b,c,d){var e,f,g=!0,h=/^\s*\(:(.*):\)/;for(e=c;e<=d;e++)if(!h.test(b.getLine(e))){g=!1;break}var j=new i(0,0,0,0);for(e=c;e<=d;e++)f=b.getLine(e),j.start.row=e,j.end.row=e,j.end.column=f.length,b.replace(j,g?f.match(h)[1]:"(:"+f+":)")}}.call(j.prototype),b.Mode=j}),define("ace/mode/xquery_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(a,b,c){"use strict";var d=a("../lib/oop"),e=a("../lib/lang"),f=a("./text_highlight_rules").TextHighlightRules,g=function(){var a=e.arrayToMap("return|for|let|where|order|by|declare|function|variable|xquery|version|option|namespace|import|module|when|encoding|switch|default|try|catch|group|tumbling|sliding|window|start|end|at|only|using|stemming|while|external|if|then|else|as|and|or|typeswitch|case|ascending|descending|empty|in|count|updating|insert|delete|replace|value|node|attribute|text|element|into|of|with|contains".split("|"));this.$rules={start:[{token:"text",regex:"<\\!\\[CDATA\\[",next:"cdata"},{token:"xml_pe",regex:"<\\?.*?\\?>"},{token:"comment",regex:"<\\!--",next:"comment"},{token:"comment",regex:"\\(:",next:"comment"},{token:"text",regex:"<\\/?",next:"tag"},{token:"constant",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},{token:"variable",regex:"\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b"},{token:"string",regex:'".*?"'},{token:"string",regex:"'.*?'"},{token:"text",regex:"\\s+"},{token:"support.function",regex:"\\w[\\w+_\\-:]+(?=\\()"},{token:function(b){return a[b]?"keyword":"identifier"},regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"\\*|=|<|>|\\-|\\+|and|or|eq|ne|lt|gt"},{token:"lparen",regex:"[[({]"},{token:"rparen",regex:"[\\])}]"}],tag:[{token:"text",regex:">",next:"start"},{token:"meta.tag",regex:"[-_a-zA-Z0-9:]+"},{token:"text",regex:"\\s+"},{token:"string",regex:'".*?"'},{token:"string",regex:"'.*?'"}],cdata:[{token:"text",regex:"\\]\\]>",next:"start"},{token:"text",regex:"\\s+"},{token:"text",regex:"(?:[^\\]]|\\](?!\\]>))+"}],comment:[{token:"comment",regex:".*?-->",next:"start"},{token:"comment",regex:".*:\\)",next:"start"},{token:"comment",regex:".+"}]}};d.inherits(g,f),b.XQueryHighlightRules=g}),define("ace/mode/behaviour/xquery",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=a("./cstyle").CstyleBehaviour,g=function(a){this.inherit(f,["braces","parens","string_dquotes"]),this.parent=a,this.add("brackets","insertion",function(a,b,c,d,e){if(e=="\n"){var f=c.getCursorPosition(),g=d.doc.getLine(f.row),h=g.substring(f.column,f.column+2);if(h=="0&&h.charAt(g.column-1)=="<"){h=h.substring(0,g.column)+"/"+h.substring(g.column);var i=e.doc.getAllLines();i[g.row]=h,a.exec("closeTag",i.join(e.doc.getNewLineCharacter()),g.row)}}return!1})};d.inherits(g,e),b.XQueryBehaviour=g}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour"],function(a,b,c){"use strict";var d=a("../../lib/oop"),e=a("../behaviour").Behaviour,f=function(){this.add("braces","insertion",function(a,b,c,d,e){if(e=="{"){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"{"+g+"}",selection:!1}:{text:"{}",selection:[1,1]}}if(e=="}"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var k=d.$findOpeningBracket("}",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}else if(e=="\n"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j=="}"){var l=d.findMatchingBracket({row:h.row,column:h.column+1});if(!l)return null;var m=this.getNextLineIndent(a,i.substring(0,i.length-1),d.getTabString()),n=this.$getIndent(d.doc.getLine(l.row));return{text:"\n"+m+"\n"+n,selection:[1,m.length,1,m.length]}}}}),this.add("braces","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="{"){var g=d.doc.getLine(e.start.row),h=g.substring(e.end.column,e.end.column+1);if(h=="}")return e.end.column++,e}}),this.add("parens","insertion",function(a,b,c,d,e){if(e=="("){var f=c.getSelectionRange(),g=d.doc.getTextRange(f);return g!==""?{text:"("+g+")",selection:!1}:{text:"()",selection:[1,1]}}if(e==")"){var h=c.getCursorPosition(),i=d.doc.getLine(h.row),j=i.substring(h.column,h.column+1);if(j==")"){var k=d.$findOpeningBracket(")",{column:h.column+1,row:h.row});if(k!==null)return{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&f=="("){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h==")")return e.end.column++,e}}),this.add("string_dquotes","insertion",function(a,b,c,d,e){if(e=='"'||e=="'"){var f=e,g=c.getSelectionRange(),h=d.doc.getTextRange(g);if(h!=="")return{text:f+h+f,selection:!1};var i=c.getCursorPosition(),j=d.doc.getLine(i.row),k=j.substring(i.column-1,i.column);if(k=="\\")return null;var l=d.getTokens(g.start.row,g.start.row)[0].tokens,m=0,n,o=-1;for(var p=0;pg.start.column)break;m+=l[p].value.length}if(!n||o<0&&n.type!=="comment"&&(n.type!=="string"||g.start.column!==n.value.length+m-1&&n.value.lastIndexOf(f)===n.value.length-1))return{text:f+f,selection:[1,1]};if(n&&n.type==="string"){var q=j.substring(i.column,i.column+1);if(q==f)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(a,b,c,d,e){var f=d.doc.getTextRange(e);if(!e.isMultiLine()&&(f=='"'||f=="'")){var g=d.doc.getLine(e.start.row),h=g.substring(e.start.column+1,e.start.column+2);if(h=='"')return e.end.column++,e}})};d.inherits(f,e),b.CstyleBehaviour=f}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/theme-clouds-uncompressed.js b/apps/files_texteditor/js/aceeditor/theme-clouds-uncompressed.js index 0c0445151b5..03048077b70 100755 --- a/apps/files_texteditor/js/aceeditor/theme-clouds-uncompressed.js +++ b/apps/files_texteditor/js/aceeditor/theme-clouds-uncompressed.js @@ -35,7 +35,7 @@ * * ***** END LICENSE BLOCK ***** */ -define('ace/theme/clouds', ['require', 'exports', 'module' ], function(require, exports, module) { +define('ace/theme/clouds', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-clouds"; @@ -68,14 +68,14 @@ exports.cssText = "\ }\ \ .ace-clouds .ace_cursor {\ - border-left: 2px solid #000000;\ + border-left: 1px solid #000000;\ }\ \ .ace-clouds .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ - \ +\ .ace-clouds .ace_marker-layer .ace_selection {\ background: #BDD5FC;\ }\ @@ -96,12 +96,12 @@ exports.cssText = "\ .ace-clouds .ace_marker-layer .ace_selected_word {\ border: 1px solid #BDD5FC;\ }\ - \ +\ .ace-clouds .ace_invisible {\ color: #BFBFBF;\ }\ \ -.ace-clouds .ace_keyword {\ +.ace-clouds .ace_keyword, .ace-clouds .ace_meta {\ color:#AF956F;\ }\ \ @@ -130,6 +130,10 @@ exports.cssText = "\ color:#C52727;\ }\ \ +.ace-clouds .ace_storage {\ + color:#C52727;\ +}\ +\ .ace-clouds .ace_string {\ color:#5D90CD;\ }\ @@ -146,17 +150,6 @@ exports.cssText = "\ text-decoration:underline;\ }"; -var dom = require("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); - + var dom = require("../lib/dom"); + dom.importCssString(exports.cssText, exports.cssClass); }); -; - (function() { - window.require(["ace/ace"], function(a) { - if (!window.ace) - window.ace = {}; - for (var key in a) if (a.hasOwnProperty(key)) - ace[key] = a[key]; - }); - })(); - \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/theme-clouds.js b/apps/files_texteditor/js/aceeditor/theme-clouds.js index 78a1d5b5e5c..de651e6c597 100644 --- a/apps/files_texteditor/js/aceeditor/theme-clouds.js +++ b/apps/files_texteditor/js/aceeditor/theme-clouds.js @@ -1 +1 @@ -define("ace/theme/clouds",["require","exports","module"],function(a,b,c){b.isDark=!1,b.cssClass="ace-clouds",b.cssText=".ace-clouds .ace_editor { border: 2px solid rgb(159, 159, 159);}.ace-clouds .ace_editor.ace_focus { border: 2px solid #327fbd;}.ace-clouds .ace_gutter { background: #e8e8e8; color: #333;}.ace-clouds .ace_print_margin { width: 1px; background: #e8e8e8;}.ace-clouds .ace_scroller { background-color: #FFFFFF;}.ace-clouds .ace_text-layer { cursor: text; color: #000000;}.ace-clouds .ace_cursor { border-left: 2px solid #000000;}.ace-clouds .ace_cursor.ace_overwrite { border-left: 0px; border-bottom: 1px solid #000000;} .ace-clouds .ace_marker-layer .ace_selection { background: #BDD5FC;}.ace-clouds .ace_marker-layer .ace_step { background: rgb(198, 219, 174);}.ace-clouds .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid #BFBFBF;}.ace-clouds .ace_marker-layer .ace_active_line { background: #FFFBD1;}.ace-clouds .ace_marker-layer .ace_selected_word { border: 1px solid #BDD5FC;} .ace-clouds .ace_invisible { color: #BFBFBF;}.ace-clouds .ace_keyword { color:#AF956F;}.ace-clouds .ace_keyword.ace_operator { color:#484848;}.ace-clouds .ace_constant.ace_language { color:#39946A;}.ace-clouds .ace_constant.ace_numeric { color:#46A609;}.ace-clouds .ace_invalid { background-color:#FF002A;}.ace-clouds .ace_fold { background-color: #AF956F; border-color: #000000;}.ace-clouds .ace_support.ace_function { color:#C52727;}.ace-clouds .ace_string { color:#5D90CD;}.ace-clouds .ace_comment { color:#BCC8BA;}.ace-clouds .ace_entity.ace_other.ace_attribute-name { color:#606060;}.ace-clouds .ace_markup.ace_underline { text-decoration:underline;}";var d=a("../lib/dom");d.importCssString(b.cssText,b.cssClass)}),function(){window.require(["ace/ace"],function(a){window.ace||(window.ace={});for(var b in a)a.hasOwnProperty(b)&&(ace[b]=a[b])})}() \ No newline at end of file +define("ace/theme/clouds",["require","exports","module","ace/lib/dom"],function(a,b,c){b.isDark=!1,b.cssClass="ace-clouds",b.cssText=".ace-clouds .ace_editor { border: 2px solid rgb(159, 159, 159);}.ace-clouds .ace_editor.ace_focus { border: 2px solid #327fbd;}.ace-clouds .ace_gutter { background: #e8e8e8; color: #333;}.ace-clouds .ace_print_margin { width: 1px; background: #e8e8e8;}.ace-clouds .ace_scroller { background-color: #FFFFFF;}.ace-clouds .ace_text-layer { cursor: text; color: #000000;}.ace-clouds .ace_cursor { border-left: 1px solid #000000;}.ace-clouds .ace_cursor.ace_overwrite { border-left: 0px; border-bottom: 1px solid #000000;}.ace-clouds .ace_marker-layer .ace_selection { background: #BDD5FC;}.ace-clouds .ace_marker-layer .ace_step { background: rgb(198, 219, 174);}.ace-clouds .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid #BFBFBF;}.ace-clouds .ace_marker-layer .ace_active_line { background: #FFFBD1;}.ace-clouds .ace_marker-layer .ace_selected_word { border: 1px solid #BDD5FC;}.ace-clouds .ace_invisible { color: #BFBFBF;}.ace-clouds .ace_keyword, .ace-clouds .ace_meta { color:#AF956F;}.ace-clouds .ace_keyword.ace_operator { color:#484848;}.ace-clouds .ace_constant.ace_language { color:#39946A;}.ace-clouds .ace_constant.ace_numeric { color:#46A609;}.ace-clouds .ace_invalid { background-color:#FF002A;}.ace-clouds .ace_fold { background-color: #AF956F; border-color: #000000;}.ace-clouds .ace_support.ace_function { color:#C52727;}.ace-clouds .ace_storage { color:#C52727;}.ace-clouds .ace_string { color:#5D90CD;}.ace-clouds .ace_comment { color:#BCC8BA;}.ace-clouds .ace_entity.ace_other.ace_attribute-name { color:#606060;}.ace-clouds .ace_markup.ace_underline { text-decoration:underline;}";var d=a("../lib/dom");d.importCssString(b.cssText,b.cssClass)}) \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/worker-coffee.js b/apps/files_texteditor/js/aceeditor/worker-coffee.js index d47238ceb7d..704ee4f3228 100644 --- a/apps/files_texteditor/js/aceeditor/worker-coffee.js +++ b/apps/files_texteditor/js/aceeditor/worker-coffee.js @@ -198,7 +198,7 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; - if (match) { + if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { @@ -263,7 +263,8 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex return -1; }; -});// vim: ts=4 sts=4 sw=4 expandtab +}); +// vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA @@ -1538,10 +1539,10 @@ exports.implement = function(proto, mixin) { * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ - + define('ace/mode/coffee_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/coffee/coffee-script'], function(require, exports, module) { "use strict"; - + var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var coffee = require("../mode/coffee/coffee-script"); @@ -1557,29 +1558,29 @@ var Worker = exports.Worker = function(sender) { oop.inherits(Worker, Mirror); (function() { - + this.onUpdate = function() { var value = this.doc.getValue(); - + try { coffee.parse(value); } catch(e) { var m = e.message.match(/Parse error on line (\d+): (.*)/); if (m) { this.sender.emit("error", { - row: parseInt(m[1]) - 1, + row: parseInt(m[1], 10) - 1, column: null, text: m[2], type: "error" }); return; } - + if (e instanceof SyntaxError) { var m = e.message.match(/ on line (\d+)/); - if (m) { + if (m) { this.sender.emit("error", { - row: parseInt(m[1]) - 1, + row: parseInt(m[1], 10) - 1, column: null, text: e.message.replace(m[0], ""), type: "error" @@ -1590,7 +1591,7 @@ oop.inherits(Worker, Mirror); } this.sender.emit("ok"); }; - + }).call(Worker.prototype); });define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { @@ -1810,11 +1811,12 @@ var Document = function(text) { }; this.insert = function(position, text) { - if (text.length == 0) + if (!text || text.length === 0) return position; position = this.$clipPosition(position); + // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); @@ -2094,7 +2096,7 @@ var Range = function(startRow, startColumn, endRow, endColumn) { }; (function() { - this.isEequal = function(range) { + this.isEqual = function(range) { return this.start.row == range.start.row && this.end.row == range.end.row && this.start.column == range.start.column && @@ -2160,6 +2162,11 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } + this.intersectsRange = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + } + this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } @@ -2319,6 +2326,21 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return Range.fromPoints(start || this.start, end || this.end); }; + this.fixOrientation = function() { + if ( + this.start.row < this.end.row + || (this.start.row == this.end.row && this.start.column < this.end.column) + ) { + return false; + } + + var temp = this.start; + this.end = this.start; + this.start = temp; + return true; + }; + + this.isEmpty = function() { return (this.start.row == this.end.row && this.start.column == this.end.column); }; @@ -2766,7 +2788,7 @@ define('ace/mode/coffee/coffee-script', ['require', 'exports', 'module' , 'ace/m }; });/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -2790,26 +2812,25 @@ define('ace/mode/coffee/coffee-script', ['require', 'exports', 'module' , 'ace/m */ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coffee/rewriter', 'ace/mode/coffee/helpers'], function(require, exports, module) { - - var ASSIGNED, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref; - var __indexOf = Array.prototype.indexOf || function(item) { - for (var i = 0, l = this.length; i < l; i++) { - if (this[i] === item) return i; - } - return -1; - }; - Rewriter = require('./rewriter').Rewriter; - _ref = require('./helpers'), count = _ref.count, starts = _ref.starts, compact = _ref.compact, last = _ref.last; +// Generated by CoffeeScript 1.2.1-pre + + var BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref, _ref1, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + _ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES; + + _ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last; + exports.Lexer = Lexer = (function() { + + Lexer.name = 'Lexer'; + function Lexer() {} + Lexer.prototype.tokenize = function(code, opts) { - var i; - if (opts == null) { - opts = {}; - } - if (WHITESPACE.test(code)) { - code = "\n" + code; - } + var i, tag; + if (opts == null) opts = {}; + if (WHITESPACE.test(code)) code = "\n" + code; code = code.replace(/\r/g, '').replace(TRAILING_SPACES, ''); this.code = code; this.line = opts.line || 0; @@ -2817,22 +2838,21 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff this.indebt = 0; this.outdebt = 0; this.indents = []; + this.ends = []; this.tokens = []; i = 0; while (this.chunk = code.slice(i)) { i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken(); } this.closeIndentation(); - if (opts.rewrite === false) { - return this.tokens; - } + if (tag = this.ends.pop()) this.error("missing " + tag); + if (opts.rewrite === false) return this.tokens; return (new Rewriter).rewrite(this.tokens); }; + Lexer.prototype.identifierToken = function() { var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3; - if (!(match = IDENTIFIER.exec(this.chunk))) { - return 0; - } + if (!(match = IDENTIFIER.exec(this.chunk))) return 0; input = match[0], id = match[1], colon = match[2]; if (id === 'own' && this.tag() === 'FOR') { this.token('OWN', id); @@ -2840,7 +2860,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@'); tag = 'IDENTIFIER'; - if (__indexOf.call(JS_KEYWORDS, id) >= 0 || !forcedIdentifier && __indexOf.call(COFFEE_KEYWORDS, id) >= 0) { + if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) { tag = id.toUpperCase(); if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) { tag = 'LEADING_WHEN'; @@ -2869,13 +2889,11 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff id = new String(id); id.reserved = true; } else if (__indexOf.call(RESERVED, id) >= 0) { - this.identifierError(id); + this.error("reserved word \"" + id + "\""); } } if (!forcedIdentifier) { - if (__indexOf.call(COFFEE_ALIASES, id) >= 0) { - id = COFFEE_ALIAS_MAP[id]; - } + if (__indexOf.call(COFFEE_ALIASES, id) >= 0) id = COFFEE_ALIAS_MAP[id]; tag = (function() { switch (id) { case '!': @@ -2893,7 +2911,6 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff return 'BOOL'; case 'break': case 'continue': - case 'debugger': return 'STATEMENT'; default: return tag; @@ -2901,33 +2918,43 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff })(); } this.token(tag, id); - if (colon) { - this.token(':', ':'); - } + if (colon) this.token(':', ':'); return input.length; }; + Lexer.prototype.numberToken = function() { - var match, number; - if (!(match = NUMBER.exec(this.chunk))) { - return 0; - } + var binaryLiteral, lexedLength, match, number, octalLiteral; + if (!(match = NUMBER.exec(this.chunk))) return 0; number = match[0]; + if (/E/.test(number)) { + this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'"); + } else if (/[BOX]/.test(number)) { + this.error("radix prefix '" + number + "' must be lowercase"); + } else if (/^0[89]/.test(number)) { + this.error("decimal literal '" + number + "' must not be prefixed with '0'"); + } else if (/^0[0-7]/.test(number)) { + this.error("octal literal '" + number + "' must be prefixed with '0o'"); + } + lexedLength = number.length; + if (octalLiteral = /0o([0-7]+)/.exec(number)) { + number = (parseInt(octalLiteral[1], 8)).toString(); + } + if (binaryLiteral = /0b([01]+)/.exec(number)) { + number = (parseInt(binaryLiteral[1], 2)).toString(); + } this.token('NUMBER', number); - return number.length; + return lexedLength; }; + Lexer.prototype.stringToken = function() { - var match, string; + var match, octalEsc, string; switch (this.chunk.charAt(0)) { case "'": - if (!(match = SIMPLESTR.exec(this.chunk))) { - return 0; - } + if (!(match = SIMPLESTR.exec(this.chunk))) return 0; this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n')); break; case '"': - if (!(string = this.balancedString(this.chunk, '"'))) { - return 0; - } + if (!(string = this.balancedString(this.chunk, '"'))) return 0; if (0 < string.indexOf('#{', 1)) { this.interpolateString(string.slice(1, -1)); } else { @@ -2937,14 +2964,16 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff default: return 0; } + if (octalEsc = /^(?:\\.|[^\\])*\\[0-7]/.test(string)) { + this.error("octal escape sequences " + string + " are not allowed"); + } this.line += count(string, '\n'); return string.length; }; + Lexer.prototype.heredocToken = function() { var doc, heredoc, match, quote; - if (!(match = HEREDOC.exec(this.chunk))) { - return 0; - } + if (!(match = HEREDOC.exec(this.chunk))) return 0; heredoc = match[0]; quote = heredoc.charAt(0); doc = this.sanitizeHeredoc(match[2], { @@ -2961,22 +2990,21 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff this.line += count(heredoc, '\n'); return heredoc.length; }; + Lexer.prototype.commentToken = function() { var comment, here, match; - if (!(match = this.chunk.match(COMMENT))) { - return 0; - } + if (!(match = this.chunk.match(COMMENT))) return 0; comment = match[0], here = match[1]; if (here) { this.token('HERECOMMENT', this.sanitizeHeredoc(here, { herecomment: true, indent: Array(this.indent + 1).join(' ') })); - this.token('TERMINATOR', '\n'); } this.line += count(comment, '\n'); return comment.length; }; + Lexer.prototype.jsToken = function() { var match, script; if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) { @@ -2985,31 +3013,37 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff this.token('JS', (script = match[0]).slice(1, -1)); return script.length; }; + Lexer.prototype.regexToken = function() { - var match, prev, regex, _ref2; - if (this.chunk.charAt(0) !== '/') { - return 0; - } + var flags, length, match, prev, regex, _ref2, _ref3; + if (this.chunk.charAt(0) !== '/') return 0; if (match = HEREGEX.exec(this.chunk)) { - this.line += count(match[0], '\n'); - return this.heregexToken(match); + length = this.heregexToken(match); + this.line += count(match[0], '\n'); + return length; } prev = last(this.tokens); if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) { return 0; } - if (!(match = REGEX.exec(this.chunk))) { - return 0; + if (!(match = REGEX.exec(this.chunk))) return 0; + _ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2]; + if (regex.slice(0, 2) === '/*') { + this.error('regular expressions cannot begin with `*`'); } - regex = match[0]; - this.token('REGEX', regex === '//' ? '/(?:)/' : regex); - return regex.length; + if (regex === '//') regex = '/(?:)/'; + this.token('REGEX', "" + regex + flags); + return match.length; }; + Lexer.prototype.heregexToken = function(match) { var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5; heregex = match[0], body = match[1], flags = match[2]; if (0 > body.indexOf('#{')) { re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/'); + if (re.match(/^\*/)) { + this.error('regular expressions cannot begin with `*`'); + } this.token('REGEX', "/" + (re || '(?:)') + "/" + flags); return heregex.length; } @@ -3024,9 +3058,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff if (tag === 'TOKENS') { tokens.push.apply(tokens, value); } else { - if (!(value = value.replace(HEREGEX_OMIT, ''))) { - continue; - } + if (!(value = value.replace(HEREGEX_OMIT, ''))) continue; value = value.replace(/\\/g, '\\\\'); tokens.push(['STRING', this.makeString(value, '"', true)]); } @@ -3037,19 +3069,17 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff this.tokens.push(['STRING', '""'], ['+', '+']); } (_ref5 = this.tokens).push.apply(_ref5, tokens); - if (flags) { - this.tokens.push([',', ','], ['STRING', '"' + flags + '"']); - } + if (flags) this.tokens.push([',', ','], ['STRING', '"' + flags + '"']); this.token(')', ')'); return heregex.length; }; + Lexer.prototype.lineToken = function() { var diff, indent, match, noNewlines, prev, size; - if (!(match = MULTI_DENT.exec(this.chunk))) { - return 0; - } + if (!(match = MULTI_DENT.exec(this.chunk))) return 0; indent = match[0]; this.line += count(indent, '\n'); + this.seenFor = false; prev = last(this.tokens, 1); size = indent.length - 1 - indent.lastIndexOf('\n'); noNewlines = this.unfinished(); @@ -3070,6 +3100,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff diff = size - this.indent + this.outdebt; this.token('INDENT', diff); this.indents.push(diff); + this.ends.push('OUTDENT'); this.outdebt = this.indebt = 0; } else { this.indebt = 0; @@ -3078,7 +3109,8 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff this.indent = size; return indent.length; }; - Lexer.prototype.outdentToken = function(moveOut, noNewlines, close) { + + Lexer.prototype.outdentToken = function(moveOut, noNewlines) { var dent, len; while (moveOut > 0) { len = this.indents.length - 1; @@ -3094,51 +3126,52 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff dent = this.indents.pop() - this.outdebt; moveOut -= dent; this.outdebt = 0; + this.pair('OUTDENT'); this.token('OUTDENT', dent); } } - if (dent) { - this.outdebt -= moveOut; + if (dent) this.outdebt -= moveOut; + while (this.value() === ';') { + this.tokens.pop(); } if (!(this.tag() === 'TERMINATOR' || noNewlines)) { this.token('TERMINATOR', '\n'); } return this; }; + Lexer.prototype.whitespaceToken = function() { var match, nline, prev; if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) { return 0; } prev = last(this.tokens); - if (prev) { - prev[match ? 'spaced' : 'newLine'] = true; - } + if (prev) prev[match ? 'spaced' : 'newLine'] = true; if (match) { return match[0].length; } else { return 0; } }; + Lexer.prototype.newlineToken = function() { - if (this.tag() !== 'TERMINATOR') { - this.token('TERMINATOR', '\n'); + while (this.value() === ';') { + this.tokens.pop(); } + if (this.tag() !== 'TERMINATOR') this.token('TERMINATOR', '\n'); return this; }; + Lexer.prototype.suppressNewlines = function() { - if (this.value() === '\\') { - this.tokens.pop(); - } + if (this.value() === '\\') this.tokens.pop(); return this; }; + Lexer.prototype.literalToken = function() { var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5; if (match = OPERATOR.exec(this.chunk)) { value = match[0]; - if (CODE.test(value)) { - this.tagParameters(); - } + if (CODE.test(value)) this.tagParameters(); } else { value = this.chunk.charAt(0); } @@ -3146,7 +3179,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff prev = last(this.tokens); if (value === '=' && prev) { if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) { - this.assignmentError(); + this.error("reserved word \"" + (this.value()) + "\" can't be assigned"); } if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') { prev[0] = 'COMPOUND_ASSIGN'; @@ -3155,6 +3188,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } } if (value === ';') { + this.seenFor = false; tag = 'TERMINATOR'; } else if (__indexOf.call(MATH, value) >= 0) { tag = 'MATH'; @@ -3170,34 +3204,39 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff tag = 'LOGIC'; } else if (prev && !prev.spaced) { if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) { - if (prev[0] === '?') { - prev[0] = 'FUNC_EXIST'; - } + if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; tag = 'CALL_START'; } else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) { tag = 'INDEX_START'; switch (prev[0]) { case '?': prev[0] = 'INDEX_SOAK'; - break; - case '::': - prev[0] = 'INDEX_PROTO'; } } } + switch (value) { + case '(': + case '{': + case '[': + this.ends.push(INVERSES[value]); + break; + case ')': + case '}': + case ']': + this.pair(value); + } this.token(tag, value); return value.length; }; + Lexer.prototype.sanitizeHeredoc = function(doc, options) { var attempt, herecomment, indent, match, _ref2; indent = options.indent, herecomment = options.herecomment; if (herecomment) { if (HEREDOC_ILLEGAL.test(doc)) { - throw new Error("block comment cannot contain \"*/\", starting on line " + (this.line + 1)); - } - if (doc.indexOf('\n') <= 0) { - return doc; + this.error("block comment cannot contain \"*/\", starting"); } + if (doc.indexOf('\n') <= 0) return doc; } else { while (match = HEREDOC_INDENT.exec(doc)) { attempt = match[1]; @@ -3206,19 +3245,14 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } } } - if (indent) { - doc = doc.replace(RegExp("\\n" + indent, "g"), '\n'); - } - if (!herecomment) { - doc = doc.replace(/^\n/, ''); - } + if (indent) doc = doc.replace(RegExp("\\n" + indent, "g"), '\n'); + if (!herecomment) doc = doc.replace(/^\n/, ''); return doc; }; + Lexer.prototype.tagParameters = function() { var i, stack, tok, tokens; - if (this.tag() !== ')') { - return this; - } + if (this.tag() !== ')') return this; stack = []; tokens = this.tokens; i = tokens.length; @@ -3235,38 +3269,41 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } else if (tok[0] === '(') { tok[0] = 'PARAM_START'; return this; + } else { + return this; } } } return this; }; + Lexer.prototype.closeIndentation = function() { return this.outdentToken(this.indent); }; - Lexer.prototype.identifierError = function(word) { - throw SyntaxError("Reserved word \"" + word + "\" on line " + (this.line + 1)); - }; - Lexer.prototype.assignmentError = function() { - throw SyntaxError("Reserved word \"" + (this.value()) + "\" on line " + (this.line + 1) + " can't be assigned"); - }; + Lexer.prototype.balancedString = function(str, end) { - var i, letter, prev, stack, _ref2; + var continueCount, i, letter, match, prev, stack, _i, _ref2; + continueCount = 0; stack = [end]; - for (i = 1, _ref2 = str.length; 1 <= _ref2 ? i < _ref2 : i > _ref2; 1 <= _ref2 ? i++ : i--) { + for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) { + if (continueCount) { + --continueCount; + continue; + } switch (letter = str.charAt(i)) { case '\\': - i++; + ++continueCount; continue; case end: stack.pop(); - if (!stack.length) { - return str.slice(0, i + 1); - } + if (!stack.length) return str.slice(0, i + 1 || 9e9); end = stack[stack.length - 1]; continue; } if (end === '}' && (letter === '"' || letter === "'")) { stack.push(end = letter); + } else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) { + continueCount += match[0].length - 1; } else if (end === '}' && letter === '{') { stack.push(end = '}'); } else if (end === '"' && prev === '#' && letter === '{') { @@ -3274,13 +3311,12 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } prev = letter; } - throw new Error("missing " + (stack.pop()) + ", starting on line " + (this.line + 1)); + return this.error("missing " + (stack.pop()) + ", starting"); }; + Lexer.prototype.interpolateString = function(str, options) { - var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _len, _ref2, _ref3, _ref4; - if (options == null) { - options = {}; - } + var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4; + if (options == null) options = {}; heredoc = options.heredoc, regex = options.regex; tokens = []; pi = 0; @@ -3293,9 +3329,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) { continue; } - if (pi < i) { - tokens.push(['NEOSTRING', str.slice(pi, i)]); - } + if (pi < i) tokens.push(['NEOSTRING', str.slice(pi, i)]); inner = expr.slice(1, -1); if (inner.length) { nested = new Lexer().tokenize(inner, { @@ -3308,8 +3342,8 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } if (len = nested.length) { if (len > 1) { - nested.unshift(['(', '(']); - nested.push([')', ')']); + nested.unshift(['(', '(', this.line]); + nested.push([')', ')', this.line]); } tokens.push(['TOKENS', nested]); } @@ -3317,59 +3351,60 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff i += expr.length; pi = i + 1; } - if ((i > pi && pi < str.length)) { - tokens.push(['NEOSTRING', str.slice(pi)]); - } - if (regex) { - return tokens; - } - if (!tokens.length) { - return this.token('STRING', '""'); - } - if (tokens[0][0] !== 'NEOSTRING') { - tokens.unshift(['', '']); - } - if (interpolated = tokens.length > 1) { - this.token('(', '('); - } - for (i = 0, _len = tokens.length; i < _len; i++) { + if ((i > pi && pi < str.length)) tokens.push(['NEOSTRING', str.slice(pi)]); + if (regex) return tokens; + if (!tokens.length) return this.token('STRING', '""'); + if (tokens[0][0] !== 'NEOSTRING') tokens.unshift(['', '']); + if (interpolated = tokens.length > 1) this.token('(', '('); + for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) { _ref3 = tokens[i], tag = _ref3[0], value = _ref3[1]; - if (i) { - this.token('+', '+'); - } + if (i) this.token('+', '+'); if (tag === 'TOKENS') { (_ref4 = this.tokens).push.apply(_ref4, value); } else { this.token('STRING', this.makeString(value, '"', heredoc)); } } - if (interpolated) { - this.token(')', ')'); - } + if (interpolated) this.token(')', ')'); return tokens; }; + + Lexer.prototype.pair = function(tag) { + var size, wanted; + if (tag !== (wanted = last(this.ends))) { + if ('OUTDENT' !== wanted) this.error("unmatched " + tag); + this.indent -= size = last(this.indents); + this.outdentToken(size, true); + return this.pair(tag); + } + return this.ends.pop(); + }; + Lexer.prototype.token = function(tag, value) { return this.tokens.push([tag, value, this.line]); }; + Lexer.prototype.tag = function(index, tag) { var tok; return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]); }; + Lexer.prototype.value = function(index, val) { var tok; return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]); }; + Lexer.prototype.unfinished = function() { - var prev, value; - return LINE_CONTINUER.test(this.chunk) || (prev = last(this.tokens, 1)) && prev[0] !== '.' && (value = this.value()) && !value.reserved && NO_NEWLINE.test(value) && !CODE.test(value) && !ASSIGNED.test(this.chunk); + var _ref2; + return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS'); }; + Lexer.prototype.escapeLines = function(str, heredoc) { return str.replace(MULTILINER, heredoc ? '\\n' : ''); }; + Lexer.prototype.makeString = function(body, quote, heredoc) { - if (!body) { - return quote + quote; - } + if (!body) return quote + quote; body = body.replace(/\\([\s\S])/g, function(match, contents) { if (contents === '\n' || contents === quote) { return contents; @@ -3380,10 +3415,19 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff body = body.replace(RegExp("" + quote, "g"), '\\$&'); return quote + this.escapeLines(body, heredoc) + quote; }; + + Lexer.prototype.error = function(message) { + throw SyntaxError("" + message + " on line " + (this.line + 1)); + }; + return Lexer; + })(); + JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super']; + COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']; + COFFEE_ALIAS_MAP = { and: '&&', or: '||', @@ -3395,6 +3439,7 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff on: 'true', off: 'false' }; + COFFEE_ALIASES = (function() { var _results; _results = []; @@ -3403,47 +3448,85 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff } return _results; })(); + COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES); - RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf']; - JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED); - exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS); + + RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield']; + + STRICT_PROSCRIBED = ['arguments', 'eval']; + + JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED); + + exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED); + + exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED; + IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/; - NUMBER = /^0x[\da-f]+|^(?:\d+(\.\d+)?|\.\d+)(?:e[+-]?\d+)?/i; + + NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; + HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/; + OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/; + WHITESPACE = /^[^\n\S]+/; + COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/; + CODE = /^[-=]>/; + MULTI_DENT = /^(?:\n[^\n\S]*)+/; + SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/; + JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/; - REGEX = /^\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/[imgy]{0,4}(?!\w)/; + + REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/; + HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/; + HEREGEX_OMIT = /\s+(?:#.*)?/g; + MULTILINER = /\n/g; + HEREDOC_INDENT = /\n+([^\n\S]*)/g; + HEREDOC_ILLEGAL = /\*\//; - ASSIGNED = /^\s*@?([$A-Za-z_][$\w\x7f-\uffff]*|['"].*['"])[^\n\S]*?[:=][^:=>]/; + LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/; + TRAILING_SPACES = /\s+$/; - NO_NEWLINE = /^(?:[-+*&|\/%=<>!.\\][<>=&|]*|and|or|is(?:nt)?|n(?:ot|ew)|delete|typeof|instanceof)$/; + COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=']; + UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO']; + LOGIC = ['&&', '||', '&', '|', '^']; + SHIFT = ['<<', '>>', '>>>']; + COMPARE = ['==', '!=', '<', '>', '<=', '>=']; + MATH = ['*', '/', '%']; + RELATION = ['IN', 'OF', 'INSTANCEOF']; + BOOL = ['TRUE', 'FALSE', 'NULL', 'UNDEFINED']; + NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', '++', '--', ']']; + NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING'); + CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']; + INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL'); + LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']; -}); -/** + + +});/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -3467,16 +3550,18 @@ define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coff */ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(require, exports, module) { - - var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref; - var __indexOf = Array.prototype.indexOf || function(item) { - for (var i = 0, l = this.length; i < l; i++) { - if (this[i] === item) return i; - } - return -1; - }, __slice = Array.prototype.slice; +// Generated by CoffeeScript 1.2.1-pre + + var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, + __slice = [].slice; + exports.Rewriter = (function() { + + Rewriter.name = 'Rewriter'; + function Rewriter() {} + Rewriter.prototype.rewrite = function(tokens) { this.tokens = tokens; this.removeLeadingNewlines(); @@ -3487,10 +3572,9 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r this.tagPostfixConditionals(); this.addImplicitBraces(); this.addImplicitParentheses(); - this.ensureBalance(BALANCED_PAIRS); - this.rewriteClosingParens(); return this.tokens; }; + Rewriter.prototype.scanTokens = function(block) { var i, token, tokens; tokens = this.tokens; @@ -3500,39 +3584,36 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r } return true; }; + Rewriter.prototype.detectEnd = function(i, condition, action) { - var levels, token, tokens, _ref, _ref2; + var levels, token, tokens, _ref, _ref1; tokens = this.tokens; levels = 0; while (token = tokens[i]) { if (levels === 0 && condition.call(this, token, i)) { return action.call(this, token, i); } - if (!token || levels < 0) { - return action.call(this, token, i - 1); - } + if (!token || levels < 0) return action.call(this, token, i - 1); if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) { levels += 1; - } else if (_ref2 = token[0], __indexOf.call(EXPRESSION_END, _ref2) >= 0) { + } else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) { levels -= 1; } i += 1; } return i - 1; }; + Rewriter.prototype.removeLeadingNewlines = function() { - var i, tag, _len, _ref; + var i, tag, _i, _len, _ref; _ref = this.tokens; - for (i = 0, _len = _ref.length; i < _len; i++) { + for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { tag = _ref[i][0]; - if (tag !== 'TERMINATOR') { - break; - } - } - if (i) { - return this.tokens.splice(0, i); + if (tag !== 'TERMINATOR') break; } + if (i) return this.tokens.splice(0, i); }; + Rewriter.prototype.removeMidExpressionNewlines = function() { return this.scanTokens(function(token, i, tokens) { var _ref; @@ -3543,6 +3624,7 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r return 0; }); }; + Rewriter.prototype.closeOpenCalls = function() { var action, condition; condition = function(token, i) { @@ -3553,12 +3635,11 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END'; }; return this.scanTokens(function(token, i) { - if (token[0] === 'CALL_START') { - this.detectEnd(i + 1, condition, action); - } + if (token[0] === 'CALL_START') this.detectEnd(i + 1, condition, action); return 1; }); }; + Rewriter.prototype.closeOpenIndexes = function() { var action, condition; condition = function(token, i) { @@ -3569,34 +3650,33 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r return token[0] = 'INDEX_END'; }; return this.scanTokens(function(token, i) { - if (token[0] === 'INDEX_START') { - this.detectEnd(i + 1, condition, action); - } + if (token[0] === 'INDEX_START') this.detectEnd(i + 1, condition, action); return 1; }); }; + Rewriter.prototype.addImplicitBraces = function() { - var action, condition, stack, start, startIndent; + var action, condition, sameLine, stack, start, startIndent, startsLine; stack = []; start = null; + startsLine = null; + sameLine = true; startIndent = 0; condition = function(token, i) { - var one, tag, three, two, _ref, _ref2; - _ref = this.tokens.slice(i + 1, (i + 3 + 1) || 9e9), one = _ref[0], two = _ref[1], three = _ref[2]; - if ('HERECOMMENT' === (one != null ? one[0] : void 0)) { - return false; - } + var one, tag, three, two, _ref, _ref1; + _ref = this.tokens.slice(i + 1, (i + 3) + 1 || 9e9), one = _ref[0], two = _ref[1], three = _ref[2]; + if ('HERECOMMENT' === (one != null ? one[0] : void 0)) return false; tag = token[0]; - return ((tag === 'TERMINATOR' || tag === 'OUTDENT') && !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':')) || (tag === ',' && one && ((_ref2 = one[0]) !== 'IDENTIFIER' && _ref2 !== 'NUMBER' && _ref2 !== 'STRING' && _ref2 !== '@' && _ref2 !== 'TERMINATOR' && _ref2 !== 'OUTDENT')); + if (__indexOf.call(LINEBREAKS, tag) >= 0) sameLine = false; + return (((tag === 'TERMINATOR' || tag === 'OUTDENT') || (__indexOf.call(IMPLICIT_END, tag) >= 0 && sameLine)) && ((!startsLine && this.tag(i - 1) !== ',') || !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':'))) || (tag === ',' && one && ((_ref1 = one[0]) !== 'IDENTIFIER' && _ref1 !== 'NUMBER' && _ref1 !== 'STRING' && _ref1 !== '@' && _ref1 !== 'TERMINATOR' && _ref1 !== 'OUTDENT')); }; action = function(token, i) { var tok; - tok = ['}', '}', token[2]]; - tok.generated = true; + tok = this.generate('}', '}', token[2]); return this.tokens.splice(i, 0, tok); }; return this.scanTokens(function(token, i, tokens) { - var ago, idx, tag, tok, value, _ref, _ref2; + var ago, idx, prevTag, tag, tok, value, _ref, _ref1; if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) { stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]); return 1; @@ -3605,80 +3685,82 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r start = stack.pop(); return 1; } - if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref2 = stack[stack.length - 1]) != null ? _ref2[0] : void 0) !== '{'))) { + if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref1 = stack[stack.length - 1]) != null ? _ref1[0] : void 0) !== '{'))) { return 1; } + sameLine = true; stack.push(['{']); idx = ago === '@' ? i - 2 : i - 1; while (this.tag(idx - 2) === 'HERECOMMENT') { idx -= 2; } + prevTag = this.tag(idx - 1); + startsLine = !prevTag || (__indexOf.call(LINEBREAKS, prevTag) >= 0); value = new String('{'); value.generated = true; - tok = ['{', value, token[2]]; - tok.generated = true; + tok = this.generate('{', value, token[2]); tokens.splice(idx, 0, tok); this.detectEnd(i + 2, condition, action); return 2; }); }; + Rewriter.prototype.addImplicitParentheses = function() { - var action, noCall; - noCall = false; + var action, condition, noCall, seenControl, seenSingle; + noCall = seenSingle = seenControl = false; + condition = function(token, i) { + var post, tag, _ref, _ref1; + tag = token[0]; + if (!seenSingle && token.fromThen) return true; + if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>' || tag === 'CLASS') { + seenSingle = true; + } + if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY' || tag === '=') { + seenControl = true; + } + if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') { + return true; + } + return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (((_ref = this.tag(i - 2)) !== 'CLASS' && _ref !== 'EXTENDS') && (_ref1 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref1) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{'))); + }; action = function(token, i) { - var idx; - idx = token[0] === 'OUTDENT' ? i + 1 : i; - return this.tokens.splice(idx, 0, ['CALL_END', ')', token[2]]); + return this.tokens.splice(i, 0, this.generate('CALL_END', ')', token[2])); }; return this.scanTokens(function(token, i, tokens) { - var callObject, current, next, prev, seenControl, seenSingle, tag, _ref, _ref2, _ref3; + var callObject, current, next, prev, tag, _ref, _ref1, _ref2; tag = token[0]; - if (tag === 'CLASS' || tag === 'IF') { + if (tag === 'CLASS' || tag === 'IF' || tag === 'FOR' || tag === 'WHILE') { noCall = true; } - _ref = tokens.slice(i - 1, (i + 1 + 1) || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2]; - callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0); + _ref = tokens.slice(i - 1, (i + 1) + 1 || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2]; + callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref1 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref1) >= 0); seenSingle = false; seenControl = false; - if (__indexOf.call(LINEBREAKS, tag) >= 0) { - noCall = false; - } - if (prev && !prev.spaced && tag === '?') { - token.call = true; - } - if (token.fromThen) { - return 1; - } - if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref3 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref3) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) { + if (__indexOf.call(LINEBREAKS, tag) >= 0) noCall = false; + if (prev && !prev.spaced && tag === '?') token.call = true; + if (token.fromThen) return 1; + if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) { return 1; } - tokens.splice(i, 0, ['CALL_START', '(', token[2]]); - this.detectEnd(i + 1, function(token, i) { - var post, _ref4; - tag = token[0]; - if (!seenSingle && token.fromThen) { - return true; - } - if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>') { - seenSingle = true; - } - if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY') { - seenControl = true; - } - if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') { - return true; - } - return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (this.tag(i - 2) !== 'CLASS' && (_ref4 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref4) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{'))); - }, action); - if (prev[0] === '?') { - prev[0] = 'FUNC_EXIST'; - } + tokens.splice(i, 0, this.generate('CALL_START', '(', token[2])); + this.detectEnd(i + 1, condition, action); + if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; return 2; }); }; + Rewriter.prototype.addImplicitIndentation = function() { + var action, condition, indent, outdent, starter; + starter = indent = outdent = null; + condition = function(token, i) { + var _ref; + return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN')); + }; + action = function(token, i) { + return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent); + }; return this.scanTokens(function(token, i, tokens) { - var action, condition, indent, outdent, starter, tag, _ref, _ref2; + var tag, _ref, _ref1; tag = token[0]; if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') { tokens.splice(i, 1); @@ -3694,145 +3776,98 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r } if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) { starter = tag; - _ref2 = this.indentation(token), indent = _ref2[0], outdent = _ref2[1]; - if (starter === 'THEN') { - indent.fromThen = true; - } - indent.generated = outdent.generated = true; + _ref1 = this.indentation(token, true), indent = _ref1[0], outdent = _ref1[1]; + if (starter === 'THEN') indent.fromThen = true; tokens.splice(i + 1, 0, indent); - condition = function(token, i) { - var _ref3; - return token[1] !== ';' && (_ref3 = token[0], __indexOf.call(SINGLE_CLOSERS, _ref3) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN')); - }; - action = function(token, i) { - return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent); - }; this.detectEnd(i + 2, condition, action); - if (tag === 'THEN') { - tokens.splice(i, 1); - } + if (tag === 'THEN') tokens.splice(i, 1); return 1; } return 1; }); }; + Rewriter.prototype.tagPostfixConditionals = function() { - var condition; + var action, condition, original; + original = null; condition = function(token, i) { var _ref; return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT'; }; - return this.scanTokens(function(token, i) { - var original; - if (token[0] !== 'IF') { - return 1; + action = function(token, i) { + if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) { + return original[0] = 'POST_' + original[0]; } + }; + return this.scanTokens(function(token, i) { + if (token[0] !== 'IF') return 1; original = token; - this.detectEnd(i + 1, condition, function(token, i) { - if (token[0] !== 'INDENT') { - return original[0] = 'POST_' + original[0]; - } - }); + this.detectEnd(i + 1, condition, action); return 1; }); }; - Rewriter.prototype.ensureBalance = function(pairs) { - var close, level, levels, open, openLine, tag, token, _i, _j, _len, _len2, _ref, _ref2; - levels = {}; - openLine = {}; - _ref = this.tokens; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - token = _ref[_i]; - tag = token[0]; - for (_j = 0, _len2 = pairs.length; _j < _len2; _j++) { - _ref2 = pairs[_j], open = _ref2[0], close = _ref2[1]; - levels[open] |= 0; - if (tag === open) { - if (levels[open]++ === 0) { - openLine[open] = token[2]; - } - } else if (tag === close && --levels[open] < 0) { - throw Error("too many " + token[1] + " on line " + (token[2] + 1)); - } - } - } - for (open in levels) { - level = levels[open]; - if (level > 0) { - throw Error("unclosed " + open + " on line " + (openLine[open] + 1)); - } - } - return this; + + Rewriter.prototype.indentation = function(token, implicit) { + var indent, outdent; + if (implicit == null) implicit = false; + indent = ['INDENT', 2, token[2]]; + outdent = ['OUTDENT', 2, token[2]]; + if (implicit) indent.generated = outdent.generated = true; + return [indent, outdent]; }; - Rewriter.prototype.rewriteClosingParens = function() { - var debt, key, stack; - stack = []; - debt = {}; - for (key in INVERSES) { - debt[key] = 0; - } - return this.scanTokens(function(token, i, tokens) { - var inv, match, mtag, oppos, tag, val, _ref; - if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) { - stack.push(token); - return 1; - } - if (__indexOf.call(EXPRESSION_END, tag) < 0) { - return 1; - } - if (debt[inv = INVERSES[tag]] > 0) { - debt[inv] -= 1; - tokens.splice(i, 1); - return 0; - } - match = stack.pop(); - mtag = match[0]; - oppos = INVERSES[mtag]; - if (tag === oppos) { - return 1; - } - debt[mtag] += 1; - val = [oppos, mtag === 'INDENT' ? match[1] : oppos]; - if (this.tag(i + 2) === mtag) { - tokens.splice(i + 3, 0, val); - stack.push(match); - } else { - tokens.splice(i, 0, val); - } - return 1; - }); - }; - Rewriter.prototype.indentation = function(token) { - return [['INDENT', 2, token[2]], ['OUTDENT', 2, token[2]]]; + + Rewriter.prototype.generate = function(tag, value, line) { + var tok; + tok = [tag, value, line]; + tok.generated = true; + return tok; }; + Rewriter.prototype.tag = function(i) { var _ref; return (_ref = this.tokens[i]) != null ? _ref[0] : void 0; }; + return Rewriter; + })(); + BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']]; - INVERSES = {}; + + exports.INVERSES = INVERSES = {}; + EXPRESSION_START = []; + EXPRESSION_END = []; + for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) { _ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1]; EXPRESSION_START.push(INVERSES[rite] = left); EXPRESSION_END.push(INVERSES[left] = rite); } + EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END); + IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS']; + IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++']; + IMPLICIT_UNSPACED_CALL = ['+', '-']; + IMPLICIT_BLOCK = ['->', '=>', '{', '[', ',']; + IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR']; + SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN']; + SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN']; + LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT']; -}); -/** + + +});/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -3856,41 +3891,44 @@ define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(r */ define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(require, exports, module) { - +// Generated by CoffeeScript 1.2.1-pre + var extend, flatten; + exports.starts = function(string, literal, start) { return literal === string.substr(start, literal.length); }; + exports.ends = function(string, literal, back) { var len; len = literal.length; return literal === string.substr(string.length - len - (back || 0), len); }; + exports.compact = function(array) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { item = array[_i]; - if (item) { - _results.push(item); - } + if (item) _results.push(item); } return _results; }; + exports.count = function(string, substr) { var num, pos; num = pos = 0; - if (!substr.length) { - return 1 / 0; - } + if (!substr.length) return 1 / 0; while (pos = 1 + string.indexOf(substr, pos)) { num++; } return num; }; + exports.merge = function(options, overrides) { return extend(extend({}, options), overrides); }; + extend = exports.extend = function(object, properties) { var key, val; for (key in properties) { @@ -3899,6 +3937,7 @@ define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(re } return object; }; + exports.flatten = flatten = function(array) { var element, flattened, _i, _len; flattened = []; @@ -3912,19 +3951,22 @@ define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(re } return flattened; }; + exports.del = function(obj, key) { var val; val = obj[key]; delete obj[key]; return val; }; + exports.last = function(array, back) { return array[array.length - (back || 0) - 1]; }; -}); -/** + + +});/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -3948,13 +3990,14 @@ define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(re */ define('ace/mode/coffee/parser', ['require', 'exports', 'module' ], function(require, exports, module) { - /* Jison generated parser */ + +undefined var parser = {trace: function trace() { }, yy: {}, -symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Throw":11,"Comment":12,"STATEMENT":13,"Value":14,"Invocation":15,"Code":16,"Operation":17,"Assign":18,"If":19,"Try":20,"While":21,"For":22,"Switch":23,"Class":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"BOOL":35,"Assignable":36,"=":37,"AssignObj":38,"ObjAssignable":39,":":40,"ThisProperty":41,"RETURN":42,"HERECOMMENT":43,"PARAM_START":44,"ParamList":45,"PARAM_END":46,"FuncGlyph":47,"->":48,"=>":49,"OptComma":50,",":51,"Param":52,"ParamVar":53,"...":54,"Array":55,"Object":56,"Splat":57,"SimpleAssignable":58,"Accessor":59,"Parenthetical":60,"Range":61,"This":62,".":63,"?.":64,"::":65,"Index":66,"INDEX_START":67,"IndexValue":68,"INDEX_END":69,"INDEX_SOAK":70,"INDEX_PROTO":71,"Slice":72,"{":73,"AssignList":74,"}":75,"CLASS":76,"EXTENDS":77,"OptFuncExist":78,"Arguments":79,"SUPER":80,"FUNC_EXIST":81,"CALL_START":82,"CALL_END":83,"ArgList":84,"THIS":85,"@":86,"[":87,"]":88,"RangeDots":89,"..":90,"Arg":91,"SimpleArgs":92,"TRY":93,"Catch":94,"FINALLY":95,"CATCH":96,"THROW":97,"(":98,")":99,"WhileSource":100,"WHILE":101,"WHEN":102,"UNTIL":103,"Loop":104,"LOOP":105,"ForBody":106,"FOR":107,"ForStart":108,"ForSource":109,"ForVariables":110,"OWN":111,"ForValue":112,"FORIN":113,"FOROF":114,"BY":115,"SWITCH":116,"Whens":117,"ELSE":118,"When":119,"LEADING_WHEN":120,"IfBlock":121,"IF":122,"POST_IF":123,"UNARY":124,"-":125,"+":126,"--":127,"++":128,"?":129,"MATH":130,"SHIFT":131,"COMPARE":132,"LOGIC":133,"RELATION":134,"COMPOUND_ASSIGN":135,"$accept":0,"$end":1}, -terminals_: {2:"error",6:"TERMINATOR",13:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"BOOL",37:"=",40:":",42:"RETURN",43:"HERECOMMENT",44:"PARAM_START",46:"PARAM_END",48:"->",49:"=>",51:",",54:"...",63:".",64:"?.",65:"::",67:"INDEX_START",69:"INDEX_END",70:"INDEX_SOAK",71:"INDEX_PROTO",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"}, -productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[18,3],[18,5],[38,1],[38,3],[38,5],[38,1],[39,1],[39,1],[39,1],[10,2],[10,1],[12,1],[16,5],[16,2],[47,1],[47,1],[50,0],[50,1],[45,0],[45,1],[45,3],[52,1],[52,2],[52,3],[53,1],[53,1],[53,1],[53,1],[57,2],[58,1],[58,2],[58,2],[58,1],[36,1],[36,1],[36,1],[14,1],[14,1],[14,1],[14,1],[14,1],[59,2],[59,2],[59,2],[59,1],[59,1],[66,3],[66,2],[66,2],[68,1],[68,1],[56,4],[74,0],[74,1],[74,3],[74,4],[74,6],[24,1],[24,2],[24,3],[24,4],[24,2],[24,3],[24,4],[24,5],[15,3],[15,3],[15,1],[15,2],[78,0],[78,1],[79,2],[79,4],[62,1],[62,1],[41,2],[55,2],[55,4],[89,1],[89,1],[61,5],[72,3],[72,2],[72,2],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[20,2],[20,3],[20,4],[20,5],[94,3],[11,2],[60,3],[60,5],[100,2],[100,4],[100,2],[100,4],[21,2],[21,2],[21,2],[21,1],[104,2],[104,2],[22,2],[22,2],[22,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[23,5],[23,7],[23,4],[23,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[19,1],[19,3],[19,3],[19,3],[17,2],[17,2],[17,2],[17,2],[17,2],[17,2],[17,2],[17,2],[17,3],[17,3],[17,3],[17,3],[17,3],[17,3],[17,3],[17,3],[17,5],[17,3]], +symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Comment":11,"STATEMENT":12,"Value":13,"Invocation":14,"Code":15,"Operation":16,"Assign":17,"If":18,"Try":19,"While":20,"For":21,"Switch":22,"Class":23,"Throw":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"DEBUGGER":35,"BOOL":36,"Assignable":37,"=":38,"AssignObj":39,"ObjAssignable":40,":":41,"ThisProperty":42,"RETURN":43,"HERECOMMENT":44,"PARAM_START":45,"ParamList":46,"PARAM_END":47,"FuncGlyph":48,"->":49,"=>":50,"OptComma":51,",":52,"Param":53,"ParamVar":54,"...":55,"Array":56,"Object":57,"Splat":58,"SimpleAssignable":59,"Accessor":60,"Parenthetical":61,"Range":62,"This":63,".":64,"?.":65,"::":66,"Index":67,"INDEX_START":68,"IndexValue":69,"INDEX_END":70,"INDEX_SOAK":71,"Slice":72,"{":73,"AssignList":74,"}":75,"CLASS":76,"EXTENDS":77,"OptFuncExist":78,"Arguments":79,"SUPER":80,"FUNC_EXIST":81,"CALL_START":82,"CALL_END":83,"ArgList":84,"THIS":85,"@":86,"[":87,"]":88,"RangeDots":89,"..":90,"Arg":91,"SimpleArgs":92,"TRY":93,"Catch":94,"FINALLY":95,"CATCH":96,"THROW":97,"(":98,")":99,"WhileSource":100,"WHILE":101,"WHEN":102,"UNTIL":103,"Loop":104,"LOOP":105,"ForBody":106,"FOR":107,"ForStart":108,"ForSource":109,"ForVariables":110,"OWN":111,"ForValue":112,"FORIN":113,"FOROF":114,"BY":115,"SWITCH":116,"Whens":117,"ELSE":118,"When":119,"LEADING_WHEN":120,"IfBlock":121,"IF":122,"POST_IF":123,"UNARY":124,"-":125,"+":126,"--":127,"++":128,"?":129,"MATH":130,"SHIFT":131,"COMPARE":132,"LOGIC":133,"RELATION":134,"COMPOUND_ASSIGN":135,"$accept":0,"$end":1}, +terminals_: {2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"BOOL",38:"=",41:":",43:"RETURN",44:"HERECOMMENT",45:"PARAM_START",47:"PARAM_END",49:"->",50:"=>",52:",",55:"...",64:".",65:"?.",66:"::",68:"INDEX_START",70:"INDEX_END",71:"INDEX_SOAK",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"}, +productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[39,1],[39,3],[39,5],[39,1],[40,1],[40,1],[40,1],[10,2],[10,1],[11,1],[15,5],[15,2],[48,1],[48,1],[51,0],[51,1],[46,0],[46,1],[46,3],[53,1],[53,2],[53,3],[54,1],[54,1],[54,1],[54,1],[58,2],[59,1],[59,2],[59,2],[59,1],[37,1],[37,1],[37,1],[13,1],[13,1],[13,1],[13,1],[13,1],[60,2],[60,2],[60,2],[60,1],[60,1],[67,3],[67,2],[69,1],[69,1],[57,4],[74,0],[74,1],[74,3],[74,4],[74,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[78,0],[78,1],[79,2],[79,4],[63,1],[63,1],[42,2],[56,2],[56,4],[89,1],[89,1],[62,5],[72,3],[72,2],[72,2],[72,1],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[19,2],[19,3],[19,4],[19,5],[94,3],[24,2],[61,3],[61,5],[100,2],[100,4],[100,2],[100,4],[20,2],[20,2],[20,2],[20,1],[104,2],[104,2],[21,2],[21,2],[21,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[22,5],[22,7],[22,4],[22,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]], performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { var $0 = $$.length - 1; @@ -3979,9 +4022,9 @@ case 9:this.$ = $$[$0]; break; case 10:this.$ = $$[$0]; break; -case 11:this.$ = $$[$0]; +case 11:this.$ = new yy.Literal($$[$0]); break; -case 12:this.$ = new yy.Literal($$[$0]); +case 12:this.$ = $$[$0]; break; case 13:this.$ = $$[$0]; break; @@ -4021,386 +4064,386 @@ case 30:this.$ = new yy.Literal($$[$0]); break; case 31:this.$ = new yy.Literal($$[$0]); break; -case 32:this.$ = (function () { +case 32:this.$ = new yy.Literal($$[$0]); +break; +case 33:this.$ = (function () { var val; val = new yy.Literal($$[$0]); - if ($$[$0] === 'undefined') { - val.isUndefined = true; - } + if ($$[$0] === 'undefined') val.isUndefined = true; return val; }()); break; -case 33:this.$ = new yy.Assign($$[$0-2], $$[$0]); -break; -case 34:this.$ = new yy.Assign($$[$0-4], $$[$0-1]); +case 34:this.$ = new yy.Assign($$[$0-2], $$[$0]); break; -case 35:this.$ = new yy.Value($$[$0]); +case 35:this.$ = new yy.Assign($$[$0-3], $$[$0]); break; -case 36:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object'); +case 36:this.$ = new yy.Assign($$[$0-4], $$[$0-1]); break; -case 37:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object'); +case 37:this.$ = new yy.Value($$[$0]); break; -case 38:this.$ = $$[$0]; +case 38:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object'); break; -case 39:this.$ = $$[$0]; +case 39:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object'); break; case 40:this.$ = $$[$0]; break; case 41:this.$ = $$[$0]; break; -case 42:this.$ = new yy.Return($$[$0]); +case 42:this.$ = $$[$0]; break; -case 43:this.$ = new yy.Return; +case 43:this.$ = $$[$0]; break; -case 44:this.$ = new yy.Comment($$[$0]); +case 44:this.$ = new yy.Return($$[$0]); break; -case 45:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]); +case 45:this.$ = new yy.Return; break; -case 46:this.$ = new yy.Code([], $$[$0], $$[$0-1]); +case 46:this.$ = new yy.Comment($$[$0]); break; -case 47:this.$ = 'func'; +case 47:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]); break; -case 48:this.$ = 'boundfunc'; +case 48:this.$ = new yy.Code([], $$[$0], $$[$0-1]); break; -case 49:this.$ = $$[$0]; +case 49:this.$ = 'func'; break; -case 50:this.$ = $$[$0]; +case 50:this.$ = 'boundfunc'; break; -case 51:this.$ = []; +case 51:this.$ = $$[$0]; break; -case 52:this.$ = [$$[$0]]; +case 52:this.$ = $$[$0]; break; -case 53:this.$ = $$[$0-2].concat($$[$0]); +case 53:this.$ = []; break; -case 54:this.$ = new yy.Param($$[$0]); +case 54:this.$ = [$$[$0]]; break; -case 55:this.$ = new yy.Param($$[$0-1], null, true); +case 55:this.$ = $$[$0-2].concat($$[$0]); break; -case 56:this.$ = new yy.Param($$[$0-2], $$[$0]); +case 56:this.$ = new yy.Param($$[$0]); break; -case 57:this.$ = $$[$0]; +case 57:this.$ = new yy.Param($$[$0-1], null, true); break; -case 58:this.$ = $$[$0]; +case 58:this.$ = new yy.Param($$[$0-2], $$[$0]); break; case 59:this.$ = $$[$0]; break; case 60:this.$ = $$[$0]; break; -case 61:this.$ = new yy.Splat($$[$0-1]); +case 61:this.$ = $$[$0]; break; -case 62:this.$ = new yy.Value($$[$0]); +case 62:this.$ = $$[$0]; break; -case 63:this.$ = $$[$0-1].push($$[$0]); +case 63:this.$ = new yy.Splat($$[$0-1]); break; -case 64:this.$ = new yy.Value($$[$0-1], [$$[$0]]); +case 64:this.$ = new yy.Value($$[$0]); break; -case 65:this.$ = $$[$0]; +case 65:this.$ = $$[$0-1].add($$[$0]); break; -case 66:this.$ = $$[$0]; +case 66:this.$ = new yy.Value($$[$0-1], [].concat($$[$0])); break; -case 67:this.$ = new yy.Value($$[$0]); +case 67:this.$ = $$[$0]; break; -case 68:this.$ = new yy.Value($$[$0]); +case 68:this.$ = $$[$0]; break; -case 69:this.$ = $$[$0]; +case 69:this.$ = new yy.Value($$[$0]); break; case 70:this.$ = new yy.Value($$[$0]); break; -case 71:this.$ = new yy.Value($$[$0]); +case 71:this.$ = $$[$0]; break; case 72:this.$ = new yy.Value($$[$0]); break; -case 73:this.$ = $$[$0]; +case 73:this.$ = new yy.Value($$[$0]); break; -case 74:this.$ = new yy.Access($$[$0]); +case 74:this.$ = new yy.Value($$[$0]); break; -case 75:this.$ = new yy.Access($$[$0], 'soak'); +case 75:this.$ = $$[$0]; break; -case 76:this.$ = new yy.Access($$[$0], 'proto'); +case 76:this.$ = new yy.Access($$[$0]); break; -case 77:this.$ = new yy.Access(new yy.Literal('prototype')); +case 77:this.$ = new yy.Access($$[$0], 'soak'); break; -case 78:this.$ = $$[$0]; +case 78:this.$ = [new yy.Access(new yy.Literal('prototype')), new yy.Access($$[$0])]; break; -case 79:this.$ = $$[$0-1]; +case 79:this.$ = new yy.Access(new yy.Literal('prototype')); break; -case 80:this.$ = yy.extend($$[$0], { - soak: true - }); +case 80:this.$ = $$[$0]; break; -case 81:this.$ = yy.extend($$[$0], { - proto: true - }); +case 81:this.$ = $$[$0-1]; break; -case 82:this.$ = new yy.Index($$[$0]); +case 82:this.$ = yy.extend($$[$0], { + soak: true + }); break; -case 83:this.$ = new yy.Slice($$[$0]); +case 83:this.$ = new yy.Index($$[$0]); break; -case 84:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated); +case 84:this.$ = new yy.Slice($$[$0]); break; -case 85:this.$ = []; +case 85:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated); break; -case 86:this.$ = [$$[$0]]; +case 86:this.$ = []; break; -case 87:this.$ = $$[$0-2].concat($$[$0]); +case 87:this.$ = [$$[$0]]; break; -case 88:this.$ = $$[$0-3].concat($$[$0]); +case 88:this.$ = $$[$0-2].concat($$[$0]); break; -case 89:this.$ = $$[$0-5].concat($$[$0-2]); +case 89:this.$ = $$[$0-3].concat($$[$0]); break; -case 90:this.$ = new yy.Class; +case 90:this.$ = $$[$0-5].concat($$[$0-2]); break; -case 91:this.$ = new yy.Class(null, null, $$[$0]); +case 91:this.$ = new yy.Class; break; -case 92:this.$ = new yy.Class(null, $$[$0]); +case 92:this.$ = new yy.Class(null, null, $$[$0]); break; -case 93:this.$ = new yy.Class(null, $$[$0-1], $$[$0]); +case 93:this.$ = new yy.Class(null, $$[$0]); break; -case 94:this.$ = new yy.Class($$[$0]); +case 94:this.$ = new yy.Class(null, $$[$0-1], $$[$0]); break; -case 95:this.$ = new yy.Class($$[$0-1], null, $$[$0]); +case 95:this.$ = new yy.Class($$[$0]); break; -case 96:this.$ = new yy.Class($$[$0-2], $$[$0]); +case 96:this.$ = new yy.Class($$[$0-1], null, $$[$0]); break; -case 97:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]); +case 97:this.$ = new yy.Class($$[$0-2], $$[$0]); break; -case 98:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); +case 98:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]); break; case 99:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); break; -case 100:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]); +case 100:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); break; -case 101:this.$ = new yy.Call('super', $$[$0]); +case 101:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]); break; -case 102:this.$ = false; +case 102:this.$ = new yy.Call('super', $$[$0]); break; -case 103:this.$ = true; +case 103:this.$ = false; break; -case 104:this.$ = []; +case 104:this.$ = true; break; -case 105:this.$ = $$[$0-2]; +case 105:this.$ = []; break; -case 106:this.$ = new yy.Value(new yy.Literal('this')); +case 106:this.$ = $$[$0-2]; break; case 107:this.$ = new yy.Value(new yy.Literal('this')); break; -case 108:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this'); +case 108:this.$ = new yy.Value(new yy.Literal('this')); break; -case 109:this.$ = new yy.Arr([]); +case 109:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this'); break; -case 110:this.$ = new yy.Arr($$[$0-2]); +case 110:this.$ = new yy.Arr([]); break; -case 111:this.$ = 'inclusive'; +case 111:this.$ = new yy.Arr($$[$0-2]); break; -case 112:this.$ = 'exclusive'; +case 112:this.$ = 'inclusive'; break; -case 113:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]); +case 113:this.$ = 'exclusive'; break; -case 114:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]); +case 114:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]); break; -case 115:this.$ = new yy.Range($$[$0-1], null, $$[$0]); +case 115:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]); break; -case 116:this.$ = new yy.Range(null, $$[$0], $$[$0-1]); +case 116:this.$ = new yy.Range($$[$0-1], null, $$[$0]); break; -case 117:this.$ = [$$[$0]]; +case 117:this.$ = new yy.Range(null, $$[$0], $$[$0-1]); break; -case 118:this.$ = $$[$0-2].concat($$[$0]); +case 118:this.$ = new yy.Range(null, null, $$[$0]); break; -case 119:this.$ = $$[$0-3].concat($$[$0]); +case 119:this.$ = [$$[$0]]; break; -case 120:this.$ = $$[$0-2]; +case 120:this.$ = $$[$0-2].concat($$[$0]); break; -case 121:this.$ = $$[$0-5].concat($$[$0-2]); +case 121:this.$ = $$[$0-3].concat($$[$0]); break; -case 122:this.$ = $$[$0]; +case 122:this.$ = $$[$0-2]; break; -case 123:this.$ = $$[$0]; +case 123:this.$ = $$[$0-5].concat($$[$0-2]); break; case 124:this.$ = $$[$0]; break; -case 125:this.$ = [].concat($$[$0-2], $$[$0]); +case 125:this.$ = $$[$0]; +break; +case 126:this.$ = $$[$0]; break; -case 126:this.$ = new yy.Try($$[$0]); +case 127:this.$ = [].concat($$[$0-2], $$[$0]); break; -case 127:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]); +case 128:this.$ = new yy.Try($$[$0]); break; -case 128:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]); +case 129:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]); break; -case 129:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]); +case 130:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]); break; -case 130:this.$ = [$$[$0-1], $$[$0]]; +case 131:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]); break; -case 131:this.$ = new yy.Throw($$[$0]); +case 132:this.$ = [$$[$0-1], $$[$0]]; break; -case 132:this.$ = new yy.Parens($$[$0-1]); +case 133:this.$ = new yy.Throw($$[$0]); break; -case 133:this.$ = new yy.Parens($$[$0-2]); +case 134:this.$ = new yy.Parens($$[$0-1]); break; -case 134:this.$ = new yy.While($$[$0]); +case 135:this.$ = new yy.Parens($$[$0-2]); break; -case 135:this.$ = new yy.While($$[$0-2], { +case 136:this.$ = new yy.While($$[$0]); +break; +case 137:this.$ = new yy.While($$[$0-2], { guard: $$[$0] }); break; -case 136:this.$ = new yy.While($$[$0], { +case 138:this.$ = new yy.While($$[$0], { invert: true }); break; -case 137:this.$ = new yy.While($$[$0-2], { +case 139:this.$ = new yy.While($$[$0-2], { invert: true, guard: $$[$0] }); break; -case 138:this.$ = $$[$0-1].addBody($$[$0]); +case 140:this.$ = $$[$0-1].addBody($$[$0]); break; -case 139:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); +case 141:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); break; -case 140:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); +case 142:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); break; -case 141:this.$ = $$[$0]; +case 143:this.$ = $$[$0]; break; -case 142:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]); +case 144:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]); break; -case 143:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]])); +case 145:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]])); break; -case 144:this.$ = new yy.For($$[$0-1], $$[$0]); +case 146:this.$ = new yy.For($$[$0-1], $$[$0]); break; -case 145:this.$ = new yy.For($$[$0-1], $$[$0]); +case 147:this.$ = new yy.For($$[$0-1], $$[$0]); break; -case 146:this.$ = new yy.For($$[$0], $$[$0-1]); +case 148:this.$ = new yy.For($$[$0], $$[$0-1]); break; -case 147:this.$ = { +case 149:this.$ = { source: new yy.Value($$[$0]) }; break; -case 148:this.$ = (function () { +case 150:this.$ = (function () { $$[$0].own = $$[$0-1].own; $$[$0].name = $$[$0-1][0]; $$[$0].index = $$[$0-1][1]; return $$[$0]; }()); break; -case 149:this.$ = $$[$0]; +case 151:this.$ = $$[$0]; break; -case 150:this.$ = (function () { +case 152:this.$ = (function () { $$[$0].own = true; return $$[$0]; }()); break; -case 151:this.$ = $$[$0]; +case 153:this.$ = $$[$0]; break; -case 152:this.$ = new yy.Value($$[$0]); +case 154:this.$ = new yy.Value($$[$0]); break; -case 153:this.$ = new yy.Value($$[$0]); +case 155:this.$ = new yy.Value($$[$0]); break; -case 154:this.$ = [$$[$0]]; +case 156:this.$ = [$$[$0]]; break; -case 155:this.$ = [$$[$0-2], $$[$0]]; +case 157:this.$ = [$$[$0-2], $$[$0]]; break; -case 156:this.$ = { +case 158:this.$ = { source: $$[$0] }; break; -case 157:this.$ = { +case 159:this.$ = { source: $$[$0], object: true }; break; -case 158:this.$ = { +case 160:this.$ = { source: $$[$0-2], guard: $$[$0] }; break; -case 159:this.$ = { +case 161:this.$ = { source: $$[$0-2], guard: $$[$0], object: true }; break; -case 160:this.$ = { +case 162:this.$ = { source: $$[$0-2], step: $$[$0] }; break; -case 161:this.$ = { +case 163:this.$ = { source: $$[$0-4], guard: $$[$0-2], step: $$[$0] }; break; -case 162:this.$ = { +case 164:this.$ = { source: $$[$0-4], step: $$[$0-2], guard: $$[$0] }; break; -case 163:this.$ = new yy.Switch($$[$0-3], $$[$0-1]); +case 165:this.$ = new yy.Switch($$[$0-3], $$[$0-1]); break; -case 164:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]); +case 166:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]); break; -case 165:this.$ = new yy.Switch(null, $$[$0-1]); +case 167:this.$ = new yy.Switch(null, $$[$0-1]); break; -case 166:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]); +case 168:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]); break; -case 167:this.$ = $$[$0]; +case 169:this.$ = $$[$0]; break; -case 168:this.$ = $$[$0-1].concat($$[$0]); +case 170:this.$ = $$[$0-1].concat($$[$0]); break; -case 169:this.$ = [[$$[$0-1], $$[$0]]]; +case 171:this.$ = [[$$[$0-1], $$[$0]]]; break; -case 170:this.$ = [[$$[$0-2], $$[$0-1]]]; +case 172:this.$ = [[$$[$0-2], $$[$0-1]]]; break; -case 171:this.$ = new yy.If($$[$0-1], $$[$0], { +case 173:this.$ = new yy.If($$[$0-1], $$[$0], { type: $$[$0-2] }); break; -case 172:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], { +case 174:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], { type: $$[$0-2] })); break; -case 173:this.$ = $$[$0]; +case 175:this.$ = $$[$0]; break; -case 174:this.$ = $$[$0-2].addElse($$[$0]); +case 176:this.$ = $$[$0-2].addElse($$[$0]); break; -case 175:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { +case 177:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { type: $$[$0-1], statement: true }); break; -case 176:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { +case 178:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { type: $$[$0-1], statement: true }); break; -case 177:this.$ = new yy.Op($$[$0-1], $$[$0]); -break; -case 178:this.$ = new yy.Op('-', $$[$0]); +case 179:this.$ = new yy.Op($$[$0-1], $$[$0]); break; -case 179:this.$ = new yy.Op('+', $$[$0]); +case 180:this.$ = new yy.Op('-', $$[$0]); break; -case 180:this.$ = new yy.Op('--', $$[$0]); +case 181:this.$ = new yy.Op('+', $$[$0]); break; -case 181:this.$ = new yy.Op('++', $$[$0]); +case 182:this.$ = new yy.Op('--', $$[$0]); break; -case 182:this.$ = new yy.Op('--', $$[$0-1], null, true); +case 183:this.$ = new yy.Op('++', $$[$0]); break; -case 183:this.$ = new yy.Op('++', $$[$0-1], null, true); +case 184:this.$ = new yy.Op('--', $$[$0-1], null, true); break; -case 184:this.$ = new yy.Existence($$[$0-1]); +case 185:this.$ = new yy.Op('++', $$[$0-1], null, true); break; -case 185:this.$ = new yy.Op('+', $$[$0-2], $$[$0]); +case 186:this.$ = new yy.Existence($$[$0-1]); break; -case 186:this.$ = new yy.Op('-', $$[$0-2], $$[$0]); +case 187:this.$ = new yy.Op('+', $$[$0-2], $$[$0]); break; -case 187:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 188:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); +case 188:this.$ = new yy.Op('-', $$[$0-2], $$[$0]); break; case 189:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; case 190:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); break; -case 191:this.$ = (function () { +case 191:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); +break; +case 192:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); +break; +case 193:this.$ = (function () { if ($$[$0-1].charAt(0) === '!') { return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert(); } else { @@ -4408,207 +4451,124 @@ case 191:this.$ = (function () { } }()); break; -case 192:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]); +case 194:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]); break; -case 193:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]); +case 195:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]); break; -case 194:this.$ = new yy.Extends($$[$0-2], $$[$0]); +case 196:this.$ = new yy.Extends($$[$0-2], $$[$0]); break; } }, -table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,5],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,71]},{6:[1,72]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:74,7:4,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,26:[1,73],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:87,101:[1,62],103:[1,63],106:88,107:[1,65],108:66,123:[1,86]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],46:[2,13],51:[2,13],54:[2,13],59:90,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],69:[2,13],70:[1,97],71:[1,98],75:[2,13],78:89,81:[1,91],82:[2,102],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],46:[2,14],51:[2,14],54:[2,14],59:100,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],69:[2,14],70:[1,97],71:[1,98],75:[2,14],78:99,81:[1,91],82:[2,102],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],46:[2,15],51:[2,15],54:[2,15],69:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],46:[2,16],51:[2,16],54:[2,16],69:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],46:[2,17],51:[2,17],54:[2,17],69:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],46:[2,18],51:[2,18],54:[2,18],69:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],46:[2,19],51:[2,19],54:[2,19],69:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],46:[2,20],51:[2,20],54:[2,20],69:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],46:[2,21],51:[2,21],54:[2,21],69:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],46:[2,22],51:[2,22],54:[2,22],69:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],46:[2,23],51:[2,23],54:[2,23],69:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,12],6:[2,12],26:[2,12],99:[2,12],101:[2,12],103:[2,12],107:[2,12],123:[2,12]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],37:[1,101],46:[2,69],51:[2,69],54:[2,69],63:[2,69],64:[2,69],65:[2,69],67:[2,69],69:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],46:[2,70],51:[2,70],54:[2,70],63:[2,70],64:[2,70],65:[2,70],67:[2,70],69:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],46:[2,71],51:[2,71],54:[2,71],63:[2,71],64:[2,71],65:[2,71],67:[2,71],69:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],46:[2,72],51:[2,72],54:[2,72],63:[2,72],64:[2,72],65:[2,72],67:[2,72],69:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],46:[2,73],51:[2,73],54:[2,73],63:[2,73],64:[2,73],65:[2,73],67:[2,73],69:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],46:[2,100],51:[2,100],54:[2,100],63:[2,100],64:[2,100],65:[2,100],67:[2,100],69:[2,100],70:[2,100],71:[2,100],75:[2,100],79:102,81:[2,100],82:[1,103],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{27:107,28:[1,70],41:108,45:104,46:[2,51],51:[2,51],52:105,53:106,55:109,56:110,73:[1,67],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{14:119,15:120,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:121,41:60,55:47,56:48,58:118,60:25,61:26,62:27,73:[1,67],80:[1,28],85:[1,55],86:[1,56],87:[1,54],98:[1,53]},{14:119,15:120,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:121,41:60,55:47,56:48,58:122,60:25,61:26,62:27,73:[1,67],80:[1,28],85:[1,55],86:[1,56],87:[1,54],98:[1,53]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],37:[2,66],46:[2,66],51:[2,66],54:[2,66],63:[2,66],64:[2,66],65:[2,66],67:[2,66],69:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[1,126],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[1,123],128:[1,124],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[1,125]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],46:[2,173],51:[2,173],54:[2,173],69:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[1,127],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],46:[2,141],51:[2,141],54:[2,141],69:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{5:130,25:[1,5]},{8:131,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,132],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,90],5:133,6:[2,90],14:119,15:120,25:[1,5],26:[2,90],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:121,41:60,46:[2,90],51:[2,90],54:[2,90],55:47,56:48,58:135,60:25,61:26,62:27,69:[2,90],73:[1,67],75:[2,90],77:[1,134],80:[1,28],83:[2,90],85:[1,55],86:[1,56],87:[1,54],88:[2,90],90:[2,90],98:[1,53],99:[2,90],101:[2,90],102:[2,90],103:[2,90],107:[2,90],115:[2,90],123:[2,90],125:[2,90],126:[2,90],129:[2,90],130:[2,90],131:[2,90],132:[2,90],133:[2,90],134:[2,90]},{1:[2,43],6:[2,43],8:136,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,26:[2,43],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],99:[2,43],100:39,101:[2,43],103:[2,43],104:40,105:[1,64],106:41,107:[2,43],108:66,116:[1,42],121:37,122:[1,61],123:[2,43],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:137,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,44],6:[2,44],25:[2,44],26:[2,44],51:[2,44],75:[2,44],99:[2,44],101:[2,44],103:[2,44],107:[2,44],123:[2,44]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],37:[2,67],46:[2,67],51:[2,67],54:[2,67],63:[2,67],64:[2,67],65:[2,67],67:[2,67],69:[2,67],70:[2,67],71:[2,67],75:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],37:[2,68],46:[2,68],51:[2,68],54:[2,68],63:[2,68],64:[2,68],65:[2,68],67:[2,68],69:[2,68],70:[2,68],71:[2,68],75:[2,68],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],46:[2,29],51:[2,29],54:[2,29],63:[2,29],64:[2,29],65:[2,29],67:[2,29],69:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],46:[2,30],51:[2,30],54:[2,30],63:[2,30],64:[2,30],65:[2,30],67:[2,30],69:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],46:[2,31],51:[2,31],54:[2,31],63:[2,31],64:[2,31],65:[2,31],67:[2,31],69:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],46:[2,32],51:[2,32],54:[2,32],63:[2,32],64:[2,32],65:[2,32],67:[2,32],69:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{4:138,7:4,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,139],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,144],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],84:142,85:[1,55],86:[1,56],87:[1,54],88:[1,141],91:143,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],46:[2,106],51:[2,106],54:[2,106],63:[2,106],64:[2,106],65:[2,106],67:[2,106],69:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],27:146,28:[1,70],46:[2,107],51:[2,107],54:[2,107],63:[2,107],64:[2,107],65:[2,107],67:[2,107],69:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{25:[2,47]},{25:[2,48]},{1:[2,62],6:[2,62],25:[2,62],26:[2,62],37:[2,62],46:[2,62],51:[2,62],54:[2,62],63:[2,62],64:[2,62],65:[2,62],67:[2,62],69:[2,62],70:[2,62],71:[2,62],75:[2,62],77:[2,62],81:[2,62],82:[2,62],83:[2,62],88:[2,62],90:[2,62],99:[2,62],101:[2,62],102:[2,62],103:[2,62],107:[2,62],115:[2,62],123:[2,62],125:[2,62],126:[2,62],127:[2,62],128:[2,62],129:[2,62],130:[2,62],131:[2,62],132:[2,62],133:[2,62],134:[2,62],135:[2,62]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],37:[2,65],46:[2,65],51:[2,65],54:[2,65],63:[2,65],64:[2,65],65:[2,65],67:[2,65],69:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{8:147,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,5],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,70],55:157,56:158,61:152,73:[1,67],87:[1,54],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,85],12:165,25:[2,85],27:166,28:[1,70],29:167,30:[1,68],31:[1,69],38:163,39:164,41:168,43:[1,46],51:[2,85],74:162,75:[2,85],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],40:[2,27],46:[2,27],51:[2,27],54:[2,27],63:[2,27],64:[2,27],65:[2,27],67:[2,27],69:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],40:[2,28],46:[2,28],51:[2,28],54:[2,28],63:[2,28],64:[2,28],65:[2,28],67:[2,28],69:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],37:[2,26],40:[2,26],46:[2,26],51:[2,26],54:[2,26],63:[2,26],64:[2,26],65:[2,26],67:[2,26],69:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,26:[2,6],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],99:[2,6],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],46:[2,24],51:[2,24],54:[2,24],69:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,71],26:[1,170]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],46:[2,184],51:[2,184],54:[2,184],69:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{8:171,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],46:[2,140],51:[2,140],54:[2,140],69:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],46:[2,145],51:[2,145],54:[2,145],69:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],101:[2,145],102:[2,145],103:[2,145],107:[2,145],115:[2,145],123:[2,145],125:[2,145],126:[2,145],129:[2,145],130:[2,145],131:[2,145],132:[2,145],133:[2,145],134:[2,145]},{8:179,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],46:[2,139],51:[2,139],54:[2,139],69:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],101:[2,139],102:[2,139],103:[2,139],107:[2,139],115:[2,139],123:[2,139],125:[2,139],126:[2,139],129:[2,139],130:[2,139],131:[2,139],132:[2,139],133:[2,139],134:[2,139]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],46:[2,144],51:[2,144],54:[2,144],69:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],101:[2,144],102:[2,144],103:[2,144],107:[2,144],115:[2,144],123:[2,144],125:[2,144],126:[2,144],129:[2,144],130:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144]},{79:180,82:[1,103]},{1:[2,63],6:[2,63],25:[2,63],26:[2,63],37:[2,63],46:[2,63],51:[2,63],54:[2,63],63:[2,63],64:[2,63],65:[2,63],67:[2,63],69:[2,63],70:[2,63],71:[2,63],75:[2,63],77:[2,63],81:[2,63],82:[2,63],83:[2,63],88:[2,63],90:[2,63],99:[2,63],101:[2,63],102:[2,63],103:[2,63],107:[2,63],115:[2,63],123:[2,63],125:[2,63],126:[2,63],127:[2,63],128:[2,63],129:[2,63],130:[2,63],131:[2,63],132:[2,63],133:[2,63],134:[2,63],135:[2,63]},{82:[2,103]},{27:181,28:[1,70]},{27:182,28:[1,70]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],27:183,28:[1,70],37:[2,77],46:[2,77],51:[2,77],54:[2,77],63:[2,77],64:[2,77],65:[2,77],67:[2,77],69:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],37:[2,78],46:[2,78],51:[2,78],54:[2,78],63:[2,78],64:[2,78],65:[2,78],67:[2,78],69:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{8:185,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],54:[1,189],55:47,56:48,58:36,60:25,61:26,62:27,68:184,72:186,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],89:187,90:[1,188],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{66:190,67:[1,96],70:[1,97],71:[1,98]},{66:191,67:[1,96],70:[1,97],71:[1,98]},{79:192,82:[1,103]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],37:[2,64],46:[2,64],51:[2,64],54:[2,64],63:[2,64],64:[2,64],65:[2,64],67:[2,64],69:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{8:193,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,194],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],46:[2,101],51:[2,101],54:[2,101],63:[2,101],64:[2,101],65:[2,101],67:[2,101],69:[2,101],70:[2,101],71:[2,101],75:[2,101],81:[2,101],82:[2,101],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,144],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,55],86:[1,56],87:[1,54],91:143,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{46:[1,198],51:[1,199]},{46:[2,52],51:[2,52]},{37:[1,201],46:[2,54],51:[2,54],54:[1,200]},{37:[2,57],46:[2,57],51:[2,57],54:[2,57]},{37:[2,58],46:[2,58],51:[2,58],54:[2,58]},{37:[2,59],46:[2,59],51:[2,59],54:[2,59]},{37:[2,60],46:[2,60],51:[2,60],54:[2,60]},{27:146,28:[1,70]},{8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,144],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],84:142,85:[1,55],86:[1,56],87:[1,54],88:[1,141],91:143,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],46:[2,46],51:[2,46],54:[2,46],69:[2,46],75:[2,46],83:[2,46],88:[2,46],90:[2,46],99:[2,46],101:[2,46],102:[2,46],103:[2,46],107:[2,46],115:[2,46],123:[2,46],125:[2,46],126:[2,46],129:[2,46],130:[2,46],131:[2,46],132:[2,46],133:[2,46],134:[2,46]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],46:[2,177],51:[2,177],54:[2,177],69:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:84,101:[2,177],102:[2,177],103:[2,177],106:85,107:[2,177],108:66,115:[2,177],123:[2,177],125:[2,177],126:[2,177],129:[1,75],130:[2,177],131:[2,177],132:[2,177],133:[2,177],134:[2,177]},{100:87,101:[1,62],103:[1,63],106:88,107:[1,65],108:66,123:[1,86]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],46:[2,178],51:[2,178],54:[2,178],69:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:84,101:[2,178],102:[2,178],103:[2,178],106:85,107:[2,178],108:66,115:[2,178],123:[2,178],125:[2,178],126:[2,178],129:[1,75],130:[2,178],131:[2,178],132:[2,178],133:[2,178],134:[2,178]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],46:[2,179],51:[2,179],54:[2,179],69:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:84,101:[2,179],102:[2,179],103:[2,179],106:85,107:[2,179],108:66,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,75],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],46:[2,180],51:[2,180],54:[2,180],63:[2,66],64:[2,66],65:[2,66],67:[2,66],69:[2,180],70:[2,66],71:[2,66],75:[2,180],81:[2,66],82:[2,66],83:[2,180],88:[2,180],90:[2,180],99:[2,180],101:[2,180],102:[2,180],103:[2,180],107:[2,180],115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[2,180],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{59:90,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],70:[1,97],71:[1,98],78:89,81:[1,91],82:[2,102]},{59:100,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],70:[1,97],71:[1,98],78:99,81:[1,91],82:[2,102]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],46:[2,69],51:[2,69],54:[2,69],63:[2,69],64:[2,69],65:[2,69],67:[2,69],69:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],46:[2,181],51:[2,181],54:[2,181],63:[2,66],64:[2,66],65:[2,66],67:[2,66],69:[2,181],70:[2,66],71:[2,66],75:[2,181],81:[2,66],82:[2,66],83:[2,181],88:[2,181],90:[2,181],99:[2,181],101:[2,181],102:[2,181],103:[2,181],107:[2,181],115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[2,181],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],46:[2,182],51:[2,182],54:[2,182],69:[2,182],75:[2,182],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],46:[2,183],51:[2,183],54:[2,183],69:[2,183],75:[2,183],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{8:202,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,203],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,126],6:[2,126],25:[2,126],26:[2,126],46:[2,126],51:[2,126],54:[2,126],69:[2,126],75:[2,126],83:[2,126],88:[2,126],90:[2,126],94:207,95:[1,208],96:[1,209],99:[2,126],101:[2,126],102:[2,126],103:[2,126],107:[2,126],115:[2,126],123:[2,126],125:[2,126],126:[2,126],129:[2,126],130:[2,126],131:[2,126],132:[2,126],133:[2,126],134:[2,126]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],46:[2,138],51:[2,138],54:[2,138],69:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],101:[2,138],102:[2,138],103:[2,138],107:[2,138],115:[2,138],123:[2,138],125:[2,138],126:[2,138],129:[2,138],130:[2,138],131:[2,138],132:[2,138],133:[2,138],134:[2,138]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],46:[2,146],51:[2,146],54:[2,146],69:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{25:[1,210],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{117:211,119:212,120:[1,213]},{1:[2,91],6:[2,91],25:[2,91],26:[2,91],46:[2,91],51:[2,91],54:[2,91],69:[2,91],75:[2,91],83:[2,91],88:[2,91],90:[2,91],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{14:214,15:120,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:121,41:60,55:47,56:48,58:215,60:25,61:26,62:27,73:[1,67],80:[1,28],85:[1,55],86:[1,56],87:[1,54],98:[1,53]},{1:[2,94],5:216,6:[2,94],25:[1,5],26:[2,94],46:[2,94],51:[2,94],54:[2,94],63:[2,66],64:[2,66],65:[2,66],67:[2,66],69:[2,94],70:[2,66],71:[2,66],75:[2,94],77:[1,217],81:[2,66],82:[2,66],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,42],6:[2,42],26:[2,42],99:[2,42],100:84,101:[2,42],103:[2,42],106:85,107:[2,42],108:66,123:[2,42],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,131],6:[2,131],26:[2,131],99:[2,131],100:84,101:[2,131],103:[2,131],106:85,107:[2,131],108:66,123:[2,131],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[1,71],99:[1,218]},{4:219,7:4,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,122],25:[2,122],51:[2,122],54:[1,221],88:[2,122],89:220,90:[1,188],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],37:[2,109],46:[2,109],51:[2,109],54:[2,109],63:[2,109],64:[2,109],65:[2,109],67:[2,109],69:[2,109],70:[2,109],71:[2,109],75:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],113:[2,109],114:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109]},{6:[2,49],25:[2,49],50:222,51:[1,223],88:[2,49]},{6:[2,117],25:[2,117],26:[2,117],51:[2,117],83:[2,117],88:[2,117]},{8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,144],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],84:224,85:[1,55],86:[1,56],87:[1,54],91:143,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,123],25:[2,123],26:[2,123],51:[2,123],83:[2,123],88:[2,123]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],37:[2,108],40:[2,108],46:[2,108],51:[2,108],54:[2,108],63:[2,108],64:[2,108],65:[2,108],67:[2,108],69:[2,108],70:[2,108],71:[2,108],75:[2,108],77:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],127:[2,108],128:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108],135:[2,108]},{5:225,25:[1,5],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],46:[2,134],51:[2,134],54:[2,134],69:[2,134],75:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],100:84,101:[1,62],102:[1,226],103:[1,63],106:85,107:[1,65],108:66,115:[2,134],123:[2,134],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],46:[2,136],51:[2,136],54:[2,136],69:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:84,101:[1,62],102:[1,227],103:[1,63],106:85,107:[1,65],108:66,115:[2,136],123:[2,136],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],46:[2,142],51:[2,142],54:[2,142],69:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],46:[2,143],51:[2,143],54:[2,143],69:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],100:84,101:[1,62],102:[2,143],103:[1,63],106:85,107:[1,65],108:66,115:[2,143],123:[2,143],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],46:[2,147],51:[2,147],54:[2,147],69:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{113:[2,149],114:[2,149]},{27:156,28:[1,70],55:157,56:158,73:[1,67],87:[1,112],110:228,112:155},{51:[1,229],113:[2,154],114:[2,154]},{51:[2,151],113:[2,151],114:[2,151]},{51:[2,152],113:[2,152],114:[2,152]},{51:[2,153],113:[2,153],114:[2,153]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],46:[2,148],51:[2,148],54:[2,148],69:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{8:230,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:231,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,49],25:[2,49],50:232,51:[1,233],75:[2,49]},{6:[2,86],25:[2,86],26:[2,86],51:[2,86],75:[2,86]},{6:[2,35],25:[2,35],26:[2,35],40:[1,234],51:[2,35],75:[2,35]},{6:[2,38],25:[2,38],26:[2,38],51:[2,38],75:[2,38]},{6:[2,39],25:[2,39],26:[2,39],40:[2,39],51:[2,39],75:[2,39]},{6:[2,40],25:[2,40],26:[2,40],40:[2,40],51:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],40:[2,41],51:[2,41],75:[2,41]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],46:[2,25],51:[2,25],54:[2,25],69:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],46:[2,185],51:[2,185],54:[2,185],69:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],100:84,101:[2,185],102:[2,185],103:[2,185],106:85,107:[2,185],108:66,115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[1,75],130:[1,78],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],46:[2,186],51:[2,186],54:[2,186],69:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],100:84,101:[2,186],102:[2,186],103:[2,186],106:85,107:[2,186],108:66,115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[1,75],130:[1,78],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],46:[2,187],51:[2,187],54:[2,187],69:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:84,101:[2,187],102:[2,187],103:[2,187],106:85,107:[2,187],108:66,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,75],130:[2,187],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],46:[2,188],51:[2,188],54:[2,188],69:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:84,101:[2,188],102:[2,188],103:[2,188],106:85,107:[2,188],108:66,115:[2,188],123:[2,188],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],46:[2,189],51:[2,189],54:[2,189],69:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:84,101:[2,189],102:[2,189],103:[2,189],106:85,107:[2,189],108:66,115:[2,189],123:[2,189],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[2,189],133:[2,189],134:[1,82]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],46:[2,190],51:[2,190],54:[2,190],69:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:84,101:[2,190],102:[2,190],103:[2,190],106:85,107:[2,190],108:66,115:[2,190],123:[2,190],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[2,190],134:[1,82]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],46:[2,191],51:[2,191],54:[2,191],69:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:84,101:[2,191],102:[2,191],103:[2,191],106:85,107:[2,191],108:66,115:[2,191],123:[2,191],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[2,191],133:[2,191],134:[2,191]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],46:[2,176],51:[2,176],54:[2,176],69:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],100:84,101:[1,62],102:[2,176],103:[1,63],106:85,107:[1,65],108:66,115:[2,176],123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],46:[2,175],51:[2,175],54:[2,175],69:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],100:84,101:[1,62],102:[2,175],103:[1,63],106:85,107:[1,65],108:66,115:[2,175],123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],46:[2,98],51:[2,98],54:[2,98],63:[2,98],64:[2,98],65:[2,98],67:[2,98],69:[2,98],70:[2,98],71:[2,98],75:[2,98],81:[2,98],82:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],37:[2,74],46:[2,74],51:[2,74],54:[2,74],63:[2,74],64:[2,74],65:[2,74],67:[2,74],69:[2,74],70:[2,74],71:[2,74],75:[2,74],77:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],127:[2,74],128:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74],135:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],37:[2,75],46:[2,75],51:[2,75],54:[2,75],63:[2,75],64:[2,75],65:[2,75],67:[2,75],69:[2,75],70:[2,75],71:[2,75],75:[2,75],77:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],127:[2,75],128:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75],135:[2,75]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],37:[2,76],46:[2,76],51:[2,76],54:[2,76],63:[2,76],64:[2,76],65:[2,76],67:[2,76],69:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{69:[1,235]},{54:[1,189],69:[2,82],89:236,90:[1,188],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{69:[2,83]},{8:237,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:[2,111],28:[2,111],30:[2,111],31:[2,111],33:[2,111],34:[2,111],35:[2,111],42:[2,111],43:[2,111],44:[2,111],48:[2,111],49:[2,111],69:[2,111],73:[2,111],76:[2,111],80:[2,111],85:[2,111],86:[2,111],87:[2,111],93:[2,111],97:[2,111],98:[2,111],101:[2,111],103:[2,111],105:[2,111],107:[2,111],116:[2,111],122:[2,111],124:[2,111],125:[2,111],126:[2,111],127:[2,111],128:[2,111]},{13:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],42:[2,112],43:[2,112],44:[2,112],48:[2,112],49:[2,112],69:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],37:[2,80],46:[2,80],51:[2,80],54:[2,80],63:[2,80],64:[2,80],65:[2,80],67:[2,80],69:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],37:[2,81],46:[2,81],51:[2,81],54:[2,81],63:[2,81],64:[2,81],65:[2,81],67:[2,81],69:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],46:[2,99],51:[2,99],54:[2,99],63:[2,99],64:[2,99],65:[2,99],67:[2,99],69:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],46:[2,33],51:[2,33],54:[2,33],69:[2,33],75:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],100:84,101:[2,33],102:[2,33],103:[2,33],106:85,107:[2,33],108:66,115:[2,33],123:[2,33],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{8:238,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,104],6:[2,104],25:[2,104],26:[2,104],46:[2,104],51:[2,104],54:[2,104],63:[2,104],64:[2,104],65:[2,104],67:[2,104],69:[2,104],70:[2,104],71:[2,104],75:[2,104],81:[2,104],82:[2,104],83:[2,104],88:[2,104],90:[2,104],99:[2,104],101:[2,104],102:[2,104],103:[2,104],107:[2,104],115:[2,104],123:[2,104],125:[2,104],126:[2,104],129:[2,104],130:[2,104],131:[2,104],132:[2,104],133:[2,104],134:[2,104]},{6:[2,49],25:[2,49],50:239,51:[1,223],83:[2,49]},{6:[2,122],25:[2,122],26:[2,122],51:[2,122],54:[1,240],83:[2,122],88:[2,122],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{47:241,48:[1,57],49:[1,58]},{27:107,28:[1,70],41:108,52:242,53:106,55:109,56:110,73:[1,67],86:[1,111],87:[1,112]},{46:[2,55],51:[2,55]},{8:243,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],46:[2,192],51:[2,192],54:[2,192],69:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:84,101:[2,192],102:[2,192],103:[2,192],106:85,107:[2,192],108:66,115:[2,192],123:[2,192],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{8:244,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],46:[2,194],51:[2,194],54:[2,194],69:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],100:84,101:[2,194],102:[2,194],103:[2,194],106:85,107:[2,194],108:66,115:[2,194],123:[2,194],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],46:[2,174],51:[2,174],54:[2,174],69:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{8:245,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,127],6:[2,127],25:[2,127],26:[2,127],46:[2,127],51:[2,127],54:[2,127],69:[2,127],75:[2,127],83:[2,127],88:[2,127],90:[2,127],95:[1,246],99:[2,127],101:[2,127],102:[2,127],103:[2,127],107:[2,127],115:[2,127],123:[2,127],125:[2,127],126:[2,127],129:[2,127],130:[2,127],131:[2,127],132:[2,127],133:[2,127],134:[2,127]},{5:247,25:[1,5]},{27:248,28:[1,70]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,167],118:[2,167],120:[2,167]},{8:254,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],92:253,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,92],5:255,6:[2,92],25:[1,5],26:[2,92],46:[2,92],51:[2,92],54:[2,92],59:90,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],69:[2,92],70:[1,97],71:[1,98],75:[2,92],78:89,81:[1,91],82:[2,102],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],46:[2,66],51:[2,66],54:[2,66],63:[2,66],64:[2,66],65:[2,66],67:[2,66],69:[2,66],70:[2,66],71:[2,66],75:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66]},{1:[2,95],6:[2,95],25:[2,95],26:[2,95],46:[2,95],51:[2,95],54:[2,95],69:[2,95],75:[2,95],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{14:256,15:120,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:121,41:60,55:47,56:48,58:215,60:25,61:26,62:27,73:[1,67],80:[1,28],85:[1,55],86:[1,56],87:[1,54],98:[1,53]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],46:[2,132],51:[2,132],54:[2,132],63:[2,132],64:[2,132],65:[2,132],67:[2,132],69:[2,132],70:[2,132],71:[2,132],75:[2,132],81:[2,132],82:[2,132],83:[2,132],88:[2,132],90:[2,132],99:[2,132],101:[2,132],102:[2,132],103:[2,132],107:[2,132],115:[2,132],123:[2,132],125:[2,132],126:[2,132],129:[2,132],130:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132]},{6:[1,71],26:[1,257]},{8:258,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,61],13:[2,112],25:[2,61],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],42:[2,112],43:[2,112],44:[2,112],48:[2,112],49:[2,112],51:[2,61],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],88:[2,61],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,50],8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[2,50],26:[2,50],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],83:[2,50],85:[1,55],86:[1,56],87:[1,54],88:[2,50],91:262,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,49],25:[2,49],26:[2,49],50:263,51:[1,223]},{1:[2,171],6:[2,171],25:[2,171],26:[2,171],46:[2,171],51:[2,171],54:[2,171],69:[2,171],75:[2,171],83:[2,171],88:[2,171],90:[2,171],99:[2,171],101:[2,171],102:[2,171],103:[2,171],107:[2,171],115:[2,171],118:[2,171],123:[2,171],125:[2,171],126:[2,171],129:[2,171],130:[2,171],131:[2,171],132:[2,171],133:[2,171],134:[2,171]},{8:264,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,150],114:[2,150]},{27:156,28:[1,70],55:157,56:158,73:[1,67],87:[1,112],112:266},{1:[2,156],6:[2,156],25:[2,156],26:[2,156],46:[2,156],51:[2,156],54:[2,156],69:[2,156],75:[2,156],83:[2,156],88:[2,156],90:[2,156],99:[2,156],100:84,101:[2,156],102:[1,267],103:[2,156],106:85,107:[2,156],108:66,115:[1,268],123:[2,156],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,157],6:[2,157],25:[2,157],26:[2,157],46:[2,157],51:[2,157],54:[2,157],69:[2,157],75:[2,157],83:[2,157],88:[2,157],90:[2,157],99:[2,157],100:84,101:[2,157],102:[1,269],103:[2,157],106:85,107:[2,157],108:66,115:[2,157],123:[2,157],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,50],12:165,25:[2,50],26:[2,50],27:166,28:[1,70],29:167,30:[1,68],31:[1,69],38:273,39:164,41:168,43:[1,46],75:[2,50],86:[1,111]},{8:274,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,275],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],37:[2,79],46:[2,79],51:[2,79],54:[2,79],63:[2,79],64:[2,79],65:[2,79],67:[2,79],69:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{8:276,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,69:[2,115],73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{69:[2,116],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{26:[1,277],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,61],25:[2,61],26:[2,61],51:[2,61],83:[2,61],88:[2,61]},{5:279,25:[1,5]},{46:[2,53],51:[2,53]},{46:[2,56],51:[2,56],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{26:[1,280],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{5:281,25:[1,5],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{5:282,25:[1,5]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],46:[2,128],51:[2,128],54:[2,128],69:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],46:[2,165],51:[2,165],54:[2,165],69:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{5:286,25:[1,5]},{26:[2,168],118:[2,168],120:[2,168]},{5:287,25:[1,5],51:[1,288]},{25:[2,124],51:[2,124],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,93],6:[2,93],25:[2,93],26:[2,93],46:[2,93],51:[2,93],54:[2,93],69:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],101:[2,93],102:[2,93],103:[2,93],107:[2,93],115:[2,93],123:[2,93],125:[2,93],126:[2,93],129:[2,93],130:[2,93],131:[2,93],132:[2,93],133:[2,93],134:[2,93]},{1:[2,96],5:289,6:[2,96],25:[1,5],26:[2,96],46:[2,96],51:[2,96],54:[2,96],59:90,63:[1,92],64:[1,93],65:[1,94],66:95,67:[1,96],69:[2,96],70:[1,97],71:[1,98],75:[2,96],78:89,81:[1,91],82:[2,102],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{99:[1,290]},{88:[1,291],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],37:[2,110],46:[2,110],51:[2,110],54:[2,110],63:[2,110],64:[2,110],65:[2,110],67:[2,110],69:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],91:292,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,144],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,57:145,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],84:293,85:[1,55],86:[1,56],87:[1,54],91:143,93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,118],25:[2,118],26:[2,118],51:[2,118],83:[2,118],88:[2,118]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],46:[2,135],51:[2,135],54:[2,135],69:[2,135],75:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],100:84,101:[1,62],102:[2,135],103:[1,63],106:85,107:[1,65],108:66,115:[2,135],123:[2,135],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],46:[2,137],51:[2,137],54:[2,137],69:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:84,101:[1,62],102:[2,137],103:[1,63],106:85,107:[1,65],108:66,115:[2,137],123:[2,137],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{113:[2,155],114:[2,155]},{8:295,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,84],6:[2,84],25:[2,84],26:[2,84],37:[2,84],46:[2,84],51:[2,84],54:[2,84],63:[2,84],64:[2,84],65:[2,84],67:[2,84],69:[2,84],70:[2,84],71:[2,84],75:[2,84],81:[2,84],82:[2,84],83:[2,84],88:[2,84],90:[2,84],99:[2,84],101:[2,84],102:[2,84],103:[2,84],107:[2,84],113:[2,84],114:[2,84],115:[2,84],123:[2,84],125:[2,84],126:[2,84],129:[2,84],130:[2,84],131:[2,84],132:[2,84],133:[2,84],134:[2,84]},{12:165,27:166,28:[1,70],29:167,30:[1,68],31:[1,69],38:298,39:164,41:168,43:[1,46],86:[1,111]},{6:[2,85],12:165,25:[2,85],26:[2,85],27:166,28:[1,70],29:167,30:[1,68],31:[1,69],38:163,39:164,41:168,43:[1,46],51:[2,85],74:299,86:[1,111]},{6:[2,87],25:[2,87],26:[2,87],51:[2,87],75:[2,87]},{6:[2,36],25:[2,36],26:[2,36],51:[2,36],75:[2,36],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{8:300,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{69:[2,114],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],46:[2,34],51:[2,34],54:[2,34],69:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],101:[2,34],102:[2,34],103:[2,34],107:[2,34],115:[2,34],123:[2,34],125:[2,34],126:[2,34],129:[2,34],130:[2,34],131:[2,34],132:[2,34],133:[2,34],134:[2,34]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],46:[2,105],51:[2,105],54:[2,105],63:[2,105],64:[2,105],65:[2,105],67:[2,105],69:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{1:[2,45],6:[2,45],25:[2,45],26:[2,45],46:[2,45],51:[2,45],54:[2,45],69:[2,45],75:[2,45],83:[2,45],88:[2,45],90:[2,45],99:[2,45],101:[2,45],102:[2,45],103:[2,45],107:[2,45],115:[2,45],123:[2,45],125:[2,45],126:[2,45],129:[2,45],130:[2,45],131:[2,45],132:[2,45],133:[2,45],134:[2,45]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],46:[2,193],51:[2,193],54:[2,193],69:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],101:[2,193],102:[2,193],103:[2,193],107:[2,193],115:[2,193],123:[2,193],125:[2,193],126:[2,193],129:[2,193],130:[2,193],131:[2,193],132:[2,193],133:[2,193],134:[2,193]},{1:[2,172],6:[2,172],25:[2,172],26:[2,172],46:[2,172],51:[2,172],54:[2,172],69:[2,172],75:[2,172],83:[2,172],88:[2,172],90:[2,172],99:[2,172],101:[2,172],102:[2,172],103:[2,172],107:[2,172],115:[2,172],118:[2,172],123:[2,172],125:[2,172],126:[2,172],129:[2,172],130:[2,172],131:[2,172],132:[2,172],133:[2,172],134:[2,172]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],46:[2,129],51:[2,129],54:[2,129],69:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],46:[2,130],51:[2,130],54:[2,130],69:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],95:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],46:[2,163],51:[2,163],54:[2,163],69:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],101:[2,163],102:[2,163],103:[2,163],107:[2,163],115:[2,163],123:[2,163],125:[2,163],126:[2,163],129:[2,163],130:[2,163],131:[2,163],132:[2,163],133:[2,163],134:[2,163]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,169],118:[2,169],120:[2,169]},{8:304,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,97],6:[2,97],25:[2,97],26:[2,97],46:[2,97],51:[2,97],54:[2,97],69:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],101:[2,97],102:[2,97],103:[2,97],107:[2,97],115:[2,97],123:[2,97],125:[2,97],126:[2,97],129:[2,97],130:[2,97],131:[2,97],132:[2,97],133:[2,97],134:[2,97]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],46:[2,133],51:[2,133],54:[2,133],63:[2,133],64:[2,133],65:[2,133],67:[2,133],69:[2,133],70:[2,133],71:[2,133],75:[2,133],81:[2,133],82:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],101:[2,133],102:[2,133],103:[2,133],107:[2,133],115:[2,133],123:[2,133],125:[2,133],126:[2,133],129:[2,133],130:[2,133],131:[2,133],132:[2,133],133:[2,133],134:[2,133]},{1:[2,113],6:[2,113],25:[2,113],26:[2,113],46:[2,113],51:[2,113],54:[2,113],63:[2,113],64:[2,113],65:[2,113],67:[2,113],69:[2,113],70:[2,113],71:[2,113],75:[2,113],81:[2,113],82:[2,113],83:[2,113],88:[2,113],90:[2,113],99:[2,113],101:[2,113],102:[2,113],103:[2,113],107:[2,113],115:[2,113],123:[2,113],125:[2,113],126:[2,113],129:[2,113],130:[2,113],131:[2,113],132:[2,113],133:[2,113],134:[2,113]},{6:[2,119],25:[2,119],26:[2,119],51:[2,119],83:[2,119],88:[2,119]},{6:[2,49],25:[2,49],26:[2,49],50:305,51:[1,223]},{6:[2,120],25:[2,120],26:[2,120],51:[2,120],83:[2,120],88:[2,120]},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],46:[2,158],51:[2,158],54:[2,158],69:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:84,101:[2,158],102:[2,158],103:[2,158],106:85,107:[2,158],108:66,115:[1,306],123:[2,158],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],46:[2,160],51:[2,160],54:[2,160],69:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:84,101:[2,160],102:[1,307],103:[2,160],106:85,107:[2,160],108:66,115:[2,160],123:[2,160],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],46:[2,159],51:[2,159],54:[2,159],69:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:84,101:[2,159],102:[2,159],103:[2,159],106:85,107:[2,159],108:66,115:[2,159],123:[2,159],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[2,88],25:[2,88],26:[2,88],51:[2,88],75:[2,88]},{6:[2,49],25:[2,49],26:[2,49],50:308,51:[1,233]},{26:[1,309],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{26:[1,310]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],46:[2,166],51:[2,166],54:[2,166],69:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{26:[2,170],118:[2,170],120:[2,170]},{25:[2,125],51:[2,125],100:84,101:[1,62],103:[1,63],106:85,107:[1,65],108:66,123:[1,83],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1,42],121:37,122:[1,61],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,37],25:[2,37],26:[2,37],51:[2,37],75:[2,37]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],46:[2,164],51:[2,164],54:[2,164],69:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],101:[2,164],102:[2,164],103:[2,164],107:[2,164],115:[2,164],123:[2,164],125:[2,164],126:[2,164],129:[2,164],130:[2,164],131:[2,164],132:[2,164],133:[2,164],134:[2,164]},{6:[2,121],25:[2,121],26:[2,121],51:[2,121],83:[2,121],88:[2,121]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],46:[2,161],51:[2,161],54:[2,161],69:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:84,101:[2,161],102:[2,161],103:[2,161],106:85,107:[2,161],108:66,115:[2,161],123:[2,161],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],46:[2,162],51:[2,162],54:[2,162],69:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:84,101:[2,162],102:[2,162],103:[2,162],106:85,107:[2,162],108:66,115:[2,162],123:[2,162],125:[1,77],126:[1,76],129:[1,75],130:[1,78],131:[1,79],132:[1,80],133:[1,81],134:[1,82]},{6:[2,89],25:[2,89],26:[2,89],51:[2,89],75:[2,89]}], -defaultActions: {57:[2,47],58:[2,48],72:[2,3],91:[2,103],186:[2,83]}, +table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,72]},{6:[1,73]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:75,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,74],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],47:[2,12],52:[2,12],55:[2,12],60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,12],71:[1,98],75:[2,12],78:90,81:[1,92],82:[2,103],83:[2,12],88:[2,12],90:[2,12],99:[2,12],101:[2,12],102:[2,12],103:[2,12],107:[2,12],115:[2,12],123:[2,12],125:[2,12],126:[2,12],129:[2,12],130:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],47:[2,13],52:[2,13],55:[2,13],60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,13],71:[1,98],75:[2,13],78:99,81:[1,92],82:[2,103],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],47:[2,14],52:[2,14],55:[2,14],70:[2,14],75:[2,14],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],47:[2,15],52:[2,15],55:[2,15],70:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],47:[2,16],52:[2,16],55:[2,16],70:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],47:[2,17],52:[2,17],55:[2,17],70:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],47:[2,18],52:[2,18],55:[2,18],70:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],47:[2,19],52:[2,19],55:[2,19],70:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],47:[2,20],52:[2,20],55:[2,20],70:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],47:[2,21],52:[2,21],55:[2,21],70:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],47:[2,22],52:[2,22],55:[2,22],70:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],47:[2,23],52:[2,23],55:[2,23],70:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],38:[1,101],47:[2,71],52:[2,71],55:[2,71],64:[2,71],65:[2,71],66:[2,71],68:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],47:[2,72],52:[2,72],55:[2,72],64:[2,72],65:[2,72],66:[2,72],68:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],47:[2,73],52:[2,73],55:[2,73],64:[2,73],65:[2,73],66:[2,73],68:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],47:[2,74],52:[2,74],55:[2,74],64:[2,74],65:[2,74],66:[2,74],68:[2,74],70:[2,74],71:[2,74],75:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],47:[2,75],52:[2,75],55:[2,75],64:[2,75],65:[2,75],66:[2,75],68:[2,75],70:[2,75],71:[2,75],75:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],47:[2,101],52:[2,101],55:[2,101],64:[2,101],65:[2,101],66:[2,101],68:[2,101],70:[2,101],71:[2,101],75:[2,101],79:102,81:[2,101],82:[1,103],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{27:107,28:[1,71],42:108,46:104,47:[2,53],52:[2,53],53:105,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:118,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:122,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],38:[2,68],47:[2,68],52:[2,68],55:[2,68],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,68],71:[2,68],75:[2,68],77:[1,126],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],127:[1,123],128:[1,124],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[1,125]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],47:[2,175],52:[2,175],55:[2,175],70:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],101:[2,175],102:[2,175],103:[2,175],107:[2,175],115:[2,175],118:[1,127],123:[2,175],125:[2,175],126:[2,175],129:[2,175],130:[2,175],131:[2,175],132:[2,175],133:[2,175],134:[2,175]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],47:[2,143],52:[2,143],55:[2,143],70:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],101:[2,143],102:[2,143],103:[2,143],107:[2,143],115:[2,143],123:[2,143],125:[2,143],126:[2,143],129:[2,143],130:[2,143],131:[2,143],132:[2,143],133:[2,143],134:[2,143]},{5:130,25:[1,5]},{8:131,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,132],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,91],5:133,6:[2,91],13:119,14:120,25:[1,5],26:[2,91],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,47:[2,91],52:[2,91],55:[2,91],56:47,57:48,59:135,61:25,62:26,63:27,70:[2,91],73:[1,68],75:[2,91],77:[1,134],80:[1,28],83:[2,91],85:[1,56],86:[1,57],87:[1,55],88:[2,91],90:[2,91],98:[1,54],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{8:136,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,45],6:[2,45],8:137,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,45],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,45],100:39,101:[2,45],103:[2,45],104:40,105:[1,65],106:41,107:[2,45],108:67,116:[1,42],121:37,122:[1,62],123:[2,45],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],52:[2,46],75:[2,46],99:[2,46],101:[2,46],103:[2,46],107:[2,46],123:[2,46]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],38:[2,69],47:[2,69],52:[2,69],55:[2,69],64:[2,69],65:[2,69],66:[2,69],68:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],38:[2,70],47:[2,70],52:[2,70],55:[2,70],64:[2,70],65:[2,70],66:[2,70],68:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],47:[2,29],52:[2,29],55:[2,29],64:[2,29],65:[2,29],66:[2,29],68:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],47:[2,30],52:[2,30],55:[2,30],64:[2,30],65:[2,30],66:[2,30],68:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],47:[2,31],52:[2,31],55:[2,31],64:[2,31],65:[2,31],66:[2,31],68:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],47:[2,32],52:[2,32],55:[2,32],64:[2,32],65:[2,32],66:[2,32],68:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],47:[2,33],52:[2,33],55:[2,33],64:[2,33],65:[2,33],66:[2,33],68:[2,33],70:[2,33],71:[2,33],75:[2,33],81:[2,33],82:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],101:[2,33],102:[2,33],103:[2,33],107:[2,33],115:[2,33],123:[2,33],125:[2,33],126:[2,33],129:[2,33],130:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33]},{4:138,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,139],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],47:[2,107],52:[2,107],55:[2,107],64:[2,107],65:[2,107],66:[2,107],68:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],27:146,28:[1,71],47:[2,108],52:[2,108],55:[2,108],64:[2,108],65:[2,108],66:[2,108],68:[2,108],70:[2,108],71:[2,108],75:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108]},{25:[2,49]},{25:[2,50]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],38:[2,64],47:[2,64],52:[2,64],55:[2,64],64:[2,64],65:[2,64],66:[2,64],68:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],38:[2,67],47:[2,67],52:[2,67],55:[2,67],64:[2,67],65:[2,67],66:[2,67],68:[2,67],70:[2,67],71:[2,67],75:[2,67],77:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],127:[2,67],128:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67],135:[2,67]},{8:147,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,71],56:157,57:158,62:152,73:[1,68],87:[1,55],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,86],11:165,25:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:162,75:[2,86],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],41:[2,27],47:[2,27],52:[2,27],55:[2,27],64:[2,27],65:[2,27],66:[2,27],68:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],41:[2,28],47:[2,28],52:[2,28],55:[2,28],64:[2,28],65:[2,28],66:[2,28],68:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],38:[2,26],41:[2,26],47:[2,26],52:[2,26],55:[2,26],64:[2,26],65:[2,26],66:[2,26],68:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,6],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],47:[2,24],52:[2,24],55:[2,24],70:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,72],26:[1,170]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],47:[2,186],52:[2,186],55:[2,186],70:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],101:[2,186],102:[2,186],103:[2,186],107:[2,186],115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[2,186],130:[2,186],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{8:171,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],47:[2,142],52:[2,142],55:[2,142],70:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],47:[2,147],52:[2,147],55:[2,147],70:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{8:179,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],47:[2,141],52:[2,141],55:[2,141],70:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],47:[2,146],52:[2,146],55:[2,146],70:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{79:180,82:[1,103]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],38:[2,65],47:[2,65],52:[2,65],55:[2,65],64:[2,65],65:[2,65],66:[2,65],68:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{82:[2,104]},{27:181,28:[1,71]},{27:182,28:[1,71]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],27:183,28:[1,71],38:[2,79],47:[2,79],52:[2,79],55:[2,79],64:[2,79],65:[2,79],66:[2,79],68:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],38:[2,80],47:[2,80],52:[2,80],55:[2,80],64:[2,80],65:[2,80],66:[2,80],68:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{8:185,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],55:[1,189],56:47,57:48,59:36,61:25,62:26,63:27,69:184,72:186,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],89:187,90:[1,188],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{67:190,68:[1,97],71:[1,98]},{79:191,82:[1,103]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],38:[2,66],47:[2,66],52:[2,66],55:[2,66],64:[2,66],65:[2,66],66:[2,66],68:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[2,66],128:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[2,66]},{6:[1,193],8:192,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,194],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],47:[2,102],52:[2,102],55:[2,102],64:[2,102],65:[2,102],66:[2,102],68:[2,102],70:[2,102],71:[2,102],75:[2,102],81:[2,102],82:[2,102],83:[2,102],88:[2,102],90:[2,102],99:[2,102],101:[2,102],102:[2,102],103:[2,102],107:[2,102],115:[2,102],123:[2,102],125:[2,102],126:[2,102],129:[2,102],130:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{47:[1,198],52:[1,199]},{47:[2,54],52:[2,54]},{38:[1,201],47:[2,56],52:[2,56],55:[1,200]},{38:[2,59],47:[2,59],52:[2,59],55:[2,59]},{38:[2,60],47:[2,60],52:[2,60],55:[2,60]},{38:[2,61],47:[2,61],52:[2,61],55:[2,61]},{38:[2,62],47:[2,62],52:[2,62],55:[2,62]},{27:146,28:[1,71]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],47:[2,48],52:[2,48],55:[2,48],70:[2,48],75:[2,48],83:[2,48],88:[2,48],90:[2,48],99:[2,48],101:[2,48],102:[2,48],103:[2,48],107:[2,48],115:[2,48],123:[2,48],125:[2,48],126:[2,48],129:[2,48],130:[2,48],131:[2,48],132:[2,48],133:[2,48],134:[2,48]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],47:[2,179],52:[2,179],55:[2,179],70:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:85,101:[2,179],102:[2,179],103:[2,179],106:86,107:[2,179],108:67,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,76],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],47:[2,180],52:[2,180],55:[2,180],70:[2,180],75:[2,180],83:[2,180],88:[2,180],90:[2,180],99:[2,180],100:85,101:[2,180],102:[2,180],103:[2,180],106:86,107:[2,180],108:67,115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[1,76],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],47:[2,181],52:[2,181],55:[2,181],70:[2,181],75:[2,181],83:[2,181],88:[2,181],90:[2,181],99:[2,181],100:85,101:[2,181],102:[2,181],103:[2,181],106:86,107:[2,181],108:67,115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[1,76],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],47:[2,182],52:[2,182],55:[2,182],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,182],71:[2,68],75:[2,182],81:[2,68],82:[2,68],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:90,81:[1,92],82:[2,103]},{60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:99,81:[1,92],82:[2,103]},{64:[2,71],65:[2,71],66:[2,71],68:[2,71],71:[2,71],81:[2,71],82:[2,71]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],47:[2,183],52:[2,183],55:[2,183],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,183],71:[2,68],75:[2,183],81:[2,68],82:[2,68],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],47:[2,184],52:[2,184],55:[2,184],70:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],47:[2,185],52:[2,185],55:[2,185],70:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],101:[2,185],102:[2,185],103:[2,185],107:[2,185],115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[2,185],130:[2,185],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{8:202,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,203],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],47:[2,128],52:[2,128],55:[2,128],70:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],94:207,95:[1,208],96:[1,209],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],47:[2,140],52:[2,140],55:[2,140],70:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],47:[2,148],52:[2,148],55:[2,148],70:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{25:[1,210],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{117:211,119:212,120:[1,213]},{1:[2,92],6:[2,92],25:[2,92],26:[2,92],47:[2,92],52:[2,92],55:[2,92],70:[2,92],75:[2,92],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{8:214,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,95],5:215,6:[2,95],25:[1,5],26:[2,95],47:[2,95],52:[2,95],55:[2,95],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,95],71:[2,68],75:[2,95],77:[1,216],81:[2,68],82:[2,68],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],47:[2,133],52:[2,133],55:[2,133],70:[2,133],75:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],100:85,101:[2,133],102:[2,133],103:[2,133],106:86,107:[2,133],108:67,115:[2,133],123:[2,133],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,44],6:[2,44],26:[2,44],99:[2,44],100:85,101:[2,44],103:[2,44],106:86,107:[2,44],108:67,123:[2,44],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,72],99:[1,217]},{4:218,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,124],25:[2,124],52:[2,124],55:[1,220],88:[2,124],89:219,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],38:[2,110],47:[2,110],52:[2,110],55:[2,110],64:[2,110],65:[2,110],66:[2,110],68:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{6:[2,51],25:[2,51],51:221,52:[1,222],88:[2,51]},{6:[2,119],25:[2,119],26:[2,119],52:[2,119],83:[2,119],88:[2,119]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:223,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,125],25:[2,125],26:[2,125],52:[2,125],83:[2,125],88:[2,125]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],38:[2,109],41:[2,109],47:[2,109],52:[2,109],55:[2,109],64:[2,109],65:[2,109],66:[2,109],68:[2,109],70:[2,109],71:[2,109],75:[2,109],77:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],127:[2,109],128:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109]},{5:224,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],47:[2,136],52:[2,136],55:[2,136],70:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:85,101:[1,63],102:[1,225],103:[1,64],106:86,107:[1,66],108:67,115:[2,136],123:[2,136],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],47:[2,138],52:[2,138],55:[2,138],70:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],100:85,101:[1,63],102:[1,226],103:[1,64],106:86,107:[1,66],108:67,115:[2,138],123:[2,138],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],47:[2,144],52:[2,144],55:[2,144],70:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],101:[2,144],102:[2,144],103:[2,144],107:[2,144],115:[2,144],123:[2,144],125:[2,144],126:[2,144],129:[2,144],130:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],47:[2,145],52:[2,145],55:[2,145],70:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],100:85,101:[1,63],102:[2,145],103:[1,64],106:86,107:[1,66],108:67,115:[2,145],123:[2,145],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],47:[2,149],52:[2,149],55:[2,149],70:[2,149],75:[2,149],83:[2,149],88:[2,149],90:[2,149],99:[2,149],101:[2,149],102:[2,149],103:[2,149],107:[2,149],115:[2,149],123:[2,149],125:[2,149],126:[2,149],129:[2,149],130:[2,149],131:[2,149],132:[2,149],133:[2,149],134:[2,149]},{113:[2,151],114:[2,151]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],110:227,112:155},{52:[1,228],113:[2,156],114:[2,156]},{52:[2,153],113:[2,153],114:[2,153]},{52:[2,154],113:[2,154],114:[2,154]},{52:[2,155],113:[2,155],114:[2,155]},{1:[2,150],6:[2,150],25:[2,150],26:[2,150],47:[2,150],52:[2,150],55:[2,150],70:[2,150],75:[2,150],83:[2,150],88:[2,150],90:[2,150],99:[2,150],101:[2,150],102:[2,150],103:[2,150],107:[2,150],115:[2,150],123:[2,150],125:[2,150],126:[2,150],129:[2,150],130:[2,150],131:[2,150],132:[2,150],133:[2,150],134:[2,150]},{8:229,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:230,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],51:231,52:[1,232],75:[2,51]},{6:[2,87],25:[2,87],26:[2,87],52:[2,87],75:[2,87]},{6:[2,37],25:[2,37],26:[2,37],41:[1,233],52:[2,37],75:[2,37]},{6:[2,40],25:[2,40],26:[2,40],52:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],41:[2,41],52:[2,41],75:[2,41]},{6:[2,42],25:[2,42],26:[2,42],41:[2,42],52:[2,42],75:[2,42]},{6:[2,43],25:[2,43],26:[2,43],41:[2,43],52:[2,43],75:[2,43]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],47:[2,25],52:[2,25],55:[2,25],70:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],47:[2,187],52:[2,187],55:[2,187],70:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:85,101:[2,187],102:[2,187],103:[2,187],106:86,107:[2,187],108:67,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,76],130:[1,79],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],47:[2,188],52:[2,188],55:[2,188],70:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:85,101:[2,188],102:[2,188],103:[2,188],106:86,107:[2,188],108:67,115:[2,188],123:[2,188],125:[2,188],126:[2,188],129:[1,76],130:[1,79],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],47:[2,189],52:[2,189],55:[2,189],70:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:85,101:[2,189],102:[2,189],103:[2,189],106:86,107:[2,189],108:67,115:[2,189],123:[2,189],125:[2,189],126:[2,189],129:[1,76],130:[2,189],131:[2,189],132:[2,189],133:[2,189],134:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],47:[2,190],52:[2,190],55:[2,190],70:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:85,101:[2,190],102:[2,190],103:[2,190],106:86,107:[2,190],108:67,115:[2,190],123:[2,190],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[2,190],132:[2,190],133:[2,190],134:[2,190]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],47:[2,191],52:[2,191],55:[2,191],70:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:85,101:[2,191],102:[2,191],103:[2,191],106:86,107:[2,191],108:67,115:[2,191],123:[2,191],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,191],133:[2,191],134:[1,83]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],47:[2,192],52:[2,192],55:[2,192],70:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:85,101:[2,192],102:[2,192],103:[2,192],106:86,107:[2,192],108:67,115:[2,192],123:[2,192],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[2,192],134:[1,83]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],47:[2,193],52:[2,193],55:[2,193],70:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],100:85,101:[2,193],102:[2,193],103:[2,193],106:86,107:[2,193],108:67,115:[2,193],123:[2,193],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,193],133:[2,193],134:[2,193]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],47:[2,178],52:[2,178],55:[2,178],70:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:85,101:[1,63],102:[2,178],103:[1,64],106:86,107:[1,66],108:67,115:[2,178],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],47:[2,177],52:[2,177],55:[2,177],70:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:85,101:[1,63],102:[2,177],103:[1,64],106:86,107:[1,66],108:67,115:[2,177],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],47:[2,99],52:[2,99],55:[2,99],64:[2,99],65:[2,99],66:[2,99],68:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],38:[2,76],47:[2,76],52:[2,76],55:[2,76],64:[2,76],65:[2,76],66:[2,76],68:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],38:[2,77],47:[2,77],52:[2,77],55:[2,77],64:[2,77],65:[2,77],66:[2,77],68:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],38:[2,78],47:[2,78],52:[2,78],55:[2,78],64:[2,78],65:[2,78],66:[2,78],68:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{70:[1,234]},{55:[1,189],70:[2,83],89:235,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{70:[2,84]},{8:236,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,118],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{12:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],36:[2,112],43:[2,112],44:[2,112],45:[2,112],49:[2,112],50:[2,112],70:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{12:[2,113],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],70:[2,113],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],38:[2,82],47:[2,82],52:[2,82],55:[2,82],64:[2,82],65:[2,82],66:[2,82],68:[2,82],70:[2,82],71:[2,82],75:[2,82],77:[2,82],81:[2,82],82:[2,82],83:[2,82],88:[2,82],90:[2,82],99:[2,82],101:[2,82],102:[2,82],103:[2,82],107:[2,82],115:[2,82],123:[2,82],125:[2,82],126:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],47:[2,100],52:[2,100],55:[2,100],64:[2,100],65:[2,100],66:[2,100],68:[2,100],70:[2,100],71:[2,100],75:[2,100],81:[2,100],82:[2,100],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],47:[2,34],52:[2,34],55:[2,34],70:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],100:85,101:[2,34],102:[2,34],103:[2,34],106:86,107:[2,34],108:67,115:[2,34],123:[2,34],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:237,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:238,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],47:[2,105],52:[2,105],55:[2,105],64:[2,105],65:[2,105],66:[2,105],68:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{6:[2,51],25:[2,51],51:239,52:[1,222],83:[2,51]},{6:[2,124],25:[2,124],26:[2,124],52:[2,124],55:[1,240],83:[2,124],88:[2,124],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{48:241,49:[1,58],50:[1,59]},{27:107,28:[1,71],42:108,53:242,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{47:[2,57],52:[2,57]},{8:243,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],47:[2,194],52:[2,194],55:[2,194],70:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],100:85,101:[2,194],102:[2,194],103:[2,194],106:86,107:[2,194],108:67,115:[2,194],123:[2,194],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:244,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,196],6:[2,196],25:[2,196],26:[2,196],47:[2,196],52:[2,196],55:[2,196],70:[2,196],75:[2,196],83:[2,196],88:[2,196],90:[2,196],99:[2,196],100:85,101:[2,196],102:[2,196],103:[2,196],106:86,107:[2,196],108:67,115:[2,196],123:[2,196],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],47:[2,176],52:[2,176],55:[2,176],70:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],101:[2,176],102:[2,176],103:[2,176],107:[2,176],115:[2,176],123:[2,176],125:[2,176],126:[2,176],129:[2,176],130:[2,176],131:[2,176],132:[2,176],133:[2,176],134:[2,176]},{8:245,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],47:[2,129],52:[2,129],55:[2,129],70:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],95:[1,246],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{5:247,25:[1,5]},{27:248,28:[1,71]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,169],118:[2,169],120:[2,169]},{8:254,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],92:253,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,93],5:255,6:[2,93],25:[1,5],26:[2,93],47:[2,93],52:[2,93],55:[2,93],70:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],100:85,101:[1,63],102:[2,93],103:[1,64],106:86,107:[1,66],108:67,115:[2,93],123:[2,93],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],47:[2,96],52:[2,96],55:[2,96],70:[2,96],75:[2,96],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{8:256,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],47:[2,134],52:[2,134],55:[2,134],64:[2,134],65:[2,134],66:[2,134],68:[2,134],70:[2,134],71:[2,134],75:[2,134],81:[2,134],82:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],101:[2,134],102:[2,134],103:[2,134],107:[2,134],115:[2,134],123:[2,134],125:[2,134],126:[2,134],129:[2,134],130:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134]},{6:[1,72],26:[1,257]},{8:258,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,63],12:[2,113],25:[2,63],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],52:[2,63],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],88:[2,63],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,52],8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,52],26:[2,52],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[2,52],85:[1,56],86:[1,57],87:[1,55],88:[2,52],91:262,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],26:[2,51],51:263,52:[1,222]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],47:[2,173],52:[2,173],55:[2,173],70:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[2,173],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{8:264,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,152],114:[2,152]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],112:266},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],47:[2,158],52:[2,158],55:[2,158],70:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:85,101:[2,158],102:[1,267],103:[2,158],106:86,107:[2,158],108:67,115:[1,268],123:[2,158],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],47:[2,159],52:[2,159],55:[2,159],70:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:85,101:[2,159],102:[1,269],103:[2,159],106:86,107:[2,159],108:67,115:[2,159],123:[2,159],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,52],11:165,25:[2,52],26:[2,52],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:273,40:164,42:168,44:[1,46],75:[2,52],86:[1,111]},{8:274,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,275],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],38:[2,81],47:[2,81],52:[2,81],55:[2,81],64:[2,81],65:[2,81],66:[2,81],68:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{8:276,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,116],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,117],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],47:[2,35],52:[2,35],55:[2,35],70:[2,35],75:[2,35],83:[2,35],88:[2,35],90:[2,35],99:[2,35],100:85,101:[2,35],102:[2,35],103:[2,35],106:86,107:[2,35],108:67,115:[2,35],123:[2,35],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,277],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,63],25:[2,63],26:[2,63],52:[2,63],83:[2,63],88:[2,63]},{5:279,25:[1,5]},{47:[2,55],52:[2,55]},{47:[2,58],52:[2,58],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,280],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:281,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:282,25:[1,5]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],47:[2,130],52:[2,130],55:[2,130],70:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],47:[2,167],52:[2,167],55:[2,167],70:[2,167],75:[2,167],83:[2,167],88:[2,167],90:[2,167],99:[2,167],101:[2,167],102:[2,167],103:[2,167],107:[2,167],115:[2,167],123:[2,167],125:[2,167],126:[2,167],129:[2,167],130:[2,167],131:[2,167],132:[2,167],133:[2,167],134:[2,167]},{5:286,25:[1,5]},{26:[2,170],118:[2,170],120:[2,170]},{5:287,25:[1,5],52:[1,288]},{25:[2,126],52:[2,126],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,94],6:[2,94],25:[2,94],26:[2,94],47:[2,94],52:[2,94],55:[2,94],70:[2,94],75:[2,94],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,97],5:289,6:[2,97],25:[1,5],26:[2,97],47:[2,97],52:[2,97],55:[2,97],70:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],100:85,101:[1,63],102:[2,97],103:[1,64],106:86,107:[1,66],108:67,115:[2,97],123:[2,97],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{99:[1,290]},{88:[1,291],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],38:[2,111],47:[2,111],52:[2,111],55:[2,111],64:[2,111],65:[2,111],66:[2,111],68:[2,111],70:[2,111],71:[2,111],75:[2,111],81:[2,111],82:[2,111],83:[2,111],88:[2,111],90:[2,111],99:[2,111],101:[2,111],102:[2,111],103:[2,111],107:[2,111],113:[2,111],114:[2,111],115:[2,111],123:[2,111],125:[2,111],126:[2,111],129:[2,111],130:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],91:292,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:293,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,120],25:[2,120],26:[2,120],52:[2,120],83:[2,120],88:[2,120]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],47:[2,137],52:[2,137],55:[2,137],70:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:85,101:[1,63],102:[2,137],103:[1,64],106:86,107:[1,66],108:67,115:[2,137],123:[2,137],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],47:[2,139],52:[2,139],55:[2,139],70:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],100:85,101:[1,63],102:[2,139],103:[1,64],106:86,107:[1,66],108:67,115:[2,139],123:[2,139],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{113:[2,157],114:[2,157]},{8:295,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],38:[2,85],47:[2,85],52:[2,85],55:[2,85],64:[2,85],65:[2,85],66:[2,85],68:[2,85],70:[2,85],71:[2,85],75:[2,85],81:[2,85],82:[2,85],83:[2,85],88:[2,85],90:[2,85],99:[2,85],101:[2,85],102:[2,85],103:[2,85],107:[2,85],113:[2,85],114:[2,85],115:[2,85],123:[2,85],125:[2,85],126:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85]},{11:165,27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:298,40:164,42:168,44:[1,46],86:[1,111]},{6:[2,86],11:165,25:[2,86],26:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:299,86:[1,111]},{6:[2,88],25:[2,88],26:[2,88],52:[2,88],75:[2,88]},{6:[2,38],25:[2,38],26:[2,38],52:[2,38],75:[2,38],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:300,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,115],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],47:[2,36],52:[2,36],55:[2,36],70:[2,36],75:[2,36],83:[2,36],88:[2,36],90:[2,36],99:[2,36],101:[2,36],102:[2,36],103:[2,36],107:[2,36],115:[2,36],123:[2,36],125:[2,36],126:[2,36],129:[2,36],130:[2,36],131:[2,36],132:[2,36],133:[2,36],134:[2,36]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],47:[2,106],52:[2,106],55:[2,106],64:[2,106],65:[2,106],66:[2,106],68:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,47],6:[2,47],25:[2,47],26:[2,47],47:[2,47],52:[2,47],55:[2,47],70:[2,47],75:[2,47],83:[2,47],88:[2,47],90:[2,47],99:[2,47],101:[2,47],102:[2,47],103:[2,47],107:[2,47],115:[2,47],123:[2,47],125:[2,47],126:[2,47],129:[2,47],130:[2,47],131:[2,47],132:[2,47],133:[2,47],134:[2,47]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],47:[2,195],52:[2,195],55:[2,195],70:[2,195],75:[2,195],83:[2,195],88:[2,195],90:[2,195],99:[2,195],101:[2,195],102:[2,195],103:[2,195],107:[2,195],115:[2,195],123:[2,195],125:[2,195],126:[2,195],129:[2,195],130:[2,195],131:[2,195],132:[2,195],133:[2,195],134:[2,195]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],47:[2,174],52:[2,174],55:[2,174],70:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],118:[2,174],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{1:[2,131],6:[2,131],25:[2,131],26:[2,131],47:[2,131],52:[2,131],55:[2,131],70:[2,131],75:[2,131],83:[2,131],88:[2,131],90:[2,131],99:[2,131],101:[2,131],102:[2,131],103:[2,131],107:[2,131],115:[2,131],123:[2,131],125:[2,131],126:[2,131],129:[2,131],130:[2,131],131:[2,131],132:[2,131],133:[2,131],134:[2,131]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],47:[2,132],52:[2,132],55:[2,132],70:[2,132],75:[2,132],83:[2,132],88:[2,132],90:[2,132],95:[2,132],99:[2,132],101:[2,132],102:[2,132],103:[2,132],107:[2,132],115:[2,132],123:[2,132],125:[2,132],126:[2,132],129:[2,132],130:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],47:[2,165],52:[2,165],55:[2,165],70:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,171],118:[2,171],120:[2,171]},{8:304,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],47:[2,98],52:[2,98],55:[2,98],70:[2,98],75:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],47:[2,135],52:[2,135],55:[2,135],64:[2,135],65:[2,135],66:[2,135],68:[2,135],70:[2,135],71:[2,135],75:[2,135],81:[2,135],82:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],101:[2,135],102:[2,135],103:[2,135],107:[2,135],115:[2,135],123:[2,135],125:[2,135],126:[2,135],129:[2,135],130:[2,135],131:[2,135],132:[2,135],133:[2,135],134:[2,135]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],47:[2,114],52:[2,114],55:[2,114],64:[2,114],65:[2,114],66:[2,114],68:[2,114],70:[2,114],71:[2,114],75:[2,114],81:[2,114],82:[2,114],83:[2,114],88:[2,114],90:[2,114],99:[2,114],101:[2,114],102:[2,114],103:[2,114],107:[2,114],115:[2,114],123:[2,114],125:[2,114],126:[2,114],129:[2,114],130:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114]},{6:[2,121],25:[2,121],26:[2,121],52:[2,121],83:[2,121],88:[2,121]},{6:[2,51],25:[2,51],26:[2,51],51:305,52:[1,222]},{6:[2,122],25:[2,122],26:[2,122],52:[2,122],83:[2,122],88:[2,122]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],47:[2,160],52:[2,160],55:[2,160],70:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:85,101:[2,160],102:[2,160],103:[2,160],106:86,107:[2,160],108:67,115:[1,306],123:[2,160],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],47:[2,162],52:[2,162],55:[2,162],70:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:85,101:[2,162],102:[1,307],103:[2,162],106:86,107:[2,162],108:67,115:[2,162],123:[2,162],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],47:[2,161],52:[2,161],55:[2,161],70:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:85,101:[2,161],102:[2,161],103:[2,161],106:86,107:[2,161],108:67,115:[2,161],123:[2,161],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,89],25:[2,89],26:[2,89],52:[2,89],75:[2,89]},{6:[2,51],25:[2,51],26:[2,51],51:308,52:[1,232]},{26:[1,309],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,310]},{1:[2,168],6:[2,168],25:[2,168],26:[2,168],47:[2,168],52:[2,168],55:[2,168],70:[2,168],75:[2,168],83:[2,168],88:[2,168],90:[2,168],99:[2,168],101:[2,168],102:[2,168],103:[2,168],107:[2,168],115:[2,168],123:[2,168],125:[2,168],126:[2,168],129:[2,168],130:[2,168],131:[2,168],132:[2,168],133:[2,168],134:[2,168]},{26:[2,172],118:[2,172],120:[2,172]},{25:[2,127],52:[2,127],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,39],25:[2,39],26:[2,39],52:[2,39],75:[2,39]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],47:[2,166],52:[2,166],55:[2,166],70:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{6:[2,123],25:[2,123],26:[2,123],52:[2,123],83:[2,123],88:[2,123]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],47:[2,163],52:[2,163],55:[2,163],70:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],100:85,101:[2,163],102:[2,163],103:[2,163],106:86,107:[2,163],108:67,115:[2,163],123:[2,163],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],47:[2,164],52:[2,164],55:[2,164],70:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],100:85,101:[2,164],102:[2,164],103:[2,164],106:86,107:[2,164],108:67,115:[2,164],123:[2,164],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,90],25:[2,90],26:[2,90],52:[2,90],75:[2,90]}], +defaultActions: {58:[2,49],59:[2,50],73:[2,3],92:[2,104],186:[2,84]}, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { - var self = this, - stack = [0], - vstack = [null], // semantic value stack - lstack = [], // location stack - table = this.table, - yytext = '', - yylineno = 0, - yyleng = 0, - recovering = 0, - TERROR = 2, - EOF = 1; - - //this.reductionCount = this.shiftCount = 0; - + var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; - if (typeof this.lexer.yylloc == 'undefined') + if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); - - if (typeof this.yy.parseError === 'function') + if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; - - function popStack (n) { - stack.length = stack.length - 2*n; + function popStack(n) { + stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } - function lex() { var token; - token = self.lexer.lex() || 1; // $end = 1 - // if token isn't its numeric value, convert - if (typeof token !== 'number') { + token = self.lexer.lex() || 1; + if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; - }; - - var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected; + } + var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { - // retreive state number from top of stack - state = stack[stack.length-1]; - - // use default actions if available + state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol == null) symbol = lex(); - // read action for current state and first input action = table[state] && table[state][symbol]; } - - // handle parse error - if (typeof action === 'undefined' || !action.length || !action[0]) { - + if (typeof action === "undefined" || !action.length || !action[0]) { if (!recovering) { - // Report error expected = []; - for (p in table[state]) if (this.terminals_[p] && p > 2) { - expected.push("'"+this.terminals_[p]+"'"); - } - var errStr = ''; + for (p in table[state]) + if (this.terminals_[p] && p > 2) { + expected.push("'" + this.terminals_[p] + "'"); + } + var errStr = ""; if (this.lexer.showPosition) { - errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+'\nExpecting '+expected.join(', '); + errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'"; } else { - errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " + - (symbol == 1 /*EOF*/ ? "end of input" : - ("'"+(this.terminals_[symbol] || symbol)+"'")); + errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } - this.parseError(errStr, - {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); + this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); } - - // just recovered from another error - if (recovering == 3) { - if (symbol == EOF) { - throw new Error(errStr || 'Parsing halted.'); - } - - // discard current lookahead and grab another + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(this.lexer.yytext); + lstack.push(this.lexer.yylloc); + stack.push(action[1]); + symbol = null; + if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; - symbol = lex(); + if (recovering > 0) + recovering--; + } else { + symbol = preErrorSymbol; + preErrorSymbol = null; } - - // try to recover from error - while (1) { - // check for error recovery rule in this state - if ((TERROR.toString()) in table[state]) { - break; - } - if (state == 0) { - throw new Error(errStr || 'Parsing halted.'); - } - popStack(1); - state = stack[stack.length-1]; + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; + r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); + if (typeof r !== "undefined") { + return r; } - - preErrorSymbol = symbol; // save the lookahead token - symbol = TERROR; // insert generic error symbol as new lookahead - state = stack[stack.length-1]; - action = table[state] && table[state][TERROR]; - recovering = 3; // allow 3 real symbols to be shifted before reporting a new error - } - - // this shouldn't happen, unless resolve defaults are off - if (action[0] instanceof Array && action.length > 1) { - throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol); - } - - switch (action[0]) { - - case 1: // shift - //this.shiftCount++; - - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); // push state - symbol = null; - if (!preErrorSymbol) { // normal execution/no error - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { // error just occurred, resume old lookahead f/ before error - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - - case 2: // reduce - //this.reductionCount++; - - len = this.productions_[action[1]][1]; - - // perform semantic action - yyval.$ = vstack[vstack.length-len]; // default to $$ = $1 - // default location, uses first token for firsts, last for lasts - yyval._$ = { - first_line: lstack[lstack.length-(len||1)].first_line, - last_line: lstack[lstack.length-1].last_line, - first_column: lstack[lstack.length-(len||1)].first_column, - last_column: lstack[lstack.length-1].last_column - }; - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - - if (typeof r !== 'undefined') { - return r; - } - - // pop off stack - if (len) { - stack = stack.slice(0,-1*len*2); - vstack = vstack.slice(0, -1*len); - lstack = lstack.slice(0, -1*len); - } - - stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce) - vstack.push(yyval.$); - lstack.push(yyval._$); - // goto new state = table[STATE][NONTERMINAL] - newState = table[stack[stack.length-2]][stack[stack.length-1]]; - stack.push(newState); - break; - - case 3: // accept - return true; + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; } - } - return true; -}}; +} +}; module.exports = parser; + + });/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -4631,45 +4591,49 @@ module.exports = parser; * OTHER DEALINGS IN THE SOFTWARE. */ -define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coffee/scope', 'ace/mode/coffee/helpers'], function(require, exports, module) { - var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, Push, Range, Return, SIMPLENUM, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref; - var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { - for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } - function ctor() { this.constructor = child; } - ctor.prototype = parent.prototype; - child.prototype = new ctor; - child.__super__ = parent.prototype; - return child; - }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __indexOf = Array.prototype.indexOf || function(item) { - for (var i = 0, l = this.length; i < l; i++) { - if (this[i] === item) return i; - } - return -1; - }; +define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coffee/scope', 'ace/mode/coffee/lexer', 'ace/mode/coffee/helpers'], function(require, exports, module) { +// Generated by CoffeeScript 1.2.1-pre + + var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref, _ref1, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + Scope = require('./scope').Scope; - _ref = require('./helpers'), compact = _ref.compact, flatten = _ref.flatten, extend = _ref.extend, merge = _ref.merge, del = _ref.del, starts = _ref.starts, ends = _ref.ends, last = _ref.last; + + _ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED; + + _ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last; + exports.extend = extend; + YES = function() { return true; }; + NO = function() { return false; }; + THIS = function() { return this; }; + NEGATE = function() { this.negated = !this.negated; return this; }; + exports.Base = Base = (function() { + + Base.name = 'Base'; + function Base() {} + Base.prototype.compile = function(o, lvl) { var node; o = extend({}, o); - if (lvl) { - o.level = lvl; - } + if (lvl) o.level = lvl; node = this.unfoldSoak(o) || this; node.tab = o.indent; if (o.level === LEVEL_TOP || !node.isStatement(o)) { @@ -4678,13 +4642,15 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return node.compileClosure(o); } }; + Base.prototype.compileClosure = function(o) { - if (this.jumps() || this instanceof Throw) { + if (this.jumps()) { throw SyntaxError('cannot use a pure statement in an expression.'); } o.sharedScope = true; return Closure.wrap(this).compileNode(o); }; + Base.prototype.cache = function(o, level, reused) { var ref, sub; if (!this.isComplex()) { @@ -4700,6 +4666,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } } }; + Base.prototype.compileLoopReference = function(o, name) { var src, tmp; src = tmp = this.compile(o, LEVEL_LIST); @@ -4708,9 +4675,17 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return [src, tmp]; }; - Base.prototype.makeReturn = function() { - return new Return(this); + + Base.prototype.makeReturn = function(res) { + var me; + me = this.unwrapAll(); + if (res) { + return new Call(new Literal("" + res + ".push"), [me]); + } else { + return new Return(me); + } }; + Base.prototype.contains = function(pred) { var contains; contains = false; @@ -4722,69 +4697,62 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff }); return contains; }; + Base.prototype.containsType = function(type) { return this instanceof type || this.contains(function(node) { return node instanceof type; }); }; + Base.prototype.lastNonComment = function(list) { var i; i = list.length; while (i--) { - if (!(list[i] instanceof Comment)) { - return list[i]; - } + if (!(list[i] instanceof Comment)) return list[i]; } return null; }; + Base.prototype.toString = function(idt, name) { var tree; - if (idt == null) { - idt = ''; - } - if (name == null) { - name = this.constructor.name; - } + if (idt == null) idt = ''; + if (name == null) name = this.constructor.name; tree = '\n' + idt + name; - if (this.soak) { - tree += '?'; - } + if (this.soak) tree += '?'; this.eachChild(function(node) { return tree += node.toString(idt + TAB); }); return tree; }; + Base.prototype.eachChild = function(func) { - var attr, child, _i, _j, _len, _len2, _ref2, _ref3; - if (!this.children) { - return this; - } + var attr, child, _i, _j, _len, _len1, _ref2, _ref3; + if (!this.children) return this; _ref2 = this.children; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { attr = _ref2[_i]; if (this[attr]) { _ref3 = flatten([this[attr]]); - for (_j = 0, _len2 = _ref3.length; _j < _len2; _j++) { + for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { child = _ref3[_j]; - if (func(child) === false) { - return this; - } + if (func(child) === false) return this; } } } return this; }; + Base.prototype.traverseChildren = function(crossScope, func) { return this.eachChild(function(child) { - if (func(child) === false) { - return false; - } + if (func(child) === false) return false; return child.traverseChildren(crossScope, func); }); }; + Base.prototype.invert = function() { return new Op('!', this); }; + Base.prototype.unwrapAll = function() { var node; node = this; @@ -4793,34 +4761,55 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return node; }; + Base.prototype.children = []; + Base.prototype.isStatement = NO; + Base.prototype.jumps = NO; + Base.prototype.isComplex = YES; + Base.prototype.isChainable = NO; + Base.prototype.isAssignable = NO; + Base.prototype.unwrap = THIS; + Base.prototype.unfoldSoak = NO; + Base.prototype.assigns = NO; + return Base; + })(); - exports.Block = Block = (function() { - __extends(Block, Base); + + exports.Block = Block = (function(_super) { + + __extends(Block, _super); + + Block.name = 'Block'; + function Block(nodes) { this.expressions = compact(flatten(nodes || [])); } + Block.prototype.children = ['expressions']; + Block.prototype.push = function(node) { this.expressions.push(node); return this; }; + Block.prototype.pop = function() { return this.expressions.pop(); }; + Block.prototype.unshift = function(node) { this.expressions.unshift(node); return this; }; + Block.prototype.unwrap = function() { if (this.expressions.length === 1) { return this.expressions[0]; @@ -4828,37 +4817,37 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return this; } }; + Block.prototype.isEmpty = function() { return !this.expressions.length; }; + Block.prototype.isStatement = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; - if (exp.isStatement(o)) { - return true; - } + if (exp.isStatement(o)) return true; } return false; }; + Block.prototype.jumps = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; - if (exp.jumps(o)) { - return exp; - } + if (exp.jumps(o)) return exp; } }; - Block.prototype.makeReturn = function() { + + Block.prototype.makeReturn = function(res) { var expr, len; len = this.expressions.length; while (len--) { expr = this.expressions[len]; if (!(expr instanceof Comment)) { - this.expressions[len] = expr.makeReturn(); + this.expressions[len] = expr.makeReturn(res); if (expr instanceof Return && !expr.expression) { this.expressions.splice(len, 1); } @@ -4867,16 +4856,16 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return this; }; + Block.prototype.compile = function(o, level) { - if (o == null) { - o = {}; - } + if (o == null) o = {}; if (o.scope) { return Block.__super__.compile.call(this, o, level); } else { return this.compileRoot(o); } }; + Block.prototype.compileNode = function(o) { var code, codes, node, top, _i, _len, _ref2; this.tab = o.indent; @@ -4887,16 +4876,26 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff node = _ref2[_i]; node = node.unwrapAll(); node = node.unfoldSoak(o) || node; - if (top) { + if (node instanceof Block) { + codes.push(node.compileNode(o)); + } else if (top) { node.front = true; code = node.compile(o); - codes.push(node.isStatement(o) ? code : this.tab + code + ';'); + if (!node.isStatement(o)) { + code = "" + this.tab + code + ";"; + if (node instanceof Literal) code = "" + code + "\n"; + } + codes.push(code); } else { codes.push(node.compile(o, LEVEL_LIST)); } } if (top) { - return codes.join('\n'); + if (this.spaced) { + return "\n" + (codes.join('\n\n')) + "\n"; + } else { + return codes.join('\n'); + } } code = codes.join(', ') || 'void 0'; if (codes.length > 1 && o.level >= LEVEL_LIST) { @@ -4905,35 +4904,56 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return code; } }; + Block.prototype.compileRoot = function(o) { - var code; - o.indent = this.tab = o.bare ? '' : TAB; + var code, exp, i, prelude, preludeExps, rest; + o.indent = o.bare ? '' : TAB; o.scope = new Scope(null, this, null); o.level = LEVEL_TOP; - code = this.compileWithDeclarations(o); - if (o.bare) { - return code; - } else { - return "(function() {\n" + code + "\n}).call(this);\n"; + this.spaced = true; + prelude = ""; + if (!o.bare) { + preludeExps = (function() { + var _i, _len, _ref2, _results; + _ref2 = this.expressions; + _results = []; + for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { + exp = _ref2[i]; + if (!(exp.unwrap() instanceof Comment)) break; + _results.push(exp); + } + return _results; + }).call(this); + rest = this.expressions.slice(preludeExps.length); + this.expressions = preludeExps; + if (preludeExps.length) { + prelude = "" + (this.compileNode(merge(o, { + indent: '' + }))) + "\n"; + } + this.expressions = rest; } + code = this.compileWithDeclarations(o); + if (o.bare) return code; + return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n"; }; + Block.prototype.compileWithDeclarations = function(o) { - var assigns, code, declars, exp, i, post, rest, scope, _len, _ref2; + var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4; code = post = ''; _ref2 = this.expressions; - for (i = 0, _len = _ref2.length; i < _len; i++) { + for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { exp = _ref2[i]; exp = exp.unwrap(); - if (!(exp instanceof Comment || exp instanceof Literal)) { - break; - } + if (!(exp instanceof Comment || exp instanceof Literal)) break; } o = merge(o, { level: LEVEL_TOP }); if (i) { - rest = this.expressions.splice(i, this.expressions.length); - code = this.compileNode(o); + rest = this.expressions.splice(i, 9e9); + _ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1]; + _ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1]; this.expressions = rest; } post = this.compileNode(o); @@ -4941,84 +4961,105 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff if (scope.expressions === this) { declars = o.scope.hasDeclarations(); assigns = scope.hasAssignments; - if ((declars || assigns) && i) { - code += '\n'; - } - if (declars) { - code += "" + this.tab + "var " + (scope.declaredVariables().join(', ')) + ";\n"; - } - if (assigns) { - code += "" + this.tab + "var " + (multident(scope.assignedVariables().join(', '), this.tab)) + ";\n"; + if (declars || assigns) { + if (i) code += '\n'; + code += "" + this.tab + "var "; + if (declars) code += scope.declaredVariables().join(', '); + if (assigns) { + if (declars) code += ",\n" + (this.tab + TAB); + code += scope.assignedVariables().join(",\n" + (this.tab + TAB)); + } + code += ';\n'; } } return code + post; }; + Block.wrap = function(nodes) { - if (nodes.length === 1 && nodes[0] instanceof Block) { - return nodes[0]; - } + if (nodes.length === 1 && nodes[0] instanceof Block) return nodes[0]; return new Block(nodes); }; + return Block; - })(); - exports.Literal = Literal = (function() { - __extends(Literal, Base); + + })(Base); + + exports.Literal = Literal = (function(_super) { + + __extends(Literal, _super); + + Literal.name = 'Literal'; + function Literal(value) { this.value = value; } + Literal.prototype.makeReturn = function() { if (this.isStatement()) { return this; } else { - return new Return(this); + return Literal.__super__.makeReturn.apply(this, arguments); } }; + Literal.prototype.isAssignable = function() { return IDENTIFIER.test(this.value); }; + Literal.prototype.isStatement = function() { var _ref2; return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger'; }; + Literal.prototype.isComplex = NO; + Literal.prototype.assigns = function(name) { return name === this.value; }; + Literal.prototype.jumps = function(o) { - if (!this.isStatement()) { - return false; - } - if (!(o && (o.loop || o.block && (this.value !== 'continue')))) { + if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) { return this; - } else { - return false; } + if (this.value === 'continue' && !(o != null ? o.loop : void 0)) return this; }; + Literal.prototype.compileNode = function(o) { - var code; - code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value.reserved ? "\"" + this.value + "\"" : this.value; + var code, _ref2; + code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value; if (this.isStatement()) { return "" + this.tab + code + ";"; } else { return code; } }; + Literal.prototype.toString = function() { return ' "' + this.value + '"'; }; + return Literal; - })(); - exports.Return = Return = (function() { - __extends(Return, Base); - function Return(expr) { - if (expr && !expr.unwrap().isUndefined) { - this.expression = expr; - } + + })(Base); + + exports.Return = Return = (function(_super) { + + __extends(Return, _super); + + Return.name = 'Return'; + + function Return(expr) { + if (expr && !expr.unwrap().isUndefined) this.expression = expr; } + Return.prototype.children = ['expression']; + Return.prototype.isStatement = YES; + Return.prototype.makeReturn = THIS; + Return.prototype.jumps = THIS; + Return.prototype.compile = function(o, level) { var expr, _ref2; expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0; @@ -5028,80 +5069,91 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return Return.__super__.compile.call(this, o, level); } }; + Return.prototype.compileNode = function(o) { - return this.tab + ("return" + (this.expression ? ' ' + this.expression.compile(o, LEVEL_PAREN) : '') + ";"); + return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";"); }; + return Return; - })(); - exports.Value = Value = (function() { - __extends(Value, Base); + + })(Base); + + exports.Value = Value = (function(_super) { + + __extends(Value, _super); + + Value.name = 'Value'; + function Value(base, props, tag) { - if (!props && base instanceof Value) { - return base; - } + if (!props && base instanceof Value) return base; this.base = base; this.properties = props || []; - if (tag) { - this[tag] = true; - } + if (tag) this[tag] = true; return this; } + Value.prototype.children = ['base', 'properties']; - Value.prototype.push = function(prop) { - this.properties.push(prop); + + Value.prototype.add = function(props) { + this.properties = this.properties.concat(props); return this; }; + Value.prototype.hasProperties = function() { return !!this.properties.length; }; + Value.prototype.isArray = function() { return !this.properties.length && this.base instanceof Arr; }; + Value.prototype.isComplex = function() { return this.hasProperties() || this.base.isComplex(); }; + Value.prototype.isAssignable = function() { return this.hasProperties() || this.base.isAssignable(); }; + Value.prototype.isSimpleNumber = function() { return this.base instanceof Literal && SIMPLENUM.test(this.base.value); }; + + Value.prototype.isString = function() { + return this.base instanceof Literal && IS_STRING.test(this.base.value); + }; + Value.prototype.isAtomic = function() { var node, _i, _len, _ref2; _ref2 = this.properties.concat(this.base); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { node = _ref2[_i]; - if (node.soak || node instanceof Call) { - return false; - } + if (node.soak || node instanceof Call) return false; } return true; }; + Value.prototype.isStatement = function(o) { return !this.properties.length && this.base.isStatement(o); }; + Value.prototype.assigns = function(name) { return !this.properties.length && this.base.assigns(name); }; + Value.prototype.jumps = function(o) { return !this.properties.length && this.base.jumps(o); }; + Value.prototype.isObject = function(onlyGenerated) { - if (this.properties.length) { - return false; - } + if (this.properties.length) return false; return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated); }; + Value.prototype.isSplice = function() { return last(this.properties) instanceof Slice; }; - Value.prototype.makeReturn = function() { - if (this.properties.length) { - return Value.__super__.makeReturn.call(this); - } else { - return this.base.makeReturn(); - } - }; + Value.prototype.unwrap = function() { if (this.properties.length) { return this; @@ -5109,6 +5161,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return this.base; } }; + Value.prototype.cacheReference = function(o) { var base, bref, name, nref; name = last(this.properties); @@ -5120,23 +5173,22 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff bref = new Literal(o.scope.freeVariable('base')); base = new Value(new Parens(new Assign(bref, base))); } - if (!name) { - return [base, bref]; - } + if (!name) return [base, bref]; if (name.isComplex()) { nref = new Literal(o.scope.freeVariable('name')); name = new Index(new Assign(nref, name.index)); nref = new Index(nref); } - return [base.push(name), new Value(bref || base.base, [nref || name])]; + return [base.add(name), new Value(bref || base.base, [nref || name])]; }; + Value.prototype.compileNode = function(o) { var code, prop, props, _i, _len; this.base.front = this.front; props = this.properties; code = this.base.compile(o, props.length ? LEVEL_ACCESS : null); - if (props[0] instanceof Access && this.isSimpleNumber()) { - code = "(" + code + ")"; + if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) { + code = "" + code + "."; } for (_i = 0, _len = props.length; _i < _len; _i++) { prop = props[_i]; @@ -5144,59 +5196,73 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return code; }; + Value.prototype.unfoldSoak = function(o) { - var result; - if (this.unfoldedSoak != null) { - return this.unfoldedSoak; - } - result = __bind(function() { - var fst, i, ifn, prop, ref, snd, _len, _ref2; - if (ifn = this.base.unfoldSoak(o)) { - Array.prototype.push.apply(ifn.body.properties, this.properties); + var result, + _this = this; + if (this.unfoldedSoak != null) return this.unfoldedSoak; + result = (function() { + var fst, i, ifn, prop, ref, snd, _i, _len, _ref2; + if (ifn = _this.base.unfoldSoak(o)) { + Array.prototype.push.apply(ifn.body.properties, _this.properties); return ifn; } - _ref2 = this.properties; - for (i = 0, _len = _ref2.length; i < _len; i++) { + _ref2 = _this.properties; + for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { prop = _ref2[i]; - if (prop.soak) { - prop.soak = false; - fst = new Value(this.base, this.properties.slice(0, i)); - snd = new Value(this.base, this.properties.slice(i)); - if (fst.isComplex()) { - ref = new Literal(o.scope.freeVariable('ref')); - fst = new Parens(new Assign(ref, fst)); - snd.base = ref; - } - return new If(new Existence(fst), snd, { - soak: true - }); + if (!prop.soak) continue; + prop.soak = false; + fst = new Value(_this.base, _this.properties.slice(0, i)); + snd = new Value(_this.base, _this.properties.slice(i)); + if (fst.isComplex()) { + ref = new Literal(o.scope.freeVariable('ref')); + fst = new Parens(new Assign(ref, fst)); + snd.base = ref; } + return new If(new Existence(fst), snd, { + soak: true + }); } return null; - }, this)(); + })(); return this.unfoldedSoak = result || false; }; + return Value; - })(); - exports.Comment = Comment = (function() { - __extends(Comment, Base); + + })(Base); + + exports.Comment = Comment = (function(_super) { + + __extends(Comment, _super); + + Comment.name = 'Comment'; + function Comment(comment) { this.comment = comment; } + Comment.prototype.isStatement = YES; + Comment.prototype.makeReturn = THIS; + Comment.prototype.compileNode = function(o, level) { var code; - code = '/*' + multident(this.comment, this.tab) + '*/'; - if ((level || o.level) === LEVEL_TOP) { - code = o.indent + code; - } + code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n"); + if ((level || o.level) === LEVEL_TOP) code = o.indent + code; return code; }; + return Comment; - })(); - exports.Call = Call = (function() { - __extends(Call, Base); + + })(Base); + + exports.Call = Call = (function(_super) { + + __extends(Call, _super); + + Call.name = 'Call'; + function Call(variable, args, soak) { this.args = args != null ? args : []; this.soak = soak; @@ -5204,40 +5270,45 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff this.isSuper = variable === 'super'; this.variable = this.isSuper ? null : variable; } + Call.prototype.children = ['variable', 'args']; + Call.prototype.newInstance = function() { - var base; - base = this.variable.base || this.variable; - if (base instanceof Call) { + var base, _ref2; + base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable; + if (base instanceof Call && !base.isNew) { base.newInstance(); } else { this.isNew = true; } return this; }; + Call.prototype.superReference = function(o) { - var method, name; + var accesses, method, name; method = o.scope.method; - if (!method) { - throw SyntaxError('cannot call super outside of a function.'); - } + if (!method) throw SyntaxError('cannot call super outside of a function.'); name = method.name; - if (!name) { + if (name == null) { throw SyntaxError('cannot call super on an anonymous function.'); } if (method.klass) { - return "" + method.klass + ".__super__." + name; + accesses = [new Access(new Literal('__super__'))]; + if (method["static"]) { + accesses.push(new Access(new Literal('constructor'))); + } + accesses.push(new Access(new Literal(name))); + return (new Value(new Literal(method.klass), accesses)).compile(o); } else { return "" + name + ".__super__.constructor"; } }; + Call.prototype.unfoldSoak = function(o) { var call, ifn, left, list, rite, _i, _len, _ref2, _ref3; if (this.soak) { if (this.variable) { - if (ifn = unfoldSoak(o, this, 'variable')) { - return ifn; - } + if (ifn = unfoldSoak(o, this, 'variable')) return ifn; _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1]; } else { left = new Literal(this.superReference(o)); @@ -5258,13 +5329,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff call = call.variable; continue; } - if (!(call.variable instanceof Value)) { - break; - } + if (!(call.variable instanceof Value)) break; list.push(call); - if (!((call = call.variable.base) instanceof Call)) { - break; - } + if (!((call = call.variable.base) instanceof Call)) break; } _ref3 = list.reverse(); for (_i = 0, _len = _ref3.length; _i < _len; _i++) { @@ -5280,8 +5347,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return ifn; }; + Call.prototype.filterImplicitObjects = function(list) { - var node, nodes, obj, prop, properties, _i, _j, _len, _len2, _ref2; + var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2; nodes = []; for (_i = 0, _len = list.length; _i < _len; _i++) { node = list[_i]; @@ -5291,12 +5359,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } obj = null; _ref2 = node.base.properties; - for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { prop = _ref2[_j]; - if (prop instanceof Assign) { - if (!obj) { - nodes.push(obj = new Obj(properties = [], true)); - } + if (prop instanceof Assign || prop instanceof Comment) { + if (!obj) nodes.push(obj = new Obj(properties = [], true)); properties.push(prop); } else { nodes.push(prop); @@ -5306,11 +5372,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return nodes; }; + Call.prototype.compileNode = function(o) { var arg, args, code, _ref2; - if ((_ref2 = this.variable) != null) { - _ref2.front = this.front; - } + if ((_ref2 = this.variable) != null) _ref2.front = this.front; if (code = Splat.compileSplattedArray(o, this.args, true)) { return this.compileSplat(o, code); } @@ -5330,9 +5395,11 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")"); } }; + Call.prototype.compileSuper = function(args, o) { return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; }; + Call.prototype.compileSplat = function(o, splatArgs) { var base, fun, idt, name, ref; if (this.isSuper) { @@ -5340,7 +5407,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } if (this.isNew) { idt = this.tab + TAB; - return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return typeof result === \"object\" ? result : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function() {})"; + return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})"; } base = new Value(this.variable); if ((name = base.properties.pop()) && base.isComplex()) { @@ -5348,9 +5415,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o)); } else { fun = base.compile(o, LEVEL_ACCESS); - if (SIMPLENUM.test(fun)) { - fun = "(" + fun + ")"; - } + if (SIMPLENUM.test(fun)) fun = "(" + fun + ")"; if (name) { ref = fun; fun += name.compile(o); @@ -5360,109 +5425,143 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return "" + fun + ".apply(" + ref + ", " + splatArgs + ")"; }; + return Call; - })(); - exports.Extends = Extends = (function() { - __extends(Extends, Base); + + })(Base); + + exports.Extends = Extends = (function(_super) { + + __extends(Extends, _super); + + Extends.name = 'Extends'; + function Extends(child, parent) { this.child = child; this.parent = parent; } + Extends.prototype.children = ['child', 'parent']; + Extends.prototype.compile = function(o) { - utility('hasProp'); return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o); }; + return Extends; - })(); - exports.Access = Access = (function() { - __extends(Access, Base); + + })(Base); + + exports.Access = Access = (function(_super) { + + __extends(Access, _super); + + Access.name = 'Access'; + function Access(name, tag) { this.name = name; this.name.asKey = true; - this.proto = tag === 'proto' ? '.prototype' : ''; this.soak = tag === 'soak'; } + Access.prototype.children = ['name']; + Access.prototype.compile = function(o) { var name; name = this.name.compile(o); - return this.proto + (IS_STRING.test(name) ? "[" + name + "]" : "." + name); + if (IDENTIFIER.test(name)) { + return "." + name; + } else { + return "[" + name + "]"; + } }; + Access.prototype.isComplex = NO; + return Access; - })(); - exports.Index = Index = (function() { - __extends(Index, Base); + + })(Base); + + exports.Index = Index = (function(_super) { + + __extends(Index, _super); + + Index.name = 'Index'; + function Index(index) { this.index = index; } + Index.prototype.children = ['index']; + Index.prototype.compile = function(o) { - return (this.proto ? '.prototype' : '') + ("[" + (this.index.compile(o, LEVEL_PAREN)) + "]"); + return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]"; }; + Index.prototype.isComplex = function() { return this.index.isComplex(); }; + return Index; - })(); - exports.Range = Range = (function() { - __extends(Range, Base); + + })(Base); + + exports.Range = Range = (function(_super) { + + __extends(Range, _super); + + Range.name = 'Range'; + Range.prototype.children = ['from', 'to']; + function Range(from, to, tag) { this.from = from; this.to = to; this.exclusive = tag === 'exclusive'; this.equals = this.exclusive ? '' : '='; } + Range.prototype.compileVariables = function(o) { var step, _ref2, _ref3, _ref4, _ref5; o = merge(o, { top: true }); - _ref2 = this.from.cache(o, LEVEL_LIST), this.from = _ref2[0], this.fromVar = _ref2[1]; - _ref3 = this.to.cache(o, LEVEL_LIST), this.to = _ref3[0], this.toVar = _ref3[1]; + _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1]; + _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1]; if (step = del(o, 'step')) { _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1]; } _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1]; - if (this.stepVar) { - return this.stepNum = this.stepVar.match(SIMPLENUM); - } + if (this.stepVar) return this.stepNum = this.stepVar.match(SIMPLENUM); }; + Range.prototype.compileNode = function(o) { - var cond, condPart, from, gt, idx, known, lt, stepPart, to, varPart, _ref2, _ref3; - if (!this.fromVar) { - this.compileVariables(o); - } - if (!o.index) { - return this.compileArray(o); - } + var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3; + if (!this.fromVar) this.compileVariables(o); + if (!o.index) return this.compileArray(o); known = this.fromNum && this.toNum; idx = del(o, 'index'); - varPart = "" + idx + " = " + this.from; - if (this.to !== this.toVar) { - varPart += ", " + this.to; - } - if (this.step !== this.stepVar) { - varPart += ", " + this.step; - } + idxName = del(o, 'name'); + namedIndex = idxName && idxName !== idx; + varPart = "" + idx + " = " + this.fromC; + if (this.toC !== this.toVar) varPart += ", " + this.toC; + if (this.step !== this.stepVar) varPart += ", " + this.step; _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1]; - condPart = this.stepNum ? condPart = +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), condPart = from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, condPart = "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); - stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? from <= to ? "" + idx + "++" : "" + idx + "--" : "" + cond + " ? " + idx + "++ : " + idx + "--"; + condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); + stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--"; + if (namedIndex) varPart = "" + idxName + " = " + varPart; + if (namedIndex) stepPart = "" + idxName + " = " + stepPart; return "" + varPart + "; " + condPart + "; " + stepPart; }; + Range.prototype.compileArray = function(o) { - var body, cond, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; + var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) { range = (function() { _results = []; for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); } return _results; - }).apply(this, arguments); - if (this.exclusive) { - range.pop(); - } + }).apply(this); + if (this.exclusive) range.pop(); return "[" + (range.join(', ')) + "]"; } idt = this.tab + TAB; @@ -5473,54 +5572,85 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff o.index = i; body = this.compileNode(o); } else { - vars = ("" + i + " = " + this.from) + (this.to !== this.toVar ? ", " + this.to : ''); + vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : ''); cond = "" + this.fromVar + " <= " + this.toVar; body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--"; } post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent; - return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this, arguments)"; + hasArgs = function(node) { + return node != null ? node.contains(function(n) { + return n instanceof Literal && n.value === 'arguments' && !n.asKey; + }) : void 0; + }; + if (hasArgs(this.from) || hasArgs(this.to)) args = ', arguments'; + return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")"; }; + return Range; - })(); - exports.Slice = Slice = (function() { - __extends(Slice, Base); + + })(Base); + + exports.Slice = Slice = (function(_super) { + + __extends(Slice, _super); + + Slice.name = 'Slice'; + Slice.prototype.children = ['range']; + function Slice(range) { this.range = range; Slice.__super__.constructor.call(this); } + Slice.prototype.compileNode = function(o) { var compiled, from, fromStr, to, toStr, _ref2; _ref2 = this.range, to = _ref2.to, from = _ref2.from; fromStr = from && from.compile(o, LEVEL_PAREN) || '0'; compiled = to && to.compile(o, LEVEL_PAREN); if (to && !(!this.range.exclusive && +compiled === -1)) { - toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? (+compiled + 1).toString() : "(" + compiled + " + 1) || 9e9"); + toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "" + compiled + " + 1 || 9e9")); } return ".slice(" + fromStr + (toStr || '') + ")"; }; + return Slice; - })(); - exports.Obj = Obj = (function() { - __extends(Obj, Base); + + })(Base); + + exports.Obj = Obj = (function(_super) { + + __extends(Obj, _super); + + Obj.name = 'Obj'; + function Obj(props, generated) { this.generated = generated != null ? generated : false; this.objects = this.properties = props || []; } + Obj.prototype.children = ['properties']; + Obj.prototype.compileNode = function(o) { - var i, idt, indent, join, lastNoncom, node, obj, prop, props, _i, _len; + var i, idt, indent, join, lastNoncom, node, obj, prop, propName, propNames, props, _i, _j, _len, _len1, _ref2; props = this.properties; - if (!props.length) { - if (this.front) { - return '({})'; - } else { - return '{}'; + propNames = []; + _ref2 = this.properties; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + prop = _ref2[_i]; + if (prop.isComplex()) prop = prop.variable; + if (prop != null) { + propName = prop.unwrapAll().value.toString(); + if (__indexOf.call(propNames, propName) >= 0) { + throw SyntaxError("multiple object literal properties named \"" + propName + "\""); + } + propNames.push(propName); } } + if (!props.length) return (this.front ? '({})' : '{}'); if (this.generated) { - for (_i = 0, _len = props.length; _i < _len; _i++) { - node = props[_i]; + for (_j = 0, _len1 = props.length; _j < _len1; _j++) { + node = props[_j]; if (node instanceof Value) { throw new Error('cannot have an implicit value in an implicit object'); } @@ -5529,9 +5659,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff idt = o.indent += TAB; lastNoncom = this.lastNonComment(this.properties); props = (function() { - var _len2, _results; + var _k, _len2, _results; _results = []; - for (i = 0, _len2 = props.length; i < _len2; i++) { + for (i = _k = 0, _len2 = props.length; _k < _len2; i = ++_k) { prop = props[i]; join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n'; indent = prop instanceof Comment ? '' : idt; @@ -5539,9 +5669,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff prop = new Assign(prop.properties[0].name, prop, 'object'); } if (!(prop instanceof Comment)) { - if (!(prop instanceof Assign)) { - prop = new Assign(prop, prop, 'object'); - } + if (!(prop instanceof Assign)) prop = new Assign(prop, prop, 'object'); (prop.variable.base || prop.variable).asKey = true; } _results.push(indent + prop.compile(o, LEVEL_TOP) + join); @@ -5556,36 +5684,41 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return obj; } }; + Obj.prototype.assigns = function(name) { var prop, _i, _len, _ref2; _ref2 = this.properties; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { prop = _ref2[_i]; - if (prop.assigns(name)) { - return true; - } + if (prop.assigns(name)) return true; } return false; }; + return Obj; - })(); - exports.Arr = Arr = (function() { - __extends(Arr, Base); + + })(Base); + + exports.Arr = Arr = (function(_super) { + + __extends(Arr, _super); + + Arr.name = 'Arr'; + function Arr(objs) { this.objects = objs || []; } + Arr.prototype.children = ['objects']; + Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects; + Arr.prototype.compileNode = function(o) { var code, obj, objs; - if (!this.objects.length) { - return '[]'; - } + if (!this.objects.length) return '[]'; o.indent += TAB; objs = this.filterImplicitObjects(this.objects); - if (code = Splat.compileSplattedArray(o, objs)) { - return code; - } + if (code = Splat.compileSplattedArray(o, objs)) return code; code = ((function() { var _i, _len, _results; _results = []; @@ -5601,21 +5734,27 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "[" + code + "]"; } }; + Arr.prototype.assigns = function(name) { var obj, _i, _len, _ref2; _ref2 = this.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; - if (obj.assigns(name)) { - return true; - } + if (obj.assigns(name)) return true; } return false; }; + return Arr; - })(); - exports.Class = Class = (function() { - __extends(Class, Base); + + })(Base); + + exports.Class = Class = (function(_super) { + + __extends(Class, _super); + + Class.name = 'Class'; + function Class(variable, parent, body) { this.variable = variable; this.parent = parent; @@ -5623,43 +5762,45 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff this.boundFuncs = []; this.body.classBody = true; } + Class.prototype.children = ['variable', 'parent', 'body']; + Class.prototype.determineName = function() { var decl, tail; - if (!this.variable) { - return null; - } + if (!this.variable) return null; decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value; + if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) { + throw SyntaxError("variable name may not be " + decl); + } return decl && (decl = IDENTIFIER.test(decl) && decl); }; + Class.prototype.setContext = function(name) { return this.body.traverseChildren(false, function(node) { - if (node.classBody) { - return false; - } + if (node.classBody) return false; if (node instanceof Literal && node.value === 'this') { return node.value = name; } else if (node instanceof Code) { node.klass = name; - if (node.bound) { - return node.context = name; - } + if (node.bound) return node.context = name; } }); }; + Class.prototype.addBoundFunctions = function(o) { - var bname, bvar, _i, _len, _ref2, _results; + var bvar, lhs, _i, _len, _ref2, _results; if (this.boundFuncs.length) { _ref2 = this.boundFuncs; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { bvar = _ref2[_i]; - bname = bvar.compile(o); - _results.push(this.ctor.body.unshift(new Literal("this." + bname + " = " + (utility('bind')) + "(this." + bname + ", this)"))); + lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); + _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)"))); } return _results; } }; + Class.prototype.addProperties = function(node, name, o) { var assign, base, exprs, func, props; props = node.base.properties.slice(0); @@ -5685,12 +5826,15 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff assign = new Assign(new Literal(this.externalCtor), func); } } else { - if (!assign.variable["this"]) { - assign.variable = new Value(new Literal(name), [new Access(base, 'proto')]); - } - if (func instanceof Code && func.bound) { - this.boundFuncs.push(base); - func.bound = false; + if (assign.variable["this"]) { + func["static"] = true; + if (func.bound) func.context = name; + } else { + assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]); + if (func instanceof Code && func.bound) { + this.boundFuncs.push(base); + func.bound = false; + } } } } @@ -5700,24 +5844,35 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff }).call(this); return compact(exprs); }; + Class.prototype.walkBody = function(name, o) { - return this.traverseChildren(false, __bind(function(child) { - var exps, i, node, _len, _ref2; - if (child instanceof Class) { - return false; - } + var _this = this; + return this.traverseChildren(false, function(child) { + var exps, i, node, _i, _len, _ref2; + if (child instanceof Class) return false; if (child instanceof Block) { _ref2 = exps = child.expressions; - for (i = 0, _len = _ref2.length; i < _len; i++) { + for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { node = _ref2[i]; if (node instanceof Value && node.isObject(true)) { - exps[i] = this.addProperties(node, name, o); + exps[i] = _this.addProperties(node, name, o); } } return child.expressions = exps = flatten(exps); } - }, this)); + }); }; + + Class.prototype.hoistDirectivePrologue = function() { + var expressions, index, node; + index = 0; + expressions = this.body.expressions; + while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) { + ++index; + } + return this.directives = expressions.splice(0, index); + }; + Class.prototype.ensureConstructor = function(name) { if (!this.ctor) { this.ctor = new Code; @@ -5727,85 +5882,112 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff if (this.externalCtor) { this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)")); } + this.ctor.body.makeReturn(); this.body.expressions.unshift(this.ctor); } this.ctor.ctor = this.ctor.name = name; this.ctor.klass = null; return this.ctor.noReturn = true; }; + Class.prototype.compileNode = function(o) { - var decl, klass, lname, name; + var call, decl, klass, lname, name, params, _ref2; decl = this.determineName(); - name = decl || this.name || '_Class'; + name = decl || '_Class'; + if (name.reserved) name = "_" + name; lname = new Literal(name); + this.hoistDirectivePrologue(); this.setContext(name); this.walkBody(name, o); this.ensureConstructor(name); - if (this.parent) { - this.body.expressions.unshift(new Extends(lname, this.parent)); - } - if (!(this.ctor instanceof Code)) { - this.body.expressions.unshift(this.ctor); + this.body.spaced = true; + if (!(this.ctor instanceof Code)) this.body.expressions.unshift(this.ctor); + if (decl) { + this.body.expressions.unshift(new Assign(new Value(new Literal(name), [new Access(new Literal('name'))]), new Literal("'" + name + "'"))); } this.body.expressions.push(lname); + (_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives); this.addBoundFunctions(o); - klass = new Parens(Closure.wrap(this.body), true); - if (this.variable) { - klass = new Assign(this.variable, klass); - } + call = Closure.wrap(this.body); + if (this.parent) { + this.superClass = new Literal(o.scope.freeVariable('super', false)); + this.body.expressions.unshift(new Extends(lname, this.superClass)); + call.args.push(this.parent); + params = call.variable.params || call.variable.base.params; + params.push(new Param(this.superClass)); + } + klass = new Parens(call, true); + if (this.variable) klass = new Assign(this.variable, klass); return klass.compile(o); }; + return Class; - })(); - exports.Assign = Assign = (function() { - __extends(Assign, Base); + + })(Base); + + exports.Assign = Assign = (function(_super) { + + __extends(Assign, _super); + + Assign.name = 'Assign'; + function Assign(variable, value, context, options) { + var forbidden, name, _ref2; this.variable = variable; this.value = value; this.context = context; this.param = options && options.param; + this.subpattern = options && options.subpattern; + forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0); + if (forbidden && this.context !== 'object') { + throw SyntaxError("variable name may not be \"" + name + "\""); + } } + Assign.prototype.children = ['variable', 'value']; + + Assign.prototype.isStatement = function(o) { + return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0; + }; + Assign.prototype.assigns = function(name) { return this[this.context === 'object' ? 'value' : 'variable'].assigns(name); }; + Assign.prototype.unfoldSoak = function(o) { return unfoldSoak(o, this, 'variable'); }; + Assign.prototype.compileNode = function(o) { - var isValue, match, name, val, _ref2; + var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5; if (isValue = this.variable instanceof Value) { if (this.variable.isArray() || this.variable.isObject()) { return this.compilePatternMatch(o); } - if (this.variable.isSplice()) { - return this.compileSplice(o); - } + if (this.variable.isSplice()) return this.compileSplice(o); if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') { return this.compileConditional(o); } } name = this.variable.compile(o, LEVEL_LIST); - if (!(this.context || this.variable.isAssignable())) { - throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); - } - if (!(this.context || isValue && (this.variable.namespaced || this.variable.hasProperties()))) { - if (this.param) { - o.scope.add(name, 'var'); - } else { - o.scope.find(name); + if (!this.context) { + if (!(varBase = this.variable.unwrapAll()).isAssignable()) { + throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); + } + if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) { + if (this.param) { + o.scope.add(name, 'var'); + } else { + o.scope.find(name); + } } } if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) { - this.value.name = match[2]; - if (match[1]) { - this.value.klass = match[1]; - } + if (match[1]) this.value.klass = match[1]; + this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5]; } val = this.value.compile(o, LEVEL_LIST); - if (this.context === 'object') { - return "" + name + ": " + val; - } + if (this.context === 'object') return "" + name + ": " + val; val = name + (" " + (this.context || '=') + " ") + val; if (o.level <= LEVEL_LIST) { return val; @@ -5813,8 +5995,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + val + ")"; } }; + Assign.prototype.compilePatternMatch = function(o) { - var acc, assigns, code, i, idx, isObject, ivar, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _len, _ref2, _ref3, _ref4, _ref5; + var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; top = o.level === LEVEL_TOP; value = this.value; objects = this.variable.base.objects; @@ -5829,10 +6012,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff isObject = this.variable.isObject(); if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) { if (obj instanceof Assign) { - _ref2 = obj, idx = _ref2.variable.base, obj = _ref2.value; + _ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value; } else { if (obj.base instanceof Parens) { - _ref3 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref3[0], idx = _ref3[1]; + _ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1]; } else { idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0); } @@ -5840,6 +6023,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff acc = IDENTIFIER.test(idx.unwrap().value || 0); value = new Value(value); value.properties.push(new (acc ? Access : Index)(idx)); + if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) { + throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o))); + } return new Assign(obj, value, null, { param: this.param }).compile(o, LEVEL_TOP); @@ -5851,21 +6037,23 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar); vvar = ref; } - for (i = 0, _len = objects.length; i < _len; i++) { + for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) { obj = objects[i]; idx = i; if (isObject) { if (obj instanceof Assign) { - _ref4 = obj, idx = _ref4.variable.base, obj = _ref4.value; + _ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value; } else { if (obj.base instanceof Parens) { - _ref5 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref5[0], idx = _ref5[1]; + _ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1]; } else { idx = obj["this"] ? obj.properties[0].name : obj; } } } if (!splat && obj instanceof Splat) { + name = obj.name.unwrap().value; + obj = obj.unwrap(); val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i; if (rest = olen - i - 1) { ivar = o.scope.freeVariable('i'); @@ -5876,9 +6064,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff val = new Literal(val); splat = "" + ivar + "++"; } else { + name = obj.unwrap().value; if (obj instanceof Splat) { obj = obj.name.compile(o); - throw SyntaxError("multiple splats are disallowed in an assignment: " + obj + " ..."); + throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "..."); } if (typeof idx === 'number') { idx = new Literal(splat || idx); @@ -5888,13 +6077,15 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]); } + if ((name != null) && __indexOf.call(RESERVED, name) >= 0) { + throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o))); + } assigns.push(new Assign(obj, val, null, { - param: this.param - }).compile(o, LEVEL_TOP)); - } - if (!top) { - assigns.push(vvar); + param: this.param, + subpattern: true + }).compile(o, LEVEL_LIST)); } + if (!(top || this.subpattern)) assigns.push(vvar); code = assigns.join(', '); if (o.level < LEVEL_LIST) { return code; @@ -5902,14 +6093,17 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + code + ")"; } }; + Assign.prototype.compileConditional = function(o) { - var left, rite, _ref2; - _ref2 = this.variable.cacheReference(o), left = _ref2[0], rite = _ref2[1]; - if (__indexOf.call(this.context, "?") >= 0) { - o.isExistentialEquals = true; + var left, right, _ref2; + _ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1]; + if (left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) { + throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined."); } - return new Op(this.context.slice(0, -1), left, new Assign(rite, this.value, '=')).compile(o); + if (__indexOf.call(this.context, "?") >= 0) o.isExistentialEquals = true; + return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o); }; + Assign.prototype.compileSplice = function(o) { var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4; _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive; @@ -5918,14 +6112,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff if (to) { if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) { to = +to.compile(o) - +fromRef; - if (!exclusive) { - to += 1; - } + if (!exclusive) to += 1; } else { - to = to.compile(o) + ' - ' + fromRef; - if (!exclusive) { - to += ' + 1'; - } + to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef; + if (!exclusive) to += ' + 1'; } } else { to = "9e9"; @@ -5938,63 +6128,73 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return code; } }; + return Assign; - })(); - exports.Code = Code = (function() { - __extends(Code, Base); - function Code(params, body, tag) { - this.params = params || []; - this.body = body || new Block; + + })(Base); + + exports.Code = Code = (function(_super) { + + __extends(Code, _super); + + Code.name = 'Code'; + + function Code(params, body, tag) { + this.params = params || []; + this.body = body || new Block; this.bound = tag === 'boundfunc'; - if (this.bound) { - this.context = 'this'; - } + if (this.bound) this.context = '_this'; } + Code.prototype.children = ['params', 'body']; + Code.prototype.isStatement = function() { return !!this.ctor; }; + Code.prototype.jumps = NO; + Code.prototype.compileNode = function(o) { - var code, exprs, i, idt, lit, p, param, ref, splats, v, val, vars, wasEmpty, _i, _j, _k, _len, _len2, _len3, _len4, _ref2, _ref3, _ref4, _ref5; + var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; o.scope = new Scope(o.scope, this.body, this); o.scope.shared = del(o, 'sharedScope'); o.indent += TAB; delete o.bare; - vars = []; + delete o.isExistentialEquals; + params = []; exprs = []; - _ref2 = this.params; + _ref2 = this.paramNames(); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - param = _ref2[_i]; - if (param.splat) { - _ref3 = this.params; - for (_j = 0, _len2 = _ref3.length; _j < _len2; _j++) { - p = _ref3[_j]; - if (p.name.value) { - o.scope.add(p.name.value, 'var', true); - } + name = _ref2[_i]; + if (!o.scope.check(name)) o.scope.parameter(name); + } + _ref3 = this.params; + for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { + param = _ref3[_j]; + if (!param.splat) continue; + _ref4 = this.params; + for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { + p = _ref4[_k]; + if (p.name.value) o.scope.add(p.name.value, 'var', true); + } + splats = new Assign(new Value(new Arr((function() { + var _l, _len3, _ref5, _results; + _ref5 = this.params; + _results = []; + for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { + p = _ref5[_l]; + _results.push(p.asReference(o)); } - splats = new Assign(new Value(new Arr((function() { - var _k, _len3, _ref4, _results; - _ref4 = this.params; - _results = []; - for (_k = 0, _len3 = _ref4.length; _k < _len3; _k++) { - p = _ref4[_k]; - _results.push(p.asReference(o)); - } - return _results; - }).call(this))), new Value(new Literal('arguments'))); - break; - } + return _results; + }).call(this))), new Value(new Literal('arguments'))); + break; } - _ref4 = this.params; - for (_k = 0, _len3 = _ref4.length; _k < _len3; _k++) { - param = _ref4[_k]; + _ref5 = this.params; + for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { + param = _ref5[_l]; if (param.isComplex()) { val = ref = param.asReference(o); - if (param.value) { - val = new Op('?', ref, param.value); - } + if (param.value) val = new Op('?', ref, param.value); exprs.push(new Assign(new Value(param.name), val, '=', { param: true })); @@ -6006,101 +6206,167 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff exprs.push(new If(lit, val)); } } - if (!splats) { - vars.push(ref); - } + if (!splats) params.push(ref); } wasEmpty = this.body.isEmpty(); - if (splats) { - exprs.unshift(splats); - } + if (splats) exprs.unshift(splats); if (exprs.length) { - (_ref5 = this.body.expressions).unshift.apply(_ref5, exprs); + (_ref6 = this.body.expressions).unshift.apply(_ref6, exprs); } - if (!splats) { - for (i = 0, _len4 = vars.length; i < _len4; i++) { - v = vars[i]; - o.scope.parameter(vars[i] = v.compile(o)); + for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) { + p = params[i]; + o.scope.parameter(params[i] = p.compile(o)); + } + uniqs = []; + _ref7 = this.paramNames(); + for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) { + name = _ref7[_n]; + if (__indexOf.call(uniqs, name) >= 0) { + throw SyntaxError("multiple parameters named '" + name + "'"); } + uniqs.push(name); } - if (!(wasEmpty || this.noReturn)) { - this.body.makeReturn(); + if (!(wasEmpty || this.noReturn)) this.body.makeReturn(); + if (this.bound) { + if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) { + this.bound = this.context = o.scope.parent.method.context; + } else if (!this["static"]) { + o.scope.parent.assign('_this', 'this'); + } } idt = o.indent; code = 'function'; - if (this.ctor) { - code += ' ' + this.name; - } - code += '(' + vars.join(', ') + ') {'; + if (this.ctor) code += ' ' + this.name; + code += '(' + params.join(', ') + ') {'; if (!this.body.isEmpty()) { code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab; } code += '}'; - if (this.ctor) { - return this.tab + code; - } - if (this.bound) { - return utility('bind') + ("(" + code + ", " + this.context + ")"); - } + if (this.ctor) return this.tab + code; if (this.front || (o.level >= LEVEL_ACCESS)) { return "(" + code + ")"; } else { return code; } }; + + Code.prototype.paramNames = function() { + var names, param, _i, _len, _ref2; + names = []; + _ref2 = this.params; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + param = _ref2[_i]; + names.push.apply(names, param.names()); + } + return names; + }; + Code.prototype.traverseChildren = function(crossScope, func) { if (crossScope) { return Code.__super__.traverseChildren.call(this, crossScope, func); } }; + return Code; - })(); - exports.Param = Param = (function() { - __extends(Param, Base); + + })(Base); + + exports.Param = Param = (function(_super) { + + __extends(Param, _super); + + Param.name = 'Param'; + function Param(name, value, splat) { + var _ref2; this.name = name; this.value = value; this.splat = splat; + if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { + throw SyntaxError("parameter name \"" + name + "\" is not allowed"); + } } + Param.prototype.children = ['name', 'value']; + Param.prototype.compile = function(o) { return this.name.compile(o, LEVEL_LIST); }; + Param.prototype.asReference = function(o) { var node; - if (this.reference) { - return this.reference; - } + if (this.reference) return this.reference; node = this.name; if (node["this"]) { node = node.properties[0].name; if (node.value.reserved) { - node = new Literal('_' + node.value); + node = new Literal(o.scope.freeVariable(node.value)); } } else if (node.isComplex()) { node = new Literal(o.scope.freeVariable('arg')); } node = new Value(node); - if (this.splat) { - node = new Splat(node); - } + if (this.splat) node = new Splat(node); return this.reference = node; }; + Param.prototype.isComplex = function() { return this.name.isComplex(); }; + + Param.prototype.names = function(name) { + var atParam, names, obj, _i, _len, _ref2; + if (name == null) name = this.name; + atParam = function(obj) { + var value; + value = obj.properties[0].name.value; + if (value.reserved) { + return []; + } else { + return [value]; + } + }; + if (name instanceof Literal) return [name.value]; + if (name instanceof Value) return atParam(name); + names = []; + _ref2 = name.objects; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + obj = _ref2[_i]; + if (obj instanceof Assign) { + names.push(obj.variable.base.value); + } else if (obj.isArray() || obj.isObject()) { + names.push.apply(names, this.names(obj.base)); + } else if (obj["this"]) { + names.push.apply(names, atParam(obj)); + } else { + names.push(obj.base.value); + } + } + return names; + }; + return Param; - })(); - exports.Splat = Splat = (function() { - __extends(Splat, Base); + + })(Base); + + exports.Splat = Splat = (function(_super) { + + __extends(Splat, _super); + + Splat.name = 'Splat'; + Splat.prototype.children = ['name']; + Splat.prototype.isAssignable = YES; + function Splat(name) { this.name = name.compile ? name : new Literal(name); } + Splat.prototype.assigns = function(name) { return this.name.assigns(name); }; + Splat.prototype.compile = function(o) { if (this.index != null) { return this.compileParam(o); @@ -6108,24 +6374,25 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return this.name.compile(o); } }; + + Splat.prototype.unwrap = function() { + return this.name; + }; + Splat.compileSplattedArray = function(o, list, apply) { - var args, base, code, i, index, node, _len; + var args, base, code, i, index, node, _i, _len; index = -1; while ((node = list[++index]) && !(node instanceof Splat)) { continue; } - if (index >= list.length) { - return ''; - } + if (index >= list.length) return ''; if (list.length === 1) { code = list[0].compile(o, LEVEL_LIST); - if (apply) { - return code; - } + if (apply) return code; return "" + (utility('slice')) + ".call(" + code + ")"; } args = list.slice(index); - for (i = 0, _len = args.length; i < _len; i++) { + for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) { node = args[i]; code = node.compile(o, LEVEL_LIST); args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]"; @@ -6134,51 +6401,66 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")"); } base = (function() { - var _i, _len2, _ref2, _results; + var _j, _len1, _ref2, _results; _ref2 = list.slice(0, index); _results = []; - for (_i = 0, _len2 = _ref2.length; _i < _len2; _i++) { - node = _ref2[_i]; + for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { + node = _ref2[_j]; _results.push(node.compile(o, LEVEL_LIST)); } return _results; })(); return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")"; }; + return Splat; - })(); - exports.While = While = (function() { - __extends(While, Base); + + })(Base); + + exports.While = While = (function(_super) { + + __extends(While, _super); + + While.name = 'While'; + function While(condition, options) { this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition; this.guard = options != null ? options.guard : void 0; } + While.prototype.children = ['condition', 'guard', 'body']; + While.prototype.isStatement = YES; - While.prototype.makeReturn = function() { - this.returns = true; - return this; + + While.prototype.makeReturn = function(res) { + if (res) { + return While.__super__.makeReturn.apply(this, arguments); + } else { + this.returns = !this.jumps({ + loop: true + }); + return this; + } }; + While.prototype.addBody = function(body) { this.body = body; return this; }; + While.prototype.jumps = function() { var expressions, node, _i, _len; expressions = this.body.expressions; - if (!expressions.length) { - return false; - } + if (!expressions.length) return false; for (_i = 0, _len = expressions.length; _i < _len; _i++) { node = expressions[_i]; if (node.jumps({ loop: true - })) { - return node; - } + })) return node; } return false; }; + While.prototype.compileNode = function(o) { var body, code, rvar, set; o.indent += TAB; @@ -6187,41 +6469,40 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff if (body.isEmpty()) { body = ''; } else { - if (o.level > LEVEL_TOP || this.returns) { - rvar = o.scope.freeVariable('results'); + if (this.returns) { + body.makeReturn(rvar = o.scope.freeVariable('results')); set = "" + this.tab + rvar + " = [];\n"; - if (body) { - body = Push.wrap(rvar, body); - } } if (this.guard) { - body = Block.wrap([new If(this.guard, body)]); + if (body.expressions.length > 1) { + body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); + } else { + if (this.guard) body = Block.wrap([new If(this.guard, body)]); + } } body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab; } code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}"); - if (this.returns) { - code += "\n" + this.tab + "return " + rvar + ";"; - } + if (this.returns) code += "\n" + this.tab + "return " + rvar + ";"; return code; }; + return While; - })(); - exports.Op = Op = (function() { + + })(Base); + + exports.Op = Op = (function(_super) { var CONVERSIONS, INVERSIONS; - __extends(Op, Base); + + __extends(Op, _super); + + Op.name = 'Op'; + function Op(op, first, second, flip) { - var call; - if (op === 'in') { - return new In(first, second); - } - if (op === 'do') { - call = new Call(first, first.params || []); - call["do"] = true; - return call; - } + if (op === 'in') return new In(first, second); + if (op === 'do') return this.generateDo(first); if (op === 'new') { - if (first instanceof Call && !first["do"]) { + if (first instanceof Call && !first["do"] && !first.isNew) { return first.newInstance(); } if (first instanceof Code && first.bound || first["do"]) { @@ -6234,28 +6515,36 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff this.flip = !!flip; return this; } + CONVERSIONS = { '==': '===', '!=': '!==', 'of': 'in' }; + INVERSIONS = { '!==': '===', '===': '!==' }; + Op.prototype.children = ['first', 'second']; + Op.prototype.isSimpleNumber = NO; + Op.prototype.isUnary = function() { return !this.second; }; + Op.prototype.isComplex = function() { var _ref2; return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex(); }; + Op.prototype.isChainable = function() { var _ref2; return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!=='; }; + Op.prototype.invert = function() { var allInvertable, curr, fst, op, _ref2; if (this.isChainable() && this.first.isChainable()) { @@ -6265,9 +6554,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff allInvertable && (allInvertable = curr.operator in INVERSIONS); curr = curr.first; } - if (!allInvertable) { - return new Parens(this).invert(); - } + if (!allInvertable) return new Parens(this).invert(); curr = this; while (curr && curr.operator) { curr.invert = !curr.invert; @@ -6277,9 +6564,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return this; } else if (op = INVERSIONS[this.operator]) { this.operator = op; - if (this.first.unwrap() instanceof Op) { - this.first.invert(); - } + if (this.first.unwrap() instanceof Op) this.first.invert(); return this; } else if (this.second) { return new Parens(this).invert(); @@ -6289,22 +6574,44 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return new Op('!', this); } }; + Op.prototype.unfoldSoak = function(o) { var _ref2; return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first'); }; - Op.prototype.compileNode = function(o) { - var code; - if (this.isUnary()) { - return this.compileUnary(o); - } - if (this.isChainable() && this.first.isChainable()) { - return this.compileChain(o); - } - if (this.operator === '?') { - return this.compileExistence(o); + + Op.prototype.generateDo = function(exp) { + var call, func, param, passedParams, ref, _i, _len, _ref2; + passedParams = []; + func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp; + _ref2 = func.params || []; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + param = _ref2[_i]; + if (param.value) { + passedParams.push(param.value); + delete param.value; + } else { + passedParams.push(param); + } } - this.first.front = this.front; + call = new Call(exp, passedParams); + call["do"] = true; + return call; + }; + + Op.prototype.compileNode = function(o) { + var code, isChain, _ref2, _ref3; + isChain = this.isChainable() && this.first.isChainable(); + if (!isChain) this.first.front = this.front; + if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) { + throw SyntaxError('delete operand may not be argument or var'); + } + if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) { + throw SyntaxError('prefix increment/decrement may not have eval or arguments operand'); + } + if (this.isUnary()) return this.compileUnary(o); + if (isChain) return this.compileChain(o); + if (this.operator === '?') return this.compileExistence(o); code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP); if (o.level <= LEVEL_OP) { return code; @@ -6312,6 +6619,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + code + ")"; } }; + Op.prototype.compileChain = function(o) { var code, fst, shared, _ref2; _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1]; @@ -6319,9 +6627,10 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP)); return "(" + code + ")"; }; + Op.prototype.compileExistence = function(o) { var fst, ref; - if (this.first.isComplex()) { + if (this.first.isComplex() && o.level > LEVEL_TOP) { ref = new Literal(o.scope.freeVariable('ref')); fst = new Parens(new Assign(ref, this.first)); } else { @@ -6332,68 +6641,76 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff type: 'if' }).addElse(this.second).compile(o); }; + Op.prototype.compileUnary = function(o) { - var op, parts; + var op, parts, plusMinus; + if (o.level >= LEVEL_ACCESS) return (new Parens(this)).compile(o); parts = [op = this.operator]; - if ((op === 'new' || op === 'typeof' || op === 'delete') || (op === '+' || op === '-') && this.first instanceof Op && this.first.operator === op) { + plusMinus = op === '+' || op === '-'; + if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) { parts.push(' '); } - if (op === 'new' && this.first.isStatement(o)) { + if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) { this.first = new Parens(this.first); } parts.push(this.first.compile(o, LEVEL_OP)); - if (this.flip) { - parts.reverse(); - } + if (this.flip) parts.reverse(); return parts.join(''); }; + Op.prototype.toString = function(idt) { return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator); }; + return Op; - })(); - exports.In = In = (function() { - __extends(In, Base); + + })(Base); + + exports.In = In = (function(_super) { + + __extends(In, _super); + + In.name = 'In'; + function In(object, array) { this.object = object; this.array = array; } + In.prototype.children = ['object', 'array']; + In.prototype.invert = NEGATE; + In.prototype.compileNode = function(o) { var hasSplat, obj, _i, _len, _ref2; if (this.array instanceof Value && this.array.isArray()) { _ref2 = this.array.base.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; - if (obj instanceof Splat) { - hasSplat = true; - break; - } - } - if (!hasSplat) { - return this.compileOrTest(o); + if (!(obj instanceof Splat)) continue; + hasSplat = true; + break; } + if (!hasSplat) return this.compileOrTest(o); } return this.compileLoopTest(o); }; + In.prototype.compileOrTest = function(o) { var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3; + if (this.array.base.objects.length === 0) return "" + (!!this.negated); _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1]; _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1]; tests = (function() { - var _len, _ref4, _results; + var _i, _len, _ref4, _results; _ref4 = this.array.base.objects; _results = []; - for (i = 0, _len = _ref4.length; i < _len; i++) { + for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) { item = _ref4[i]; - _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_OP)); + _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS)); } return _results; }).call(this); - if (tests.length === 0) { - return 'false'; - } tests = tests.join(cnj); if (o.level < LEVEL_OP) { return tests; @@ -6401,13 +6718,12 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + tests + ")"; } }; + In.prototype.compileLoopTest = function(o) { var code, ref, sub, _ref2; _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1]; code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0'); - if (sub === ref) { - return code; - } + if (sub === ref) return code; code = sub + ', ' + code; if (o.level < LEVEL_LIST) { return code; @@ -6415,91 +6731,151 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + code + ")"; } }; + In.prototype.toString = function(idt) { return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : '')); }; + return In; - })(); - exports.Try = Try = (function() { - __extends(Try, Base); + + })(Base); + + exports.Try = Try = (function(_super) { + + __extends(Try, _super); + + Try.name = 'Try'; + function Try(attempt, error, recovery, ensure) { this.attempt = attempt; this.error = error; this.recovery = recovery; this.ensure = ensure; } + Try.prototype.children = ['attempt', 'recovery', 'ensure']; + Try.prototype.isStatement = YES; + Try.prototype.jumps = function(o) { var _ref2; return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0); }; - Try.prototype.makeReturn = function() { - if (this.attempt) { - this.attempt = this.attempt.makeReturn(); - } - if (this.recovery) { - this.recovery = this.recovery.makeReturn(); - } + + Try.prototype.makeReturn = function(res) { + if (this.attempt) this.attempt = this.attempt.makeReturn(res); + if (this.recovery) this.recovery = this.recovery.makeReturn(res); return this; }; + Try.prototype.compileNode = function(o) { - var catchPart, errorPart; + var catchPart, ensurePart, errorPart, tryPart; o.indent += TAB; errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' '; - catchPart = this.recovery ? " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : !(this.ensure || this.recovery) ? ' catch (_e) {}' : void 0; - return ("" + this.tab + "try {\n" + (this.attempt.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" + (catchPart || '')) + (this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''); + tryPart = this.attempt.compile(o, LEVEL_TOP); + catchPart = (function() { + var _ref2; + if (this.recovery) { + if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { + throw SyntaxError("catch variable may not be \"" + this.error.value + "\""); + } + if (!o.scope.check(this.error.value)) { + o.scope.add(this.error.value, 'param'); + } + return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"; + } else if (!(this.ensure || this.recovery)) { + return ' catch (_error) {}'; + } + }).call(this); + ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''; + return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart; }; + return Try; - })(); - exports.Throw = Throw = (function() { - __extends(Throw, Base); + + })(Base); + + exports.Throw = Throw = (function(_super) { + + __extends(Throw, _super); + + Throw.name = 'Throw'; + function Throw(expression) { this.expression = expression; } + Throw.prototype.children = ['expression']; + Throw.prototype.isStatement = YES; + Throw.prototype.jumps = NO; + Throw.prototype.makeReturn = THIS; + Throw.prototype.compileNode = function(o) { return this.tab + ("throw " + (this.expression.compile(o)) + ";"); }; + return Throw; - })(); - exports.Existence = Existence = (function() { - __extends(Existence, Base); + + })(Base); + + exports.Existence = Existence = (function(_super) { + + __extends(Existence, _super); + + Existence.name = 'Existence'; + function Existence(expression) { this.expression = expression; } + Existence.prototype.children = ['expression']; + Existence.prototype.invert = NEGATE; + Existence.prototype.compileNode = function(o) { var cmp, cnj, code, _ref2; + this.expression.front = this.front; code = this.expression.compile(o, LEVEL_OP); - code = IDENTIFIER.test(code) && !o.scope.check(code) ? ((_ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1], _ref2), "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null") : "" + code + " " + (this.negated ? '==' : '!=') + " null"; + if (IDENTIFIER.test(code) && !o.scope.check(code)) { + _ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1]; + code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null"; + } else { + code = "" + code + " " + (this.negated ? '==' : '!=') + " null"; + } if (o.level <= LEVEL_COND) { return code; } else { return "(" + code + ")"; } }; + return Existence; - })(); - exports.Parens = Parens = (function() { - __extends(Parens, Base); + + })(Base); + + exports.Parens = Parens = (function(_super) { + + __extends(Parens, _super); + + Parens.name = 'Parens'; + function Parens(body) { this.body = body; } + Parens.prototype.children = ['body']; + Parens.prototype.unwrap = function() { return this.body; }; + Parens.prototype.isComplex = function() { return this.body.isComplex(); }; - Parens.prototype.makeReturn = function() { - return this.body.makeReturn(); - }; + Parens.prototype.compileNode = function(o) { var bare, code, expr; expr = this.body.unwrap(); @@ -6515,10 +6891,17 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return "(" + code + ")"; } }; + return Parens; - })(); - exports.For = For = (function() { - __extends(For, Base); + + })(Base); + + exports.For = For = (function(_super) { + + __extends(For, _super); + + For.name = 'For'; + function For(body, source) { var _ref2; this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index; @@ -6541,20 +6924,14 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } this.returns = false; } + For.prototype.children = ['body', 'source', 'guard', 'step']; - For.prototype.isStatement = YES; - For.prototype.jumps = While.prototype.jumps; - For.prototype.makeReturn = function() { - this.returns = true; - return this; - }; + For.prototype.compileNode = function(o) { - var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; + var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; body = Block.wrap([this.body]); lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0; - if (lastJumps && lastJumps instanceof Return) { - this.returns = false; - } + if (lastJumps && lastJumps instanceof Return) this.returns = false; source = this.range ? this.source.base : this.source; scope = o.scope; name = this.name && this.name.compile(o, LEVEL_LIST); @@ -6569,16 +6946,12 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff immediate: true }); } - if (this.returns) { - rvar = scope.freeVariable('results'); - } - ivar = (this.range ? name : index) || scope.freeVariable('i'); - if (this.step && !this.range) { - stepvar = scope.freeVariable("step"); - } - if (this.pattern) { - name = ivar; - } + if (this.returns) rvar = scope.freeVariable('results'); + ivar = (this.object && index) || scope.freeVariable('i'); + kvar = (this.range && name) || index || ivar; + kvarAssign = kvar !== ivar ? "" + kvar + " = " : ""; + if (this.step && !this.range) stepvar = scope.freeVariable("step"); + if (this.pattern) name = ivar; varPart = ''; guardPart = ''; defPart = ''; @@ -6586,6 +6959,7 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff if (this.range) { forPart = source.compile(merge(o, { index: ivar, + name: name, step: this.step })); } else { @@ -6595,54 +6969,56 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff svar = ref; } if (name && !this.pattern) { - namePart = "" + name + " = " + svar + "[" + ivar + "]"; + namePart = "" + name + " = " + svar + "[" + kvar + "]"; } if (!this.object) { lvar = scope.freeVariable('len'); - forVarPart = ("" + ivar + " = 0, " + lvar + " = " + svar + ".length") + (this.step ? ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)) : ''); - stepPart = this.step ? "" + ivar + " += " + stepvar : "" + ivar + "++"; + forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length"; + if (this.step) { + forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)); + } + stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++")); forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart; } } if (this.returns) { resultPart = "" + this.tab + rvar + " = [];\n"; returnResult = "\n" + this.tab + "return " + rvar + ";"; - body = Push.wrap(rvar, body); + body.makeReturn(rvar); } if (this.guard) { - body = Block.wrap([new If(this.guard, body)]); + if (body.expressions.length > 1) { + body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); + } else { + if (this.guard) body = Block.wrap([new If(this.guard, body)]); + } } if (this.pattern) { - body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + ivar + "]"))); + body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]"))); } defPart += this.pluckDirectCall(o, body); - if (namePart) { - varPart = "\n" + idt1 + namePart + ";"; - } + if (namePart) varPart = "\n" + idt1 + namePart + ";"; if (this.object) { - forPart = "" + ivar + " in " + svar; + forPart = "" + kvar + " in " + svar; if (this.own) { - guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + ivar + ")) continue;"; + guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;"; } } body = body.compile(merge(o, { indent: idt1 }), LEVEL_TOP); - if (body) { - body = '\n' + body + '\n'; - } + if (body) body = '\n' + body + '\n'; return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || ''); }; + For.prototype.pluckDirectCall = function(o, body) { - var base, defs, expr, fn, idx, ref, val, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; + var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; defs = ''; _ref2 = body.expressions; - for (idx = 0, _len = _ref2.length; idx < _len; idx++) { + for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) { expr = _ref2[idx]; expr = expr.unwrapAll(); - if (!(expr instanceof Call)) { - continue; - } + if (!(expr instanceof Call)) continue; val = expr.variable.unwrapAll(); if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) { continue; @@ -6650,26 +7026,33 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val; ref = new Literal(o.scope.freeVariable('fn')); base = new Value(ref); - if (val.base) { - _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; - args.unshift(new Literal('this')); - } + if (val.base) _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; body.expressions[idx] = new Call(base, expr.args); defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n'; } return defs; }; + return For; - })(); - exports.Switch = Switch = (function() { - __extends(Switch, Base); + + })(While); + + exports.Switch = Switch = (function(_super) { + + __extends(Switch, _super); + + Switch.name = 'Switch'; + function Switch(subject, cases, otherwise) { this.subject = subject; this.cases = cases; this.otherwise = otherwise; } + Switch.prototype.children = ['subject', 'cases', 'otherwise']; + Switch.prototype.isStatement = YES; + Switch.prototype.jumps = function(o) { var block, conds, _i, _len, _ref2, _ref3, _ref4; if (o == null) { @@ -6680,46 +7063,41 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1]; - if (block.jumps(o)) { - return block; - } + if (block.jumps(o)) return block; } return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0; }; - Switch.prototype.makeReturn = function() { + + Switch.prototype.makeReturn = function(res) { var pair, _i, _len, _ref2, _ref3; _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { pair = _ref2[_i]; - pair[1].makeReturn(); + pair[1].makeReturn(res); } - if ((_ref3 = this.otherwise) != null) { - _ref3.makeReturn(); + if (res) { + this.otherwise || (this.otherwise = new Block([new Literal('void 0')])); } + if ((_ref3 = this.otherwise) != null) _ref3.makeReturn(res); return this; }; + Switch.prototype.compileNode = function(o) { - var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _len, _len2, _ref2, _ref3, _ref4, _ref5; + var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5; idt1 = o.indent + TAB; idt2 = o.indent = idt1 + TAB; code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n"); _ref3 = this.cases; - for (i = 0, _len = _ref3.length; i < _len; i++) { + for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) { _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1]; _ref5 = flatten([conditions]); - for (_i = 0, _len2 = _ref5.length; _i < _len2; _i++) { - cond = _ref5[_i]; - if (!this.subject) { - cond = cond.invert(); - } + for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) { + cond = _ref5[_j]; + if (!this.subject) cond = cond.invert(); code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n"); } - if (body = block.compile(o, LEVEL_TOP)) { - code += body + '\n'; - } - if (i === this.cases.length - 1 && !this.otherwise) { - break; - } + if (body = block.compile(o, LEVEL_TOP)) code += body + '\n'; + if (i === this.cases.length - 1 && !this.otherwise) break; expr = this.lastNonComment(block.expressions); if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) { continue; @@ -6731,29 +7109,38 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return code + this.tab + '}'; }; + return Switch; - })(); - exports.If = If = (function() { - __extends(If, Base); + + })(Base); + + exports.If = If = (function(_super) { + + __extends(If, _super); + + If.name = 'If'; + function If(condition, body, options) { this.body = body; - if (options == null) { - options = {}; - } + if (options == null) options = {}; this.condition = options.type === 'unless' ? condition.invert() : condition; this.elseBody = null; this.isChain = false; this.soak = options.soak; } + If.prototype.children = ['condition', 'body', 'elseBody']; + If.prototype.bodyNode = function() { var _ref2; return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0; }; + If.prototype.elseBodyNode = function() { var _ref2; return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0; }; + If.prototype.addElse = function(elseBody) { if (this.isChain) { this.elseBodyNode().addElse(elseBody); @@ -6763,14 +7150,17 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } return this; }; + If.prototype.isStatement = function(o) { var _ref2; return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0); }; + If.prototype.jumps = function(o) { var _ref2; return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0); }; + If.prototype.compileNode = function(o) { if (this.isStatement(o)) { return this.compileStatement(o); @@ -6778,11 +7168,16 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return this.compileExpression(o); } }; - If.prototype.makeReturn = function() { - this.body && (this.body = new Block([this.body.makeReturn()])); - this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn()])); + + If.prototype.makeReturn = function(res) { + if (res) { + this.elseBody || (this.elseBody = new Block([new Literal('void 0')])); + } + this.body && (this.body = new Block([this.body.makeReturn(res)])); + this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)])); return this; }; + If.prototype.ensureBlock = function(node) { if (node instanceof Block) { return node; @@ -6790,8 +7185,9 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return new Block([node]); } }; + If.prototype.compileStatement = function(o) { - var body, child, cond, exeq, ifPart; + var body, bodyc, child, cond, exeq, ifPart, _ref2; child = del(o, 'chainChild'); exeq = del(o, 'isExistentialEquals'); if (exeq) { @@ -6801,19 +7197,18 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff } cond = this.condition.compile(o, LEVEL_PAREN); o.indent += TAB; - body = this.ensureBlock(this.body).compile(o); - if (body) { - body = "\n" + body + "\n" + this.tab; - } - ifPart = "if (" + cond + ") {" + body + "}"; - if (!child) { - ifPart = this.tab + ifPart; - } - if (!this.elseBody) { - return ifPart; - } + body = this.ensureBlock(this.body); + bodyc = body.compile(o); + if (1 === ((_ref2 = body.expressions) != null ? _ref2.length : void 0) && !this.elseBody && !child && bodyc && cond && -1 === (bodyc.indexOf('\n')) && 80 > cond.length + bodyc.length) { + return "" + this.tab + "if (" + cond + ") " + (bodyc.replace(/^\s+/, '')); + } + if (bodyc) bodyc = "\n" + bodyc + "\n" + this.tab; + ifPart = "if (" + cond + ") {" + bodyc + "}"; + if (!child) ifPart = this.tab + ifPart; + if (!this.elseBody) return ifPart; return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"); }; + If.prototype.compileExpression = function(o) { var alt, body, code, cond; cond = this.condition.compile(o, LEVEL_COND); @@ -6826,33 +7221,25 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return code; } }; + If.prototype.unfoldSoak = function() { return this.soak && this; }; + return If; - })(); - Push = { - wrap: function(name, exps) { - if (exps.isEmpty() || last(exps.expressions).jumps()) { - return exps; - } - return exps.push(new Call(new Value(new Literal(name), [new Access(new Literal('push'))]), [exps.pop()])); - } - }; + + })(Base); + Closure = { wrap: function(expressions, statement, noReturn) { var args, call, func, mentionsArgs, meth; - if (expressions.jumps()) { - return expressions; - } + if (expressions.jumps()) return expressions; func = new Code([], Block.wrap([expressions])); args = []; if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) { meth = new Literal(mentionsArgs ? 'apply' : 'call'); args = [new Literal('this')]; - if (mentionsArgs) { - args.push(new Literal('arguments')); - } + if (mentionsArgs) args.push(new Literal('arguments')); func = new Value(func, [new Access(meth)]); } func.noReturn = noReturn; @@ -6870,46 +7257,73 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound); } }; + unfoldSoak = function(o, parent, name) { var ifn; - if (!(ifn = parent[name].unfoldSoak(o))) { - return; - } + if (!(ifn = parent[name].unfoldSoak(o))) return; parent[name] = ifn.body; ifn.body = new Value(parent); return ifn; }; + UTILITIES = { - "extends": 'function(child, parent) {\n for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor;\n child.__super__ = parent.prototype;\n return child;\n}', - bind: 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }', - indexOf: 'Array.prototype.indexOf || function(item) {\n for (var i = 0, l = this.length; i < l; i++) {\n if (this[i] === item) return i;\n }\n return -1;\n}', - hasProp: 'Object.prototype.hasOwnProperty', - slice: 'Array.prototype.slice' + "extends": function() { + return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }"; + }, + bind: function() { + return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }'; + }, + indexOf: function() { + return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"; + }, + hasProp: function() { + return '{}.hasOwnProperty'; + }, + slice: function() { + return '[].slice'; + } }; + LEVEL_TOP = 1; + LEVEL_PAREN = 2; + LEVEL_LIST = 3; + LEVEL_COND = 4; + LEVEL_OP = 5; + LEVEL_ACCESS = 6; + TAB = ' '; - IDENTIFIER = /^[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*$/; + + IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; + + IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$"); + SIMPLENUM = /^[+-]?\d+$/; - METHOD_DEF = /^(?:([$A-Za-z_][$\w\x7f-\uffff]*)\.prototype\.)?([$A-Za-z_][$\w\x7f-\uffff]*)$/; + + METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$"); + IS_STRING = /^['"]/; + utility = function(name) { var ref; ref = "__" + name; - Scope.root.assign(ref, UTILITIES[name]); + Scope.root.assign(ref, UTILITIES[name]()); return ref; }; + multident = function(code, tab) { - return code.replace(/\n/g, '$&' + tab); + code = code.replace(/\n/g, '$&' + tab); + return code.replace(/\s+$/, ''); }; -}); -/** + + +});/** * Copyright (c) 2011 Jeremy Ashkenas - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -6933,10 +7347,18 @@ define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coff */ define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coffee/helpers'], function(require, exports, module) { +// Generated by CoffeeScript 1.2.1-pre + var Scope, extend, last, _ref; + _ref = require('./helpers'), extend = _ref.extend, last = _ref.last; + exports.Scope = Scope = (function() { + + Scope.name = 'Scope'; + Scope.root = null; + function Scope(parent, expressions, method) { this.parent = parent; this.expressions = expressions; @@ -6948,17 +7370,13 @@ define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coff } ]; this.positions = {}; - if (!this.parent) { - Scope.root = this; - } + if (!this.parent) Scope.root = this; } + Scope.prototype.add = function(name, type, immediate) { - var pos; - if (this.shared && !immediate) { - return this.parent.add(name, type, immediate); - } - if (typeof (pos = this.positions[name]) === 'number') { - return this.variables[pos].type = type; + if (this.shared && !immediate) return this.parent.add(name, type, immediate); + if (Object.prototype.hasOwnProperty.call(this.positions, name)) { + return this.variables[this.positions[name]].type = type; } else { return this.positions[name] = this.variables.push({ name: name, @@ -6966,89 +7384,94 @@ define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coff }) - 1; } }; + Scope.prototype.find = function(name, options) { - if (this.check(name, options)) { - return true; - } + if (this.check(name, options)) return true; this.add(name, 'var'); return false; }; + Scope.prototype.parameter = function(name) { - if (this.shared && this.parent.check(name, true)) { - return; - } + if (this.shared && this.parent.check(name, true)) return; return this.add(name, 'param'); }; + Scope.prototype.check = function(name, immediate) { - var found, _ref2; + var found, _ref1; found = !!this.type(name); - if (found || immediate) { - return found; - } - return !!((_ref2 = this.parent) != null ? _ref2.check(name) : void 0); + if (found || immediate) return found; + return !!((_ref1 = this.parent) != null ? _ref1.check(name) : void 0); }; + Scope.prototype.temporary = function(name, index) { if (name.length > 1) { - return '_' + name + (index > 1 ? index : ''); + return '_' + name + (index > 1 ? index - 1 : ''); } else { return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a'); } }; + Scope.prototype.type = function(name) { - var v, _i, _len, _ref2; - _ref2 = this.variables; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - v = _ref2[_i]; - if (v.name === name) { - return v.type; - } + var v, _i, _len, _ref1; + _ref1 = this.variables; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + v = _ref1[_i]; + if (v.name === name) return v.type; } return null; }; - Scope.prototype.freeVariable = function(type) { + + Scope.prototype.freeVariable = function(name, reserve) { var index, temp; + if (reserve == null) reserve = true; index = 0; - while (this.check((temp = this.temporary(type, index)))) { + while (this.check((temp = this.temporary(name, index)))) { index++; } - this.add(temp, 'var', true); + if (reserve) this.add(temp, 'var', true); return temp; }; + Scope.prototype.assign = function(name, value) { this.add(name, { value: value, assigned: true - }); + }, true); return this.hasAssignments = true; }; + Scope.prototype.hasDeclarations = function() { return !!this.declaredVariables().length; }; + Scope.prototype.declaredVariables = function() { - var realVars, tempVars, v, _i, _len, _ref2; + var realVars, tempVars, v, _i, _len, _ref1; realVars = []; tempVars = []; - _ref2 = this.variables; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - v = _ref2[_i]; + _ref1 = this.variables; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + v = _ref1[_i]; if (v.type === 'var') { (v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name); } } return realVars.sort().concat(tempVars.sort()); }; + Scope.prototype.assignedVariables = function() { - var v, _i, _len, _ref2, _results; - _ref2 = this.variables; + var v, _i, _len, _ref1, _results; + _ref1 = this.variables; _results = []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - v = _ref2[_i]; - if (v.type.assigned) { - _results.push("" + v.name + " = " + v.type.value); - } + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + v = _ref1[_i]; + if (v.type.assigned) _results.push("" + v.name + " = " + v.type.value); } return _results; }; + return Scope; + })(); -}); + + +}); \ No newline at end of file diff --git a/apps/files_texteditor/js/aceeditor/worker-css.js b/apps/files_texteditor/js/aceeditor/worker-css.js index 7b179068ae1..7037c9b6aa6 100644 --- a/apps/files_texteditor/js/aceeditor/worker-css.js +++ b/apps/files_texteditor/js/aceeditor/worker-css.js @@ -198,7 +198,7 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; - if (match) { + if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { @@ -263,7 +263,8 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex return -1; }; -});// vim: ts=4 sts=4 sw=4 expandtab +}); +// vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA @@ -1784,11 +1785,12 @@ var Document = function(text) { }; this.insert = function(position, text) { - if (text.length == 0) + if (!text || text.length === 0) return position; position = this.$clipPosition(position); + // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); @@ -2068,7 +2070,7 @@ var Range = function(startRow, startColumn, endRow, endColumn) { }; (function() { - this.isEequal = function(range) { + this.isEqual = function(range) { return this.start.row == range.start.row && this.end.row == range.end.row && this.start.column == range.start.column && @@ -2134,6 +2136,11 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } + this.intersectsRange = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + } + this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } @@ -2293,6 +2300,21 @@ var Range = function(startRow, startColumn, endRow, endColumn) { return Range.fromPoints(start || this.start, end || this.end); }; + this.fixOrientation = function() { + if ( + this.start.row < this.end.row + || (this.start.row == this.end.row && this.start.column < this.end.column) + ) { + return false; + } + + var temp = this.start; + this.end = this.start; + this.start = temp; + return true; + }; + + this.isEmpty = function() { return (this.start.row == this.end.row && this.start.column == this.end.column); }; @@ -2676,7 +2698,8 @@ exports.deferredCall = function(fcn) { }; }); -/* +define('ace/mode/css/csslint', ['require', 'exports', 'module' ], function(require, exports, module) { +/*! CSSLint Copyright (c) 2011 Nicole Sullivan and Nicholas C. Zakas. All rights reserved. @@ -2699,7 +2722,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -define('ace/mode/css/csslint', ['require', 'exports', 'module' ], function(require, exports, module) { +/* Build time: 2-March-2012 02:47:11 */ + /*! Parser-Lib Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved. @@ -2723,10 +2747,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* Build time: 13-July-2011 04:35:28 */ +/* Version v0.1.6, Build time: 2-March-2012 02:44:32 */ var parserlib = {}; (function(){ + /** * A generic base to inherit from for any object * that needs event handling. @@ -2775,11 +2800,11 @@ EventTarget.prototype = { if (typeof event == "string"){ event = { type: event }; } - if (!event.target){ + if (typeof event.target != "undefined"){ event.target = this; } - if (!event.type){ + if (typeof event.type == "undefined"){ throw new Error("Event object missing 'type' property."); } @@ -3126,7 +3151,7 @@ SyntaxError.prototype = new Error(); * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ -function SyntaxUnit(text, line, col){ +function SyntaxUnit(text, line, col, type){ /** @@ -3150,6 +3175,12 @@ function SyntaxUnit(text, line, col){ */ this.text = text; + /** + * The type of syntax unit. + * @type int + * @property type + */ + this.type = type; } /** @@ -3189,6 +3220,8 @@ SyntaxUnit.prototype = { } }; +/*global StringReader, SyntaxError*/ + /** * Generic TokenStream providing base functionality. * @class TokenStreamBase @@ -3205,7 +3238,6 @@ function TokenStreamBase(input, tokenData){ * @property _reader * @private */ - //this._reader = (typeof input == "string") ? new StringReader(input) : input; this._reader = input ? new StringReader(input.toString()) : null; /** @@ -3254,14 +3286,14 @@ function TokenStreamBase(input, tokenData){ */ TokenStreamBase.createTokenData = function(tokens){ - var nameMap = [], - typeMap = {}, - tokenData = tokens.concat([]), - i = 0, - len = tokenData.length+1; + var nameMap = [], + typeMap = {}, + tokenData = tokens.concat([]), + i = 0, + len = tokenData.length+1; tokenData.UNKNOWN = -1; - tokenData.unshift({name:"EOF"}); + tokenData.unshift({name:"EOF"}); for (; i < len; i++){ nameMap.push(tokenData[i].name); @@ -3278,8 +3310,8 @@ TokenStreamBase.createTokenData = function(tokens){ tokenData.type = function(c){ return typeMap[c]; }; - - return tokenData; + + return tokenData; }; TokenStreamBase.prototype = { @@ -3340,6 +3372,8 @@ TokenStreamBase.prototype = { */ mustMatch: function(tokenTypes, channel){ + var token; + //always convert to an array, makes things easier if (!(tokenTypes instanceof Array)){ tokenTypes = [tokenTypes]; @@ -3369,7 +3403,7 @@ TokenStreamBase.prototype = { */ advance: function(tokenTypes, channel){ - while(this.LA(0) != 0 && !this.match(tokenTypes, channel)){ + while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){ this.get(); } @@ -3416,7 +3450,7 @@ TokenStreamBase.prototype = { } //call token retriever method - token = this._getToken(); + token = this._getToken(); //if it should be hidden, don't save a token if (token.type > -1 && !tokenInfo[token.type].hide){ @@ -3589,6 +3623,7 @@ TokenStreamBase.prototype = { + parserlib.util = { StringReader: StringReader, SyntaxError : SyntaxError, @@ -3598,6 +3633,7 @@ TokenStreamBase : TokenStreamBase }; })(); + /* Parser-Lib Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved. @@ -3621,7 +3657,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* Build time: 13-July-2011 04:35:28 */ +/* Version v0.1.6, Build time: 2-March-2012 02:44:32 */ (function(){ var EventTarget = parserlib.util.EventTarget, TokenStreamBase = parserlib.util.TokenStreamBase, @@ -3629,6 +3665,7 @@ StringReader = parserlib.util.StringReader, SyntaxError = parserlib.util.SyntaxError, SyntaxUnit = parserlib.util.SyntaxUnit; + var Colors = { aliceblue :"#f0f8ff", antiquewhite :"#faebd7", @@ -3697,7 +3734,7 @@ var Colors = { lightcoral :"#f08080", lightcyan :"#e0ffff", lightgoldenrodyellow :"#fafad2", - lightgrey :"#d3d3d3", + lightgray :"#d3d3d3", lightgreen :"#90ee90", lightpink :"#ffb6c1", lightsalmon :"#ffa07a", @@ -3771,6 +3808,7 @@ var Colors = { yellow :"#ffff00", yellowgreen :"#9acd32" }; +/*global SyntaxUnit, Parser*/ /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css @@ -3783,7 +3821,7 @@ var Colors = { */ function Combinator(text, line, col){ - SyntaxUnit.call(this, text, line, col); + SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE); /** * The type of modifier. @@ -3809,182 +3847,7 @@ Combinator.prototype = new SyntaxUnit(); Combinator.prototype.constructor = Combinator; - -var Level1Properties = { - - "background": 1, - "background-attachment": 1, - "background-color": 1, - "background-image": 1, - "background-position": 1, - "background-repeat": 1, - - "border": 1, - "border-bottom": 1, - "border-bottom-width": 1, - "border-color": 1, - "border-left": 1, - "border-left-width": 1, - "border-right": 1, - "border-right-width": 1, - "border-style": 1, - "border-top": 1, - "border-top-width": 1, - "border-width": 1, - - "clear": 1, - "color": 1, - "display": 1, - "float": 1, - - "font": 1, - "font-family": 1, - "font-size": 1, - "font-style": 1, - "font-variant": 1, - "font-weight": 1, - - "height": 1, - "letter-spacing": 1, - "line-height": 1, - - "list-style": 1, - "list-style-image": 1, - "list-style-position": 1, - "list-style-type": 1, - - "margin": 1, - "margin-bottom": 1, - "margin-left": 1, - "margin-right": 1, - "margin-top": 1, - - "padding": 1, - "padding-bottom": 1, - "padding-left": 1, - "padding-right": 1, - "padding-top": 1, - - "text-align": 1, - "text-decoration": 1, - "text-indent": 1, - "text-transform": 1, - - "vertical-align": 1, - "white-space": 1, - "width": 1, - "word-spacing": 1 - -}; - -var Level2Properties = { - - //Aural - "azimuth": 1, - "cue-after": 1, - "cue-before": 1, - "cue": 1, - "elevation": 1, - "pause-after": 1, - "pause-before": 1, - "pause": 1, - "pitch-range": 1, - "pitch": 1, - "play-during": 1, - "richness": 1, - "speak-header": 1, - "speak-numeral": 1, - "speak-punctuation": 1, - "speak": 1, - "speech-rate": 1, - "stress": 1, - "voice-family": 1, - "volume": 1, - - //Paged - "orphans": 1, - "page-break-after": 1, - "page-break-before": 1, - "page-break-inside": 1, - "widows": 1, - - //Interactive - "cursor": 1, - "outline-color": 1, - "outline-style": 1, - "outline-width": 1, - "outline": 1, - - //Visual - "background-attachment": 1, - "background-color": 1, - "background-image": 1, - "background-position": 1, - "background-repeat": 1, - "background": 1, - "border-collapse": 1, - "border-color": 1, - "border-spacing": 1, - "border-style": 1, - "border-top": 1, - "border-top-color": 1, - "border-top-style": 1, - "border-top-width": 1, - "border-width": 1, - "border": 1, - "bottom": 1, - "caption-side": 1, - "clear": 1, - "clip": 1, - "color": 1, - "content": 1, - "counter-increment": 1, - "counter-reset": 1, - "direction": 1, - "display": 1, - "empty-cells": 1, - "float": 1, - "font-family": 1, - "font-size": 1, - "font-style": 1, - "font-variant": 1, - "font-weight": 1, - "font": 1, - "height": 1, - "left": 1, - "letter-spacing": 1, - "line-height": 1, - "list-style-image": 1, - "list-style-position": 1, - "list-style-type": 1, - "list-style": 1, - "margin-right": 1, - "margin-top": 1, - "margin": 1, - "max-height": 1, - "max-width": 1, - "min-height": 1, - "min-width": 1, - "overflow": 1, - "padding-top": 1, - "padding": 1, - "position": 1, - "quotes": 1, - "right": 1, - "table-layout": 1, - "text-align": 1, - "text-decoration": 1, - "text-indent": 1, - "text-transform": 1, - "top": 1, - "unicode-bidi": 1, - "vertical-align": 1, - "visibility": 1, - "white-space": 1, - "width": 1, - "word-spacing": 1, - "z-index": 1 -}; +/*global SyntaxUnit, Parser*/ /** * Represents a media feature, such as max-width:500. * @namespace parserlib.css @@ -3996,7 +3859,7 @@ var Level2Properties = { */ function MediaFeature(name, value){ - SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol); + SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE); /** * The name of the media feature @@ -4017,6 +3880,7 @@ MediaFeature.prototype = new SyntaxUnit(); MediaFeature.prototype.constructor = MediaFeature; +/*global SyntaxUnit, Parser*/ /** * Represents an individual media query. * @namespace parserlib.css @@ -4031,7 +3895,7 @@ MediaFeature.prototype.constructor = MediaFeature; */ function MediaQuery(modifier, mediaType, features, line, col){ - SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + features.join(" and "), line, col); + SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE); /** * The media modifier ("not" or "only") @@ -4060,6 +3924,10 @@ MediaQuery.prototype = new SyntaxUnit(); MediaQuery.prototype.constructor = MediaQuery; +/*global Tokens, TokenStream, SyntaxError, Properties, Validation, ValidationError, SyntaxUnit, + PropertyValue, PropertyValuePart, SelectorPart, SelectorSubPart, Selector, + PropertyName, Combinator, MediaFeature, MediaQuery, EventTarget */ + /** * A CSS3 parser. * @namespace parserlib.css @@ -4083,6 +3951,18 @@ function Parser(options){ this._tokenStream = null; } +//Static constants +Parser.DEFAULT_TYPE = 0; +Parser.COMBINATOR_TYPE = 1; +Parser.MEDIA_FEATURE_TYPE = 2; +Parser.MEDIA_QUERY_TYPE = 3; +Parser.PROPERTY_NAME_TYPE = 4; +Parser.PROPERTY_VALUE_TYPE = 5; +Parser.PROPERTY_VALUE_PART_TYPE = 6; +Parser.SELECTOR_TYPE = 7; +Parser.SELECTOR_PART_TYPE = 8; +Parser.SELECTOR_SUB_PART_TYPE = 9; + Parser.prototype = function(){ var proto = new EventTarget(), //new prototype @@ -4091,6 +3971,18 @@ Parser.prototype = function(){ //restore constructor constructor: Parser, + + //instance constants - yuck + DEFAULT_TYPE : 0, + COMBINATOR_TYPE : 1, + MEDIA_FEATURE_TYPE : 2, + MEDIA_QUERY_TYPE : 3, + PROPERTY_NAME_TYPE : 4, + PROPERTY_VALUE_TYPE : 5, + PROPERTY_VALUE_PART_TYPE : 6, + SELECTOR_TYPE : 7, + SELECTOR_PART_TYPE : 8, + SELECTOR_SUB_PART_TYPE : 9, //----------------------------------------------------------------- // Grammar @@ -4109,6 +4001,7 @@ Parser.prototype = function(){ var tokenStream = this._tokenStream, charset = null, + count, token, tt; @@ -4155,7 +4048,36 @@ Parser.prototype = function(){ case Tokens.KEYFRAMES_SYM: this._keyframes(); this._skipCruft(); - break; + break; + case Tokens.UNKNOWN_SYM: //unknown @ rule + tokenStream.get(); + if (!this.options.strict){ + + //fire error event + this.fire({ + type: "error", + error: null, + message: "Unknown @ rule: " + tokenStream.LT(0).value + ".", + line: tokenStream.LT(0).startLine, + col: tokenStream.LT(0).startCol + }); + + //skip braces + count=0; + while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){ + count++; //keep track of nesting depth + } + + while(count){ + tokenStream.advance([Tokens.RBRACE]); + count--; + } + + } else { + //not a syntax error, rethrow it + throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol); + } + break; case Tokens.S: this._readWhitespace(); break; @@ -5442,7 +5364,9 @@ Parser.prototype = function(){ var tokenStream = this._tokenStream, property = null, expr = null, - prio = null; + prio = null, + error = null, + invalid = null; property = this._property(); if (property !== null){ @@ -5459,13 +5383,20 @@ Parser.prototype = function(){ prio = this._prio(); + try { + this._validateProperty(property, expr); + } catch (ex) { + invalid = ex; + } + this.fire({ type: "property", property: property, value: expr, important: prio, line: property.line, - col: property.col + col: property.col, + invalid: invalid }); return true; @@ -5533,7 +5464,7 @@ Parser.prototype = function(){ values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col)); }*/ - return values.length > 0 ? new PropertyValue(values, values[0].startLine, values[0].startCol) : null; + return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null; }, _term: function(){ @@ -5550,6 +5481,7 @@ Parser.prototype = function(){ var tokenStream = this._tokenStream, unary = null, value = null, + token, line, col; @@ -5583,8 +5515,8 @@ Parser.prototype = function(){ } else { //see if it's a color - value = this._hexcolor(); - if (value === null){ + token = this._hexcolor(); + if (token === null){ //if there's no unary, get the start of the next token for line/col info if (unary === null){ @@ -5612,9 +5544,10 @@ Parser.prototype = function(){ }*/ } else { + value = token.value; if (unary === null){ - line = tokenStream.token().startLine; - col = tokenStream.token().startCol; + line = token.startLine; + col = token.startCol; } } @@ -5636,15 +5569,48 @@ Parser.prototype = function(){ var tokenStream = this._tokenStream, functionText = null, - expr = null; + expr = null, + lt; if (tokenStream.match(Tokens.FUNCTION)){ functionText = tokenStream.token().value; this._readWhitespace(); expr = this._expr(); + functionText += expr; + + //START: Horrible hack in case it's an IE filter + if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){ + do { + + if (this._readWhitespace()){ + functionText += tokenStream.token().value; + } + + //might be second time in the loop + if (tokenStream.LA(0) == Tokens.COMMA){ + functionText += tokenStream.token().value; + } + + tokenStream.match(Tokens.IDENT); + functionText += tokenStream.token().value; + + tokenStream.match(Tokens.EQUALS); + functionText += tokenStream.token().value; + + //functionText += this._term(); + lt = tokenStream.peek(); + while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){ + tokenStream.get(); + functionText += tokenStream.token().value; + lt = tokenStream.peek(); + } + } while(tokenStream.match([Tokens.COMMA, Tokens.S])); + } + + //END: Horrible Hack tokenStream.match(Tokens.RPAREN); - functionText += expr + ")"; + functionText += ")"; this._readWhitespace(); } @@ -5714,9 +5680,9 @@ Parser.prototype = function(){ */ var tokenStream = this._tokenStream, - token, - color = null; - + token = null, + color; + if(tokenStream.match(Tokens.HASH)){ //need to do some validation here @@ -5729,7 +5695,7 @@ Parser.prototype = function(){ this._readWhitespace(); } - return color; + return token; }, //----------------------------------------------------------------- @@ -5939,7 +5905,7 @@ Parser.prototype = function(){ while(true){ - if (readMargins && this._margin()){ + if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){ //noop } else if (this._declaration()){ if (!tokenStream.match(Tokens.SEMICOLON)){ @@ -5974,10 +5940,9 @@ Parser.prototype = function(){ tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]); if (tt == Tokens.SEMICOLON){ //if there's a semicolon, then there might be another declaration - this._readDeclarations(false, readMargins); - } else if (tt == Tokens.RBRACE){ + this._readDeclarations(false, readMargins); + } else if (tt != Tokens.RBRACE){ //if there's a right brace, the rule is finished so don't do anything - } else { //otherwise, rethrow the error because it wasn't handled properly throw ex; } @@ -6035,6 +6000,13 @@ Parser.prototype = function(){ } }, + //----------------------------------------------------------------- + // Validation methods + //----------------------------------------------------------------- + _validateProperty: function(property, value){ + Validation.validate(property, value); + }, + //----------------------------------------------------------------- // Parsing methods //----------------------------------------------------------------- @@ -6132,13 +6104,27 @@ Parser.prototype = function(){ //otherwise return result return result; + }, + + /** + * Parses an HTML style attribute: a set of CSS declarations + * separated by semicolons. + * @param {String} input The text to parse as a style attribute + * @return {void} + * @method parseStyleAttribute + */ + parseStyleAttribute: function(input){ + input += "}"; // for error recovery in _readDeclarations() + this._tokenStream = new TokenStream(input, Tokens); + this._readDeclarations(); } - }; //copy over onto prototype for (prop in additions){ - proto[prop] = additions[prop]; + if (additions.hasOwnProperty(prop)){ + proto[prop] = additions[prop]; + } } return proto; @@ -6151,6 +6137,485 @@ nth ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S* ; */ +/*global Validation, ValidationTypes, ValidationError*/ +var Properties = { + + //A + "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | | ", + "alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", + "animation" : 1, + "animation-delay" : { multi: "
    "; -echo ""; \ No newline at end of file +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; \ No newline at end of file -- GitLab From 8959e0af3def5bae8ca7d5cf8edc225f29a1162a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 11:39:00 +0200 Subject: [PATCH 183/430] implement shared calendar activation on js-side --- apps/calendar/js/calendar.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index a267f15f781..ebfe31723da 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -499,6 +499,9 @@ Calendar={ Share:{ currentid: 'false', idtype: '', + activation:function(object,owner,id){ + $.getJSON(OC.filePath('calendar', 'ajax/share', 'activation.php'),{id:id, idtype:'calendar', activation:object.checked?1:0}); + }, dropdown:function(userid, calid){ $('.calendar_share_dropdown').remove(); $('
    ').appendTo('#'+userid+'_'+calid); @@ -513,10 +516,7 @@ Calendar={ }, share:function(id, idtype, sharewith, sharetype){ $.getJSON(OC.filePath('calendar', 'ajax/share', 'share.php'),{id:id, idtype:idtype, sharewith:sharewith, sharetype:sharetype}, function(data){ - if(sharetype == 'public'){ - $('#public_token').val(window.location.protocol + '//' + location.host + OC.linkTo('calendar', 'share.php?t=' + data.message)); - $('#public_token').css('display', 'block'); - } + }); }, unshare:function(id, idtype, sharewith, sharetype){ -- GitLab From de7184288816e4d542985eb4d6a7dc33c77fb4ff Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 11:50:12 +0200 Subject: [PATCH 184/430] implement shared calendar activation on server side --- apps/calendar/ajax/share/activation.php | 12 ++++++++++++ apps/calendar/js/calendar.js | 1 + apps/calendar/lib/share.php | 9 +++++++++ apps/calendar/templates/part.choosecalendar.php | 4 ++-- 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 apps/calendar/ajax/share/activation.php diff --git a/apps/calendar/ajax/share/activation.php b/apps/calendar/ajax/share/activation.php new file mode 100644 index 00000000000..a4a3ce48192 --- /dev/null +++ b/apps/calendar/ajax/share/activation.php @@ -0,0 +1,12 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +require_once('../../../../lib/base.php'); +$id = strip_tags($_GET['id']); +$activation = strip_tags($_GET['activation']); +OC_Calendar_Share::set_active(OC_User::getUser(), $id, $activation); +OC_JSON::success(); \ No newline at end of file diff --git a/apps/calendar/js/calendar.js b/apps/calendar/js/calendar.js index ebfe31723da..a16856938ce 100644 --- a/apps/calendar/js/calendar.js +++ b/apps/calendar/js/calendar.js @@ -501,6 +501,7 @@ Calendar={ idtype: '', activation:function(object,owner,id){ $.getJSON(OC.filePath('calendar', 'ajax/share', 'activation.php'),{id:id, idtype:'calendar', activation:object.checked?1:0}); + $('#calendar_holder').fullCalendar('refetchEvents'); }, dropdown:function(userid, calid){ $('.calendar_share_dropdown').remove(); diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php index 16c10589671..8f91be97474 100644 --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -247,4 +247,13 @@ class OC_Calendar_Share{ } return $return; } + + /* + * @brief sets the active status of the calendar + * @param (string) $ + */ + public static function set_active($share, $id, $active){ + $stmt = OC_DB::prepare('UPDATE *PREFIX*calendar_share_calendar SET active = ? WHERE share = ? AND sharetype = "user" AND calendarid = ?'); + $stmt->execute(array($active, $share, $id)); + } } \ No newline at end of file diff --git a/apps/calendar/templates/part.choosecalendar.php b/apps/calendar/templates/part.choosecalendar.php index 3c6799d892e..d93a85aeca0 100644 --- a/apps/calendar/templates/part.choosecalendar.php +++ b/apps/calendar/templates/part.choosecalendar.php @@ -18,7 +18,7 @@ for($i = 0; $i < count($option_calendars); $i++){
      - +
    t("CalDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Calendar.UI.Calendar.edit(this, " . $_['calendar']["id"] . ");\">t("Delete") . "\" class=\"action\">t("CalDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Calendar.UI.Calendar.edit(this, " . $_['calendar']["id"] . ");\">t("Delete") . "\" class=\"action\">t("CardDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Contacts.UI.Addressbooks.editAddressbook(this, " . $_['addressbook']["id"] . ");\">t("Delete") . "\" class=\"action\">t("CardDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Contacts.UI.Addressbooks.editAddressbook(this, " . $_['addressbook']["id"] . ");\">t("Delete") . "\" class=\"action\">t("CalDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Calendar.UI.Calendar.edit(this, " . $_['calendar']["id"] . ");\">t("Delete") . "\" class=\"action\">
    -

    ">

    +

    ">


    @@ -28,7 +28,7 @@ for($i = 0; $i < count($option_calendars); $i++){ $share = OC_Calendar_Share::allSharedwithuser(OC_User::getUser(), OC_Calendar_Share::CALENDAR); $count = count($share); for($i = 0; $i < $count; $i++){ - $share[$i]['calendar'] = OC_Calendar_App::getCalendar($share[$i]['calendarid']); + $share[$i]['calendar'] = OC_Calendar_App::getCalendar($share[$i]['calendarid'], false, false); echo ''; $tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields.shared'); $tmpl->assign('share', $share[$i]); -- GitLab From dfc92675e0d76ad9550a274b712e084e1738831c Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 17:25:44 +0200 Subject: [PATCH 185/430] make menu work with movable apps --- lib/helper.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/helper.php b/lib/helper.php index 61a57ec27e3..77b56051419 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -41,7 +41,11 @@ class OC_Helper { $app .= '/'; // Check if the app is in the app folder if( file_exists( OC::$APPSROOT . '/apps/'. $app.$file )){ - $urlLinkTo = OC::$APPSWEBROOT . '/apps/' . $app . $file; + if(substr($app, -1, 1) == '/'){ + $app = substr($app, 0, strlen($app) - 1); + } + $urlLinkTo = OC::$WEBROOT . '?app=' . $app; + $urlLinkTo .= ($file!='index.php')?'&file=' . $file:''; } else{ $urlLinkTo = OC::$WEBROOT . '/' . $app . $file; -- GitLab From 45de7ad221f9e505abdabcc5084dd12c80851469 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 17:27:34 +0200 Subject: [PATCH 186/430] move files to app folder --- {files => apps/files}/admin.php | 0 {files => apps/files}/ajax/autocomplete.php | 0 {files => apps/files}/ajax/delete.php | 0 {files => apps/files}/ajax/download.php | 0 {files => apps/files}/ajax/list.php | 0 {files => apps/files}/ajax/mimeicon.php | 0 {files => apps/files}/ajax/move.php | 0 {files => apps/files}/ajax/newfile.php | 0 {files => apps/files}/ajax/newfolder.php | 0 {files => apps/files}/ajax/rawlist.php | 0 {files => apps/files}/ajax/rename.php | 0 {files => apps/files}/ajax/scan.php | 0 {files => apps/files}/ajax/timezone.php | 0 {files => apps/files}/ajax/upload.php | 0 {files => apps/files}/appinfo/app.php | 0 {files => apps/files}/css/files.css | 0 {files => apps/files}/download.php | 0 {files => apps/files}/index.php | 0 {files => apps/files}/js/admin.js | 0 {files => apps/files}/js/fileactions.js | 0 {files => apps/files}/js/filelist.js | 0 {files => apps/files}/js/files.js | 0 {files => apps/files}/js/timezone.js | 0 {files => apps/files}/l10n/ar.php | 0 {files => apps/files}/l10n/bg_BG.php | 0 {files => apps/files}/l10n/ca.php | 0 {files => apps/files}/l10n/cs_CZ.php | 0 {files => apps/files}/l10n/da.php | 0 {files => apps/files}/l10n/de.php | 0 {files => apps/files}/l10n/el.php | 0 {files => apps/files}/l10n/eo.php | 0 {files => apps/files}/l10n/es.php | 0 {files => apps/files}/l10n/et_EE.php | 0 {files => apps/files}/l10n/eu.php | 0 {files => apps/files}/l10n/fr.php | 0 {files => apps/files}/l10n/gl.php | 0 {files => apps/files}/l10n/he.php | 0 {files => apps/files}/l10n/hr.php | 0 {files => apps/files}/l10n/hu_HU.php | 0 {files => apps/files}/l10n/ia.php | 0 {files => apps/files}/l10n/id.php | 0 {files => apps/files}/l10n/it.php | 0 {files => apps/files}/l10n/ja_JP.php | 0 {files => apps/files}/l10n/lb.php | 0 {files => apps/files}/l10n/lt_LT.php | 0 {files => apps/files}/l10n/ms_MY.php | 0 {files => apps/files}/l10n/nb_NO.php | 0 {files => apps/files}/l10n/nl.php | 0 {files => apps/files}/l10n/nn_NO.php | 0 {files => apps/files}/l10n/pl.php | 0 {files => apps/files}/l10n/pt_BR.php | 0 {files => apps/files}/l10n/ro.php | 0 {files => apps/files}/l10n/ru.php | 0 {files => apps/files}/l10n/sk_SK.php | 0 {files => apps/files}/l10n/sl.php | 0 {files => apps/files}/l10n/sr.php | 0 {files => apps/files}/l10n/sr@latin.php | 0 {files => apps/files}/l10n/sv.php | 0 {files => apps/files}/l10n/th_TH.php | 0 {files => apps/files}/l10n/tr.php | 0 {files => apps/files}/l10n/xgettextfiles | 0 {files => apps/files}/l10n/zh_CN.php | 0 {files => apps/files}/settings.php | 0 {files => apps/files}/templates/admin.php | 0 {files => apps/files}/templates/index.php | 0 {files => apps/files}/templates/part.breadcrumb.php | 0 {files => apps/files}/templates/part.list.php | 0 {files => apps/files}/webdav.php | 0 68 files changed, 0 insertions(+), 0 deletions(-) rename {files => apps/files}/admin.php (100%) rename {files => apps/files}/ajax/autocomplete.php (100%) rename {files => apps/files}/ajax/delete.php (100%) rename {files => apps/files}/ajax/download.php (100%) rename {files => apps/files}/ajax/list.php (100%) rename {files => apps/files}/ajax/mimeicon.php (100%) rename {files => apps/files}/ajax/move.php (100%) rename {files => apps/files}/ajax/newfile.php (100%) rename {files => apps/files}/ajax/newfolder.php (100%) rename {files => apps/files}/ajax/rawlist.php (100%) rename {files => apps/files}/ajax/rename.php (100%) rename {files => apps/files}/ajax/scan.php (100%) rename {files => apps/files}/ajax/timezone.php (100%) rename {files => apps/files}/ajax/upload.php (100%) rename {files => apps/files}/appinfo/app.php (100%) rename {files => apps/files}/css/files.css (100%) rename {files => apps/files}/download.php (100%) rename {files => apps/files}/index.php (100%) rename {files => apps/files}/js/admin.js (100%) rename {files => apps/files}/js/fileactions.js (100%) rename {files => apps/files}/js/filelist.js (100%) rename {files => apps/files}/js/files.js (100%) rename {files => apps/files}/js/timezone.js (100%) rename {files => apps/files}/l10n/ar.php (100%) rename {files => apps/files}/l10n/bg_BG.php (100%) rename {files => apps/files}/l10n/ca.php (100%) rename {files => apps/files}/l10n/cs_CZ.php (100%) rename {files => apps/files}/l10n/da.php (100%) rename {files => apps/files}/l10n/de.php (100%) rename {files => apps/files}/l10n/el.php (100%) rename {files => apps/files}/l10n/eo.php (100%) rename {files => apps/files}/l10n/es.php (100%) rename {files => apps/files}/l10n/et_EE.php (100%) rename {files => apps/files}/l10n/eu.php (100%) rename {files => apps/files}/l10n/fr.php (100%) rename {files => apps/files}/l10n/gl.php (100%) rename {files => apps/files}/l10n/he.php (100%) rename {files => apps/files}/l10n/hr.php (100%) rename {files => apps/files}/l10n/hu_HU.php (100%) rename {files => apps/files}/l10n/ia.php (100%) rename {files => apps/files}/l10n/id.php (100%) rename {files => apps/files}/l10n/it.php (100%) rename {files => apps/files}/l10n/ja_JP.php (100%) rename {files => apps/files}/l10n/lb.php (100%) rename {files => apps/files}/l10n/lt_LT.php (100%) rename {files => apps/files}/l10n/ms_MY.php (100%) rename {files => apps/files}/l10n/nb_NO.php (100%) rename {files => apps/files}/l10n/nl.php (100%) rename {files => apps/files}/l10n/nn_NO.php (100%) rename {files => apps/files}/l10n/pl.php (100%) rename {files => apps/files}/l10n/pt_BR.php (100%) rename {files => apps/files}/l10n/ro.php (100%) rename {files => apps/files}/l10n/ru.php (100%) rename {files => apps/files}/l10n/sk_SK.php (100%) rename {files => apps/files}/l10n/sl.php (100%) rename {files => apps/files}/l10n/sr.php (100%) rename {files => apps/files}/l10n/sr@latin.php (100%) rename {files => apps/files}/l10n/sv.php (100%) rename {files => apps/files}/l10n/th_TH.php (100%) rename {files => apps/files}/l10n/tr.php (100%) rename {files => apps/files}/l10n/xgettextfiles (100%) rename {files => apps/files}/l10n/zh_CN.php (100%) rename {files => apps/files}/settings.php (100%) rename {files => apps/files}/templates/admin.php (100%) rename {files => apps/files}/templates/index.php (100%) rename {files => apps/files}/templates/part.breadcrumb.php (100%) rename {files => apps/files}/templates/part.list.php (100%) rename {files => apps/files}/webdav.php (100%) diff --git a/files/admin.php b/apps/files/admin.php similarity index 100% rename from files/admin.php rename to apps/files/admin.php diff --git a/files/ajax/autocomplete.php b/apps/files/ajax/autocomplete.php similarity index 100% rename from files/ajax/autocomplete.php rename to apps/files/ajax/autocomplete.php diff --git a/files/ajax/delete.php b/apps/files/ajax/delete.php similarity index 100% rename from files/ajax/delete.php rename to apps/files/ajax/delete.php diff --git a/files/ajax/download.php b/apps/files/ajax/download.php similarity index 100% rename from files/ajax/download.php rename to apps/files/ajax/download.php diff --git a/files/ajax/list.php b/apps/files/ajax/list.php similarity index 100% rename from files/ajax/list.php rename to apps/files/ajax/list.php diff --git a/files/ajax/mimeicon.php b/apps/files/ajax/mimeicon.php similarity index 100% rename from files/ajax/mimeicon.php rename to apps/files/ajax/mimeicon.php diff --git a/files/ajax/move.php b/apps/files/ajax/move.php similarity index 100% rename from files/ajax/move.php rename to apps/files/ajax/move.php diff --git a/files/ajax/newfile.php b/apps/files/ajax/newfile.php similarity index 100% rename from files/ajax/newfile.php rename to apps/files/ajax/newfile.php diff --git a/files/ajax/newfolder.php b/apps/files/ajax/newfolder.php similarity index 100% rename from files/ajax/newfolder.php rename to apps/files/ajax/newfolder.php diff --git a/files/ajax/rawlist.php b/apps/files/ajax/rawlist.php similarity index 100% rename from files/ajax/rawlist.php rename to apps/files/ajax/rawlist.php diff --git a/files/ajax/rename.php b/apps/files/ajax/rename.php similarity index 100% rename from files/ajax/rename.php rename to apps/files/ajax/rename.php diff --git a/files/ajax/scan.php b/apps/files/ajax/scan.php similarity index 100% rename from files/ajax/scan.php rename to apps/files/ajax/scan.php diff --git a/files/ajax/timezone.php b/apps/files/ajax/timezone.php similarity index 100% rename from files/ajax/timezone.php rename to apps/files/ajax/timezone.php diff --git a/files/ajax/upload.php b/apps/files/ajax/upload.php similarity index 100% rename from files/ajax/upload.php rename to apps/files/ajax/upload.php diff --git a/files/appinfo/app.php b/apps/files/appinfo/app.php similarity index 100% rename from files/appinfo/app.php rename to apps/files/appinfo/app.php diff --git a/files/css/files.css b/apps/files/css/files.css similarity index 100% rename from files/css/files.css rename to apps/files/css/files.css diff --git a/files/download.php b/apps/files/download.php similarity index 100% rename from files/download.php rename to apps/files/download.php diff --git a/files/index.php b/apps/files/index.php similarity index 100% rename from files/index.php rename to apps/files/index.php diff --git a/files/js/admin.js b/apps/files/js/admin.js similarity index 100% rename from files/js/admin.js rename to apps/files/js/admin.js diff --git a/files/js/fileactions.js b/apps/files/js/fileactions.js similarity index 100% rename from files/js/fileactions.js rename to apps/files/js/fileactions.js diff --git a/files/js/filelist.js b/apps/files/js/filelist.js similarity index 100% rename from files/js/filelist.js rename to apps/files/js/filelist.js diff --git a/files/js/files.js b/apps/files/js/files.js similarity index 100% rename from files/js/files.js rename to apps/files/js/files.js diff --git a/files/js/timezone.js b/apps/files/js/timezone.js similarity index 100% rename from files/js/timezone.js rename to apps/files/js/timezone.js diff --git a/files/l10n/ar.php b/apps/files/l10n/ar.php similarity index 100% rename from files/l10n/ar.php rename to apps/files/l10n/ar.php diff --git a/files/l10n/bg_BG.php b/apps/files/l10n/bg_BG.php similarity index 100% rename from files/l10n/bg_BG.php rename to apps/files/l10n/bg_BG.php diff --git a/files/l10n/ca.php b/apps/files/l10n/ca.php similarity index 100% rename from files/l10n/ca.php rename to apps/files/l10n/ca.php diff --git a/files/l10n/cs_CZ.php b/apps/files/l10n/cs_CZ.php similarity index 100% rename from files/l10n/cs_CZ.php rename to apps/files/l10n/cs_CZ.php diff --git a/files/l10n/da.php b/apps/files/l10n/da.php similarity index 100% rename from files/l10n/da.php rename to apps/files/l10n/da.php diff --git a/files/l10n/de.php b/apps/files/l10n/de.php similarity index 100% rename from files/l10n/de.php rename to apps/files/l10n/de.php diff --git a/files/l10n/el.php b/apps/files/l10n/el.php similarity index 100% rename from files/l10n/el.php rename to apps/files/l10n/el.php diff --git a/files/l10n/eo.php b/apps/files/l10n/eo.php similarity index 100% rename from files/l10n/eo.php rename to apps/files/l10n/eo.php diff --git a/files/l10n/es.php b/apps/files/l10n/es.php similarity index 100% rename from files/l10n/es.php rename to apps/files/l10n/es.php diff --git a/files/l10n/et_EE.php b/apps/files/l10n/et_EE.php similarity index 100% rename from files/l10n/et_EE.php rename to apps/files/l10n/et_EE.php diff --git a/files/l10n/eu.php b/apps/files/l10n/eu.php similarity index 100% rename from files/l10n/eu.php rename to apps/files/l10n/eu.php diff --git a/files/l10n/fr.php b/apps/files/l10n/fr.php similarity index 100% rename from files/l10n/fr.php rename to apps/files/l10n/fr.php diff --git a/files/l10n/gl.php b/apps/files/l10n/gl.php similarity index 100% rename from files/l10n/gl.php rename to apps/files/l10n/gl.php diff --git a/files/l10n/he.php b/apps/files/l10n/he.php similarity index 100% rename from files/l10n/he.php rename to apps/files/l10n/he.php diff --git a/files/l10n/hr.php b/apps/files/l10n/hr.php similarity index 100% rename from files/l10n/hr.php rename to apps/files/l10n/hr.php diff --git a/files/l10n/hu_HU.php b/apps/files/l10n/hu_HU.php similarity index 100% rename from files/l10n/hu_HU.php rename to apps/files/l10n/hu_HU.php diff --git a/files/l10n/ia.php b/apps/files/l10n/ia.php similarity index 100% rename from files/l10n/ia.php rename to apps/files/l10n/ia.php diff --git a/files/l10n/id.php b/apps/files/l10n/id.php similarity index 100% rename from files/l10n/id.php rename to apps/files/l10n/id.php diff --git a/files/l10n/it.php b/apps/files/l10n/it.php similarity index 100% rename from files/l10n/it.php rename to apps/files/l10n/it.php diff --git a/files/l10n/ja_JP.php b/apps/files/l10n/ja_JP.php similarity index 100% rename from files/l10n/ja_JP.php rename to apps/files/l10n/ja_JP.php diff --git a/files/l10n/lb.php b/apps/files/l10n/lb.php similarity index 100% rename from files/l10n/lb.php rename to apps/files/l10n/lb.php diff --git a/files/l10n/lt_LT.php b/apps/files/l10n/lt_LT.php similarity index 100% rename from files/l10n/lt_LT.php rename to apps/files/l10n/lt_LT.php diff --git a/files/l10n/ms_MY.php b/apps/files/l10n/ms_MY.php similarity index 100% rename from files/l10n/ms_MY.php rename to apps/files/l10n/ms_MY.php diff --git a/files/l10n/nb_NO.php b/apps/files/l10n/nb_NO.php similarity index 100% rename from files/l10n/nb_NO.php rename to apps/files/l10n/nb_NO.php diff --git a/files/l10n/nl.php b/apps/files/l10n/nl.php similarity index 100% rename from files/l10n/nl.php rename to apps/files/l10n/nl.php diff --git a/files/l10n/nn_NO.php b/apps/files/l10n/nn_NO.php similarity index 100% rename from files/l10n/nn_NO.php rename to apps/files/l10n/nn_NO.php diff --git a/files/l10n/pl.php b/apps/files/l10n/pl.php similarity index 100% rename from files/l10n/pl.php rename to apps/files/l10n/pl.php diff --git a/files/l10n/pt_BR.php b/apps/files/l10n/pt_BR.php similarity index 100% rename from files/l10n/pt_BR.php rename to apps/files/l10n/pt_BR.php diff --git a/files/l10n/ro.php b/apps/files/l10n/ro.php similarity index 100% rename from files/l10n/ro.php rename to apps/files/l10n/ro.php diff --git a/files/l10n/ru.php b/apps/files/l10n/ru.php similarity index 100% rename from files/l10n/ru.php rename to apps/files/l10n/ru.php diff --git a/files/l10n/sk_SK.php b/apps/files/l10n/sk_SK.php similarity index 100% rename from files/l10n/sk_SK.php rename to apps/files/l10n/sk_SK.php diff --git a/files/l10n/sl.php b/apps/files/l10n/sl.php similarity index 100% rename from files/l10n/sl.php rename to apps/files/l10n/sl.php diff --git a/files/l10n/sr.php b/apps/files/l10n/sr.php similarity index 100% rename from files/l10n/sr.php rename to apps/files/l10n/sr.php diff --git a/files/l10n/sr@latin.php b/apps/files/l10n/sr@latin.php similarity index 100% rename from files/l10n/sr@latin.php rename to apps/files/l10n/sr@latin.php diff --git a/files/l10n/sv.php b/apps/files/l10n/sv.php similarity index 100% rename from files/l10n/sv.php rename to apps/files/l10n/sv.php diff --git a/files/l10n/th_TH.php b/apps/files/l10n/th_TH.php similarity index 100% rename from files/l10n/th_TH.php rename to apps/files/l10n/th_TH.php diff --git a/files/l10n/tr.php b/apps/files/l10n/tr.php similarity index 100% rename from files/l10n/tr.php rename to apps/files/l10n/tr.php diff --git a/files/l10n/xgettextfiles b/apps/files/l10n/xgettextfiles similarity index 100% rename from files/l10n/xgettextfiles rename to apps/files/l10n/xgettextfiles diff --git a/files/l10n/zh_CN.php b/apps/files/l10n/zh_CN.php similarity index 100% rename from files/l10n/zh_CN.php rename to apps/files/l10n/zh_CN.php diff --git a/files/settings.php b/apps/files/settings.php similarity index 100% rename from files/settings.php rename to apps/files/settings.php diff --git a/files/templates/admin.php b/apps/files/templates/admin.php similarity index 100% rename from files/templates/admin.php rename to apps/files/templates/admin.php diff --git a/files/templates/index.php b/apps/files/templates/index.php similarity index 100% rename from files/templates/index.php rename to apps/files/templates/index.php diff --git a/files/templates/part.breadcrumb.php b/apps/files/templates/part.breadcrumb.php similarity index 100% rename from files/templates/part.breadcrumb.php rename to apps/files/templates/part.breadcrumb.php diff --git a/files/templates/part.list.php b/apps/files/templates/part.list.php similarity index 100% rename from files/templates/part.list.php rename to apps/files/templates/part.list.php diff --git a/files/webdav.php b/apps/files/webdav.php similarity index 100% rename from files/webdav.php rename to apps/files/webdav.php -- GitLab From b44bc9f4b289eda95ec94321c9698f3ce1a700be Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 17:42:11 +0200 Subject: [PATCH 187/430] remove require once lib base in some more files --- apps/files/admin.php | 2 +- apps/files/download.php | 2 +- apps/files/index.php | 4 ---- apps/files/settings.php | 2 +- apps/files/webdav.php | 2 +- ocs/providers.php | 2 +- ocs/v1.php | 2 +- search/index.php | 2 +- settings/admin.php | 2 +- settings/apps.php | 2 +- settings/help.php | 2 +- settings/log.php | 2 +- settings/personal.php | 2 +- settings/settings.php | 2 +- settings/users.php | 2 +- 15 files changed, 14 insertions(+), 18 deletions(-) diff --git a/apps/files/admin.php b/apps/files/admin.php index 4ae3ee51236..bdea70506fb 100644 --- a/apps/files/admin.php +++ b/apps/files/admin.php @@ -23,7 +23,7 @@ // Init owncloud -require_once('../lib/base.php'); + OC_Util::checkAdminUser(); diff --git a/apps/files/download.php b/apps/files/download.php index d1f5ba486d7..ec4a6e1fc9c 100644 --- a/apps/files/download.php +++ b/apps/files/download.php @@ -22,7 +22,7 @@ */ // Init owncloud -require_once('../lib/base.php'); + // Check if we are a user OC_Util::checkLoggedIn(); diff --git a/apps/files/index.php b/apps/files/index.php index aea91542db6..46b511d66eb 100644 --- a/apps/files/index.php +++ b/apps/files/index.php @@ -21,10 +21,6 @@ * */ - -// Init owncloud -require_once('../lib/base.php'); - // Check if we are a user OC_Util::checkLoggedIn(); diff --git a/apps/files/settings.php b/apps/files/settings.php index c47eb130095..41017c064ef 100644 --- a/apps/files/settings.php +++ b/apps/files/settings.php @@ -23,7 +23,7 @@ // Init owncloud -require_once('../lib/base.php'); + // Check if we are a user OC_Util::checkLoggedIn(); diff --git a/apps/files/webdav.php b/apps/files/webdav.php index 25e33024470..3418eba5a6c 100644 --- a/apps/files/webdav.php +++ b/apps/files/webdav.php @@ -29,7 +29,7 @@ $RUNTIME_NOSETUPFS = true; // only need filesystem apps $RUNTIME_APPTYPES=array('filesystem','authentication'); -require_once('../lib/base.php'); + // Backends $authBackend = new OC_Connector_Sabre_Auth(); diff --git a/ocs/providers.php b/ocs/providers.php index e1d6ef7ee1e..d4ccd4ef9f8 100644 --- a/ocs/providers.php +++ b/ocs/providers.php @@ -21,7 +21,7 @@ * */ -require_once('../lib/base.php'); + $url='http://'.substr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],0,-17).'ocs/v1.php/'; diff --git a/ocs/v1.php b/ocs/v1.php index f5ff6cb6054..ed97db2d9b3 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -21,7 +21,7 @@ * */ -require_once('../lib/base.php'); + @ob_clean(); OC_OCS::handle(); diff --git a/search/index.php b/search/index.php index 518695c56d2..d1f94f74a2e 100644 --- a/search/index.php +++ b/search/index.php @@ -23,7 +23,7 @@ // Init owncloud -require_once('../lib/base.php'); + // Check if we are a user OC_Util::checkLoggedIn(); diff --git a/settings/admin.php b/settings/admin.php index a997bad4e3c..399ddd907ee 100644 --- a/settings/admin.php +++ b/settings/admin.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ -require_once('../lib/base.php'); + OC_Util::checkAdminUser(); OC_Util::addStyle( "settings", "settings" ); diff --git a/settings/apps.php b/settings/apps.php index 0889b0c45ed..aed198c77c6 100644 --- a/settings/apps.php +++ b/settings/apps.php @@ -21,7 +21,7 @@ * */ -require_once('../lib/base.php'); + OC_Util::checkAdminUser(); // Load the files we need diff --git a/settings/help.php b/settings/help.php index 48fcec32782..00e93720eec 100644 --- a/settings/help.php +++ b/settings/help.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ -require_once('../lib/base.php'); + OC_Util::checkLoggedIn(); diff --git a/settings/log.php b/settings/log.php index ddbf72c4433..31e6f6ff371 100644 --- a/settings/log.php +++ b/settings/log.php @@ -20,7 +20,7 @@ * */ -require_once('../lib/base.php'); + OC_Util::checkAdminUser(); // Load the files we need diff --git a/settings/personal.php b/settings/personal.php index 41499657ac7..7717bb76667 100755 --- a/settings/personal.php +++ b/settings/personal.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ -require_once('../lib/base.php'); + OC_Util::checkLoggedIn(); // Highlight navigation entry diff --git a/settings/settings.php b/settings/settings.php index a49de85520b..c73d6b706ea 100644 --- a/settings/settings.php +++ b/settings/settings.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ -require_once('../lib/base.php'); + OC_Util::checkLoggedIn(); OC_Util::addStyle( 'settings', 'settings' ); diff --git a/settings/users.php b/settings/users.php index 96515a90ce4..591d85ff675 100644 --- a/settings/users.php +++ b/settings/users.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ -require_once('../lib/base.php'); + OC_Util::checkAdminUser(); // We have some javascript foo! -- GitLab From 3fb91a74112c00457d549c79d6908acdd32651c5 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 18 Apr 2012 17:49:50 +0200 Subject: [PATCH 188/430] restore require once command for non app files --- core/ajax/appconfig.php | 2 +- core/ajax/grouplist.php | 2 +- core/ajax/translations.php | 2 +- core/ajax/userlist.php | 2 +- core/ajax/validateuser.php | 2 +- core/ajax/vcategories/add.php | 2 +- core/ajax/vcategories/delete.php | 2 +- core/ajax/vcategories/edit.php | 2 +- core/lostpassword/index.php | 2 +- core/lostpassword/resetpassword.php | 2 +- ocs/providers.php | 2 +- ocs/v1.php | 2 +- search/ajax/search.php | 2 +- search/index.php | 2 +- settings/admin.php | 2 +- settings/ajax/changepassword.php | 2 +- settings/ajax/creategroup.php | 2 +- settings/ajax/createuser.php | 2 +- settings/ajax/disableapp.php | 2 +- settings/ajax/enableapp.php | 2 +- settings/ajax/getlog.php | 2 +- settings/ajax/lostpassword.php | 2 +- settings/ajax/openid.php | 2 +- settings/ajax/removegroup.php | 2 +- settings/ajax/removeuser.php | 2 +- settings/ajax/setlanguage.php | 2 +- settings/ajax/setloglevel.php | 2 +- settings/ajax/setquota.php | 2 +- settings/ajax/togglegroups.php | 2 +- settings/apps.php | 2 +- settings/help.php | 2 +- settings/log.php | 2 +- settings/personal.php | 2 +- settings/settings.php | 2 +- settings/users.php | 2 +- 35 files changed, 35 insertions(+), 35 deletions(-) diff --git a/core/ajax/appconfig.php b/core/ajax/appconfig.php index 41e421b2fe4..f815d710631 100644 --- a/core/ajax/appconfig.php +++ b/core/ajax/appconfig.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ - +require_once ("../../lib/base.php"); OC_JSON::checkLoggedIn(); $action=isset($_POST['action'])?$_POST['action']:$_GET['action']; $result=false; diff --git a/core/ajax/grouplist.php b/core/ajax/grouplist.php index ba079e2dae1..cc15102bbc3 100644 --- a/core/ajax/grouplist.php +++ b/core/ajax/grouplist.php @@ -22,7 +22,7 @@ */ $RUNTIME_NOAPPS = TRUE; //no apps, yet - +require_once('../../lib/base.php'); if(!OC_User::isLoggedIn()){ if(!isset($_SERVER['PHP_AUTH_USER'])){ diff --git a/core/ajax/translations.php b/core/ajax/translations.php index 3091926095f..a6433b1964a 100644 --- a/core/ajax/translations.php +++ b/core/ajax/translations.php @@ -22,7 +22,7 @@ */ // Init owncloud - +require_once('../../lib/base.php'); $app = $_POST["app"]; diff --git a/core/ajax/userlist.php b/core/ajax/userlist.php index d9910d5a98f..c8168eaf460 100644 --- a/core/ajax/userlist.php +++ b/core/ajax/userlist.php @@ -22,7 +22,7 @@ */ $RUNTIME_NOAPPS = TRUE; //no apps, yet - +require_once('../../lib/base.php'); if(!OC_User::isLoggedIn()){ if(!isset($_SERVER['PHP_AUTH_USER'])){ diff --git a/core/ajax/validateuser.php b/core/ajax/validateuser.php index a55c54a9a46..258bd50fcad 100644 --- a/core/ajax/validateuser.php +++ b/core/ajax/validateuser.php @@ -22,7 +22,7 @@ */ $RUNTIME_NOAPPS = TRUE; //no apps, yet - +require_once('../../lib/base.php'); if(!isset($_SERVER['PHP_AUTH_USER'])){ header('WWW-Authenticate: Basic realm="ownCloud Server"'); diff --git a/core/ajax/vcategories/add.php b/core/ajax/vcategories/add.php index b0183af7fc5..a58489228d8 100644 --- a/core/ajax/vcategories/add.php +++ b/core/ajax/vcategories/add.php @@ -14,7 +14,7 @@ function debug($msg) { OC_Log::write('core','ajax/vcategories/add.php: '.$msg, OC_Log::DEBUG); } - +require_once('../../../lib/base.php'); OC_JSON::checkLoggedIn(); $category = isset($_GET['category'])?strip_tags($_GET['category']):null; $app = isset($_GET['app'])?$_GET['app']:null; diff --git a/core/ajax/vcategories/delete.php b/core/ajax/vcategories/delete.php index f96add3d8c3..75def433d30 100644 --- a/core/ajax/vcategories/delete.php +++ b/core/ajax/vcategories/delete.php @@ -15,7 +15,7 @@ function debug($msg) { OC_Log::write('core','ajax/vcategories/delete.php: '.$msg, OC_Log::DEBUG); } - +require_once('../../../lib/base.php'); OC_JSON::checkLoggedIn(); $app = isset($_POST['app'])?$_POST['app']:null; $categories = isset($_POST['categories'])?$_POST['categories']:null; diff --git a/core/ajax/vcategories/edit.php b/core/ajax/vcategories/edit.php index 5b346bef28c..252b3d3454c 100644 --- a/core/ajax/vcategories/edit.php +++ b/core/ajax/vcategories/edit.php @@ -15,7 +15,7 @@ function debug($msg) { OC_Log::write('core','ajax/vcategories/edit.php: '.$msg, OC_Log::DEBUG); } - +require_once('../../../lib/base.php'); OC_JSON::checkLoggedIn(); $app = isset($_GET['app'])?$_GET['app']:null; diff --git a/core/lostpassword/index.php b/core/lostpassword/index.php index 1400ec67cab..89bb6cfa794 100644 --- a/core/lostpassword/index.php +++ b/core/lostpassword/index.php @@ -7,7 +7,7 @@ */ $RUNTIME_NOAPPS = TRUE; //no apps - +require_once('../../lib/base.php'); // Someone lost their password: if (isset($_POST['user'])) { diff --git a/core/lostpassword/resetpassword.php b/core/lostpassword/resetpassword.php index 5f16e854f42..1c78d720947 100644 --- a/core/lostpassword/resetpassword.php +++ b/core/lostpassword/resetpassword.php @@ -7,7 +7,7 @@ */ $RUNTIME_NOAPPS = TRUE; //no apps - +require_once('../../lib/base.php'); // Someone wants to reset their password: if(isset($_GET['token']) && isset($_GET['user']) && OC_Preferences::getValue($_GET['user'], 'owncloud', 'lostpassword') === $_GET['token']) { diff --git a/ocs/providers.php b/ocs/providers.php index d4ccd4ef9f8..e1d6ef7ee1e 100644 --- a/ocs/providers.php +++ b/ocs/providers.php @@ -21,7 +21,7 @@ * */ - +require_once('../lib/base.php'); $url='http://'.substr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],0,-17).'ocs/v1.php/'; diff --git a/ocs/v1.php b/ocs/v1.php index ed97db2d9b3..f5ff6cb6054 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -21,7 +21,7 @@ * */ - +require_once('../lib/base.php'); @ob_clean(); OC_OCS::handle(); diff --git a/search/ajax/search.php b/search/ajax/search.php index 8f89256b827..326724d60c4 100644 --- a/search/ajax/search.php +++ b/search/ajax/search.php @@ -23,7 +23,7 @@ // Init owncloud - +require_once('../../lib/base.php'); // Check if we are a user OC_JSON::checkLoggedIn(); diff --git a/search/index.php b/search/index.php index d1f94f74a2e..518695c56d2 100644 --- a/search/index.php +++ b/search/index.php @@ -23,7 +23,7 @@ // Init owncloud - +require_once('../lib/base.php'); // Check if we are a user OC_Util::checkLoggedIn(); diff --git a/settings/admin.php b/settings/admin.php index 399ddd907ee..a997bad4e3c 100644 --- a/settings/admin.php +++ b/settings/admin.php @@ -5,7 +5,7 @@ * See the COPYING-README file. */ - +require_once('../lib/base.php'); OC_Util::checkAdminUser(); OC_Util::addStyle( "settings", "settings" ); diff --git a/settings/ajax/changepassword.php b/settings/ajax/changepassword.php index 0ed3c4919f5..860ea987871 100644 --- a/settings/ajax/changepassword.php +++ b/settings/ajax/changepassword.php @@ -1,7 +1,7 @@ Date: Tue, 17 Apr 2012 20:56:53 +0200 Subject: [PATCH 189/430] bugfixes for encryption library and test cases --- apps/files_encryption/lib/crypt.php | 55 +++++++++++----------- apps/files_encryption/tests/encryption.php | 36 ++++++++++++++ 2 files changed, 64 insertions(+), 27 deletions(-) create mode 100644 apps/files_encryption/tests/encryption.php diff --git a/apps/files_encryption/lib/crypt.php b/apps/files_encryption/lib/crypt.php index 246d4f672db..8cf9451c63c 100644 --- a/apps/files_encryption/lib/crypt.php +++ b/apps/files_encryption/lib/crypt.php @@ -119,7 +119,7 @@ class OC_Crypt { */ public static function encrypt( $content, $key='') { $bf = self::getBlowfish($key); - return($bf->encrypt($content)); + return $bf->encrypt($content); } /** @@ -132,61 +132,62 @@ class OC_Crypt { */ public static function decrypt( $content, $key='') { $bf = self::getBlowfish($key); - return($bf->decrypt($content)); + $data=$bf->decrypt($content); + return rtrim($data, "\0"); } /** * @brief encryption of a file - * @param $filename - * @param $key the encryption key + * @param string $source + * @param string $target + * @param string $key the decryption key * * This function encrypts a file */ - public static function encryptfile( $filename, $key) { - $handleread = fopen($filename, "rb"); - if($handleread<>FALSE) { - $handlewrite = fopen($filename.OC_Crypt::$encription_extension, "wb"); + public static function encryptFile( $source, $target, $key='') { + $handleread = fopen($source, "rb"); + if($handleread!=FALSE) { + $handlewrite = fopen($target, "wb"); while (!feof($handleread)) { $content = fread($handleread, 8192); $enccontent=OC_CRYPT::encrypt( $content, $key); fwrite($handlewrite, $enccontent); } fclose($handlewrite); - unlink($filename); + fclose($handleread); } - fclose($handleread); } - /** - * @brief decryption of a file - * @param $filename - * @param $key the decryption key - * - * This function decrypts a file - */ - public static function decryptfile( $filename, $key) { - $handleread = fopen($filename.OC_Crypt::$encription_extension, "rb"); - if($handleread<>FALSE) { - $handlewrite = fopen($filename, "wb"); + /** + * @brief decryption of a file + * @param string $source + * @param string $target + * @param string $key the decryption key + * + * This function decrypts a file + */ + public static function decryptFile( $source, $target, $key='') { + $handleread = fopen($source, "rb"); + if($handleread!=FALSE) { + $handlewrite = fopen($target, "wb"); while (!feof($handleread)) { $content = fread($handleread, 8192); $enccontent=OC_CRYPT::decrypt( $content, $key); fwrite($handlewrite, $enccontent); } fclose($handlewrite); - unlink($filename.OC_Crypt::$encription_extension); + fclose($handleread); } - fclose($handleread); } /** * encrypt data in 8192b sized blocks */ - public static function blockEncrypt($data){ + public static function blockEncrypt($data, $key=''){ $result=''; while(strlen($data)){ - $result=self::encrypt(substr($data,0,8192)); + $result.=self::encrypt(substr($data,0,8192),$key); $data=substr($data,8192); } return $result; @@ -195,10 +196,10 @@ class OC_Crypt { /** * decrypt data in 8192b sized blocks */ - public static function blockDecrypt($data){ + public static function blockDecrypt($data, $key=''){ $result=''; while(strlen($data)){ - $result=self::decrypt(substr($data,0,8192)); + $result.=self::decrypt(substr($data,0,8192),$key); $data=substr($data,8192); } return $result; diff --git a/apps/files_encryption/tests/encryption.php b/apps/files_encryption/tests/encryption.php new file mode 100644 index 00000000000..140fe6b126d --- /dev/null +++ b/apps/files_encryption/tests/encryption.php @@ -0,0 +1,36 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_Encryption extends UnitTestCase { + function testEncryption(){ + $key=uniqid(); + $file=OC::$SERVERROOT.'/3rdparty/MDB2.php'; + $source=file_get_contents($file); //nice large text file + $encrypted=OC_Crypt::encrypt($source,$key); + $decrypted=OC_Crypt::decrypt($encrypted,$key); + $this->assertNotEqual($encrypted,$source); + $this->assertEqual($decrypted,$source); + + $encrypted=OC_Crypt::blockEncrypt($source,$key); + $decrypted=OC_Crypt::blockDecrypt($encrypted,$key); + $this->assertNotEqual($encrypted,$source); + $this->assertEqual($decrypted,$source); + + $tmpFileEncrypted=OC_Helper::tmpFile(); + OC_Crypt::encryptfile($file,$tmpFileEncrypted,$key); + $encrypted=file_get_contents($tmpFileEncrypted); + $decrypted=OC_Crypt::blockDecrypt($encrypted,$key); + $this->assertNotEqual($encrypted,$source); + $this->assertEqual($decrypted,$source); + + $tmpFileDecrypted=OC_Helper::tmpFile(); + OC_Crypt::decryptfile($tmpFileEncrypted,$tmpFileDecrypted,$key); + $decrypted=file_get_contents($tmpFileDecrypted); + $this->assertEqual($decrypted,$source); + } +} -- GitLab From b39c3d4c4edbb9a7fd2be22e2d2684e4185ca0e5 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Tue, 17 Apr 2012 23:10:14 +0200 Subject: [PATCH 190/430] make use of the fact that stream_read will always read 8192 bytes for encryption stream https://bugs.php.net/bug.php?id=21641 --- apps/files_encryption/lib/cryptstream.php | 38 ++++++--------- apps/files_encryption/tests/stream.php | 56 +++++++++++++++++++++++ 2 files changed, 71 insertions(+), 23 deletions(-) create mode 100644 apps/files_encryption/tests/stream.php diff --git a/apps/files_encryption/lib/cryptstream.php b/apps/files_encryption/lib/cryptstream.php index 86583096f1d..21fa38e4b59 100644 --- a/apps/files_encryption/lib/cryptstream.php +++ b/apps/files_encryption/lib/cryptstream.php @@ -64,29 +64,19 @@ class OC_CryptStream{ } public function stream_read($count){ - $pos=0; - $currentPos=ftell($this->source); - $offset=$currentPos%8192; - $result=''; - if($offset>0){ - if($this->meta['seekable']){ - fseek($this->source,-$offset,SEEK_CUR);//if seeking isnt supported the internal read buffer will be used - }else{ - $pos=strlen($this->readBuffer); - $result=$this->readBuffer; - } + //$count will always be 8192 https://bugs.php.net/bug.php?id=21641 + //This makes this function a lot simpler but will breake everything the moment it's fixed + if($count!=8192){ + OC_Log::write('files_encryption','php bug 21641 no longer holds, decryption will not work',OC_Log::FATAL); + die(); } - while($count>$pos){ - $data=fread($this->source,8192); - $pos+=8192; - if(strlen($data)){ - $result.=OC_Crypt::decrypt($data); - } - } - if(!$this->meta['seekable']){ - $this->readBuffer=substr($result,$count); + $data=fread($this->source,8192); + if(strlen($data)){ + $result=OC_Crypt::decrypt($data); + }else{ + $result=''; } - return substr($result,0,$count); + return $result; } public function stream_write($data){ @@ -107,8 +97,10 @@ class OC_CryptStream{ $oldPos=ftell($this->source); $encryptedBlock=fread($this->source,8192); fseek($this->source,$oldPos); - $block=OC_Crypt::decrypt($encryptedBlock); - $data.=substr($block,strlen($data)); + if($encryptedBlock){ + $block=OC_Crypt::decrypt($encryptedBlock); + $data.=substr($block,strlen($data)); + } } $encrypted=OC_Crypt::encrypt(substr($data,0,8192)); fwrite($this->source,$encrypted); diff --git a/apps/files_encryption/tests/stream.php b/apps/files_encryption/tests/stream.php new file mode 100644 index 00000000000..578b091a36c --- /dev/null +++ b/apps/files_encryption/tests/stream.php @@ -0,0 +1,56 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_CryptStream extends UnitTestCase { + private $tmpFiles=array(); + + function testStream(){ + $stream=$this->getStream('test1','w'); + fwrite($stream,'foobar'); + fclose($stream); + + $stream=$this->getStream('test1','r'); + $data=fread($stream,6); + fclose($stream); + $this->assertEqual('foobar',$data); + + $file=OC::$SERVERROOT.'/3rdparty/MDB2.php'; + $source=fopen($file,'r'); + $target=$this->getStream('test2','w'); + OC_Helper::streamCopy($source,$target); + fclose($target); + fclose($source); + + $stream=$this->getStream('test2','r'); + $data=stream_get_contents($stream); + $original=file_get_contents($file); + $this->assertEqual(strlen($original),strlen($data)); + $this->assertEqual($original,$data); + } + + /** + * get a cryptstream to a temporary file + * @param string $id + * @param string $mode + * @return resource + */ + function getStream($id,$mode){ + if($id===''){ + $id=uniqid(); + } + if(!isset($this->tmpFiles[$id])){ + $file=OC_Helper::tmpFile(); + $this->tmpFiles[$id]=$file; + }else{ + $file=$this->tmpFiles[$id]; + } + $stream=fopen($file,$mode); + OC_CryptStream::$sourceStreams[$id]=array('path'=>'dummy','stream'=>$stream); + return fopen('crypt://streams/'.$id,$mode); + } +} -- GitLab From d1ad4dc8d60a656606b6c237df9f4c931f828c73 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 18 Apr 2012 16:02:35 +0200 Subject: [PATCH 191/430] add test cases for cryptstream --- apps/files_encryption/lib/proxy.php | 7 +++++++ apps/files_encryption/tests/encryption.php | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index c68df06f9fa..a0de411a7b6 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -28,6 +28,7 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ private static $blackList=null; //mimetypes blacklisted from encryption private static $metaData=array(); //metadata cache + private static $enableEncryption=null; /** * check if a file should be encrypted during write @@ -35,6 +36,12 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ * @return bool */ private static function shouldEncrypt($path){ + if(is_null($this->enableEncryption)){ + $this->enableEncryption=(OC_Appconfig::getValue('files_encryption','enabled','true')=='true'); + } + if(!$this->enableEncryption){ + return false; + } if(is_null(self::$blackList)){ self::$blackList=explode(',',OC_Appconfig::getValue('files_encryption','type_blacklist','jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg')); } diff --git a/apps/files_encryption/tests/encryption.php b/apps/files_encryption/tests/encryption.php index 140fe6b126d..13093256717 100644 --- a/apps/files_encryption/tests/encryption.php +++ b/apps/files_encryption/tests/encryption.php @@ -15,6 +15,12 @@ class Test_Encryption extends UnitTestCase { $decrypted=OC_Crypt::decrypt($encrypted,$key); $this->assertNotEqual($encrypted,$source); $this->assertEqual($decrypted,$source); + + $chunk=substr($source,0,8192); + $encrypted=OC_Crypt::encrypt($chunk,$key); + $this->assertEqual(strlen($chunk),strlen($encrypted)); + $decrypted=OC_Crypt::decrypt($encrypted,$key); + $this->assertEqual($decrypted,$chunk); $encrypted=OC_Crypt::blockEncrypt($source,$key); $decrypted=OC_Crypt::blockDecrypt($encrypted,$key); -- GitLab From bdb3962b8dc42493a9db87882d1671d6d3a53eea Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 18 Apr 2012 20:24:22 +0200 Subject: [PATCH 192/430] add function to get mimetype from string --- lib/helper.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/helper.php b/lib/helper.php index eed94917767..beb10280d93 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -353,6 +353,26 @@ class OC_Helper { return $mimeType; } + /** + * get the mimetype form a data string + * @param string data + * @return string + */ + static function getStringMimeType($data){ + if(function_exists('finfo_open') and function_exists('finfo_file')){ + $finfo=finfo_open(FILEINFO_MIME); + return finfo_buffer($finfo, $data); + }else{ + $tmpFile=OC_Helper::tmpFile(); + $fh=fopen($tmpFile,'wb'); + fwrite($fh,$data,8024); + fclose($fh); + $mime=self::getMimeType($tmpFile); + unset($tmpFile); + return $mime; + } + } + /** * @brief Checks $_REQUEST contains a var for the $s key. If so, returns the html-escaped value of this var; otherwise returns the default value provided by $d. * @param $s name of the var to escape, if set. -- GitLab From aceda02887eb4a52188f0308c6404cc9f201ce79 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 18 Apr 2012 20:46:00 +0200 Subject: [PATCH 193/430] check if removed folders are really gone --- tests/lib/filestorage.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/lib/filestorage.php b/tests/lib/filestorage.php index 4858234a2d8..b58e28cefde 100644 --- a/tests/lib/filestorage.php +++ b/tests/lib/filestorage.php @@ -68,6 +68,15 @@ abstract class Test_FileStorage extends UnitTestCase { $this->assertFalse($this->instance->file_exists('/folder')); $this->assertFalse($this->instance->rmdir('/folder'));//cant remove non existing folders + + $dh=$this->instance->opendir('/'); + $content=array(); + while($file=readdir($dh)){ + if($file!='.' and $file!='..'){ + $content[]=$file; + } + } + $this->assertEqual(array(),$content); } /** -- GitLab From 9a707e10bf70619bf1a553b2bc56c989f9725ab2 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 18 Apr 2012 20:54:07 +0200 Subject: [PATCH 194/430] add SWIFT (openstack object storage) storage backend --- 3rdparty/php-cloudfiles/.gitignore | 3 + 3rdparty/php-cloudfiles/AUTHORS | 11 + 3rdparty/php-cloudfiles/COPYING | 27 + 3rdparty/php-cloudfiles/Changelog | 93 + 3rdparty/php-cloudfiles/README | 73 + 3rdparty/php-cloudfiles/cloudfiles.php | 2599 +++++++++++++++++ .../php-cloudfiles/cloudfiles_exceptions.php | 41 + 3rdparty/php-cloudfiles/cloudfiles_http.php | 1488 ++++++++++ apps/files_external/appinfo/app.php | 1 + apps/files_external/lib/swift.php | 488 ++++ apps/files_external/tests/config.php | 9 +- apps/files_external/tests/swift.php | 32 + 12 files changed, 4864 insertions(+), 1 deletion(-) create mode 100644 3rdparty/php-cloudfiles/.gitignore create mode 100644 3rdparty/php-cloudfiles/AUTHORS create mode 100644 3rdparty/php-cloudfiles/COPYING create mode 100644 3rdparty/php-cloudfiles/Changelog create mode 100644 3rdparty/php-cloudfiles/README create mode 100644 3rdparty/php-cloudfiles/cloudfiles.php create mode 100644 3rdparty/php-cloudfiles/cloudfiles_exceptions.php create mode 100644 3rdparty/php-cloudfiles/cloudfiles_http.php create mode 100644 apps/files_external/lib/swift.php create mode 100644 apps/files_external/tests/swift.php diff --git a/3rdparty/php-cloudfiles/.gitignore b/3rdparty/php-cloudfiles/.gitignore new file mode 100644 index 00000000000..875b72b27e7 --- /dev/null +++ b/3rdparty/php-cloudfiles/.gitignore @@ -0,0 +1,3 @@ +*.swp +*~ +tests/output.log diff --git a/3rdparty/php-cloudfiles/AUTHORS b/3rdparty/php-cloudfiles/AUTHORS new file mode 100644 index 00000000000..a92cfa7c1a9 --- /dev/null +++ b/3rdparty/php-cloudfiles/AUTHORS @@ -0,0 +1,11 @@ +Current maintainer: + Conrad Weidenkeller + +Previous maintainer: + Eric "EJ" Johnson + Chmouel Boudjnah + +Contributors: + Paul Kehrer + Ben Arwin + Jordan Callicoat diff --git a/3rdparty/php-cloudfiles/COPYING b/3rdparty/php-cloudfiles/COPYING new file mode 100644 index 00000000000..0e10239d001 --- /dev/null +++ b/3rdparty/php-cloudfiles/COPYING @@ -0,0 +1,27 @@ +Unless otherwise noted, all files are released under the MIT license, +exceptions contain licensing information in them. + + Copyright (C) 2008 Rackspace US, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Except as contained in this notice, the name of Rackspace US, Inc. shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from Rackspace US, Inc. + diff --git a/3rdparty/php-cloudfiles/Changelog b/3rdparty/php-cloudfiles/Changelog new file mode 100644 index 00000000000..df9303c3e5b --- /dev/null +++ b/3rdparty/php-cloudfiles/Changelog @@ -0,0 +1,93 @@ +1.7.10 Conrad Weidenkeller + * Added Streaming URI Functionality + +1.7.9 Conrad Weidenkeller + * Added Manifest file support for Large Objects + +1.7.8 Conrad Weidenkeller + * Added CDN SSL URI Stuff + +1.7.7 Conrad Weidenkeller + * Added CDN Purge Functionality + +1.7.6 - Chmouel Boudjnah + * Add Cloud UK Support (conrad.weidenkeller). + +1.7.5 - Conrad Weidenkeller + * Added the ability to list only currently enabled CDN containers + * Added curl timeout to CF_Http + * Fixed some logic errors in some if statements. + +1.7.4 - Conrad Weidenkeller + * Added Manual SSL support for MacOSX users + +1.7.3 - Conrad Weidenkeller + * Fixed a Small Bug where some users were seeing response bodies for PUTs + +1.7.1 - Conrad Weidenkeller + * Added Support for Auth Token Caching. + +1.7.0 - Chmouel Boudjnah + * Adjust api auth to rackspacecloud not mosso (mshuler). + +1.6.2 - Chmouel Boudjnah + * Add a close method to close all the current connection. + * Fix when container_name is named 0. + +1.6.1 - Chmouel Boudjnah + * Fix setting etag on objects. + * Fix throwing proper exception when an invalid etag has been set. + * Fix throwing proper exception when no content type has been set. + +1.6.0 - Chmouel Boudjnah + * Add CDN ACL restriction by referrer feature. + * Add CDN ACL restriction by User Agent feature. + * Add documentation for log_retention method. + * Return True if log_retention as succeeded. + * Invalid the PHP stats cache before getting filesize. + +1.5.1 - Chmouel Boudjnah - 20091020 + * If the environement variable RACKSPACE_SERVICENET is defined then force to + connect via rakcspace servicenet. + +1.5.0 - Chmouel Boudjnah - 20091015 + * Add the option servicenet to connection to use Rackspace service net + instead of public network. + +1.4.0 - Chmouel Boudjnah - 20090808 + + * Add the ability to store the container log. + +1.3.2 - Chmouel Boudjnah - 20090606 + + * Change the Unit Tests to phpunit. + * Automatically set the updated CA bundle when on the windows OS. + * More simplification of the mimetype detection and support for PHP 5.3. + * Fix documentation information about the ttl for cached object. + * Use the hash library to compute MD5 for streams instead of storing the + stream in memory. + * Fix CF_Connection::get_containers to display the container name properly. + +1.3.1 - - 20090325 + + * Simplify use of FileInfo, remove packaged MIME/Magic file + * Throw Exception if no Content-Type is set + * Fix bug with tracking bytes transferred + * Support/tested on Windows XP (PHP v5.2.9) + +1.3.0 - - 20090311 + + * Support for list operations in JSON/XML + * Added support for FileInfo automatic Content-Type/MIME detection + * Workaround for cURL's old CA bundle with CF_Connection->ssl_use_cabundle() + * Supports limit/marker on Account and Container lists + * Support "pathname" traversal on Container lists + * Helper function on Container to create directory marker Objects + * Support for chunked transfer on PUT requests + +1.2.3 - - 20081210 + + * Improved in-line comments and generated HTML docs + * Callbacks for read/write progress on CF_Connection class + * Fixed minor bugs + * Started this Changelog diff --git a/3rdparty/php-cloudfiles/README b/3rdparty/php-cloudfiles/README new file mode 100644 index 00000000000..4bcbeade1a4 --- /dev/null +++ b/3rdparty/php-cloudfiles/README @@ -0,0 +1,73 @@ +;; PHP Cloud Files API +;; ======================================================================== +;; This package contains the PHP API for the Cloud Files storage system. +;; +;; Please see http://www.rackspacecloud.com/ for more information regarding the +;; Cloud Files storage system. +;; +;; Install +;; ------------------------------------------------------------------------ +;; Extract this archive and make sure the source code files are in your +;; PHP "include path". To use the API in your source code, just make +;; sure to include/require the "cloudfiles.php" script. +;; +;; Requirements +;; ------------------------------------------------------------------------ +;; [mandatory] PHP version 5.x (developed against 5.2.0) +;; [mandatory] PHP's cURL module +;; [mandatory] PHP enabled with mbstring (multi-byte string) support +;; [suggested] PEAR FileInfo module (for Content-Type detection) +;; +;; Examples +;; ------------------------------------------------------------------------ +;; For sample code, please see the tests and API docs. +;; +;; Docs +;; ------------------------------------------------------------------------ +;; The included documentation was generated directly from the source +;; code files using the PHPDocumentor tool. +;; +;; This README file is actually the PHPDocumentor INI configuration file. +;; The following packages were installed via PEAR to generate the HTML +;; API documentation. +;; +;; * PEAR 1.4.11 (stable) +;; * PhpDocumentor 1.4.2 (stable) +;; * XML_Beautifier 1.2.0 (stable) +;; * XML_Parser 1.3.1 (stable) +;; * XML_Util 1.2.0 (stable) +;; +;; To re-generate the API docs, make sure the above software is +;; available and run: +;; rm -rf docs && phpdoc -c phpdoc.ini +;; +;; Tests +;; ------------------------------------------------------------------------ +;; The tests are based on phpunit and are run with PHPUnit 3.3.17 +;; please follow the instructions on : +;; +;; http://www.phpunit.de/manual/current/en/installation.html +;; +;; to install PHPUnit. When installed just run the command phpunit on +;; the top of the directory and it will launch the tests. +;; +;; The tests/Comprehensive.php is not enabled by default since +;; generating big files. If you want to run it you need to go in the +;; tests directory and run with phpunit Comprehensive.php +;; +;; ======================================================================== +;; The lines below here are the configuration settings for re-generating +;; the PHP API documentation. +;; +[Parse Data] +title = php-cloudfiles +hidden = false +parseprivate = off +javadocdesc = off +defaultpackagename = php-cloudfiles +defaultcategoryname = php-cloudfiles +target = docs +directory = . +ignore = share/,examples/,tests/,.git/,.gitignore,*.ini,*.swp +output=HTML:Smarty:PHP +readmeinstallchangelog = README,COPYING,AUTHORS,Changelog diff --git a/3rdparty/php-cloudfiles/cloudfiles.php b/3rdparty/php-cloudfiles/cloudfiles.php new file mode 100644 index 00000000000..5f7e2100a99 --- /dev/null +++ b/3rdparty/php-cloudfiles/cloudfiles.php @@ -0,0 +1,2599 @@ + + * # Authenticate to Cloud Files. The default is to automatically try + * # to re-authenticate if an authentication token expires. + * # + * # NOTE: Some versions of cURL include an outdated certificate authority (CA) + * # file. This API ships with a newer version obtained directly from + * # cURL's web site (http://curl.haxx.se). To use the newer CA bundle, + * # call the CF_Authentication instance's 'ssl_use_cabundle()' method. + * # + * $auth = new CF_Authentication($username, $api_key); + * # $auth->ssl_use_cabundle(); # bypass cURL's old CA bundle + * $auth->authenticate(); + * + * # Establish a connection to the storage system + * # + * # NOTE: Some versions of cURL include an outdated certificate authority (CA) + * # file. This API ships with a newer version obtained directly from + * # cURL's web site (http://curl.haxx.se). To use the newer CA bundle, + * # call the CF_Connection instance's 'ssl_use_cabundle()' method. + * # + * $conn = new CF_Connection($auth); + * # $conn->ssl_use_cabundle(); # bypass cURL's old CA bundle + * + * # Create a remote Container and storage Object + * # + * $images = $conn->create_container("photos"); + * $bday = $images->create_object("first_birthday.jpg"); + * + * # Upload content from a local file by streaming it. Note that we use + * # a "float" for the file size to overcome PHP's 32-bit integer limit for + * # very large files. + * # + * $fname = "/home/user/photos/birthdays/birthday1.jpg"; # filename to upload + * $size = (float) sprintf("%u", filesize($fname)); + * $fp = open($fname, "r"); + * $bday->write($fp, $size); + * + * # Or... use a convenience function instead + * # + * $bday->load_from_filename("/home/user/photos/birthdays/birthday1.jpg"); + * + * # Now, publish the "photos" container to serve the images by CDN. + * # Use the "$uri" value to put in your web pages or send the link in an + * # email message, etc. + * # + * $uri = $images->make_public(); + * + * # Or... print out the Object's public URI + * # + * print $bday->public_uri(); + * + * + * See the included tests directory for additional sample code. + * + * Requres PHP 5.x (for Exceptions and OO syntax) and PHP's cURL module. + * + * It uses the supporting "cloudfiles_http.php" module for HTTP(s) support and + * allows for connection re-use and streaming of content into/out of Cloud Files + * via PHP's cURL module. + * + * See COPYING for license information. + * + * @author Eric "EJ" Johnson + * @copyright Copyright (c) 2008, Rackspace US, Inc. + * @package php-cloudfiles + */ + +/** + */ +require_once("cloudfiles_exceptions.php"); +require("cloudfiles_http.php"); +define("DEFAULT_CF_API_VERSION", 1); +define("MAX_CONTAINER_NAME_LEN", 256); +define("MAX_OBJECT_NAME_LEN", 1024); +define("MAX_OBJECT_SIZE", 5*1024*1024*1024+1); +define("US_AUTHURL", "https://auth.api.rackspacecloud.com"); +define("UK_AUTHURL", "https://lon.auth.api.rackspacecloud.com"); +/** + * Class for handling Cloud Files Authentication, call it's {@link authenticate()} + * method to obtain authorized service urls and an authentication token. + * + * Example: + * + * # Create the authentication instance + * # + * $auth = new CF_Authentication("username", "api_key"); + * + * # NOTE: For UK Customers please specify your AuthURL Manually + * # There is a Predfined constant to use EX: + * # + * # $auth = new CF_Authentication("username, "api_key", NULL, UK_AUTHURL); + * # Using the UK_AUTHURL keyword will force the api to use the UK AuthUrl. + * # rather then the US one. The NULL Is passed for legacy purposes and must + * # be passed to function correctly. + * + * # NOTE: Some versions of cURL include an outdated certificate authority (CA) + * # file. This API ships with a newer version obtained directly from + * # cURL's web site (http://curl.haxx.se). To use the newer CA bundle, + * # call the CF_Authentication instance's 'ssl_use_cabundle()' method. + * # + * # $auth->ssl_use_cabundle(); # bypass cURL's old CA bundle + * + * # Perform authentication request + * # + * $auth->authenticate(); + * + * + * @package php-cloudfiles + */ +class CF_Authentication +{ + public $dbug; + public $username; + public $api_key; + public $auth_host; + public $account; + + /** + * Instance variables that are set after successful authentication + */ + public $storage_url; + public $cdnm_url; + public $auth_token; + + /** + * Class constructor (PHP 5 syntax) + * + * @param string $username Mosso username + * @param string $api_key Mosso API Access Key + * @param string $account Account name + * @param string $auth_host Authentication service URI + */ + function __construct($username=NULL, $api_key=NULL, $account=NULL, $auth_host=US_AUTHURL) + { + + $this->dbug = False; + $this->username = $username; + $this->api_key = $api_key; + $this->account_name = $account; + $this->auth_host = $auth_host; + + $this->storage_url = NULL; + $this->cdnm_url = NULL; + $this->auth_token = NULL; + + $this->cfs_http = new CF_Http(DEFAULT_CF_API_VERSION); + } + + /** + * Use the Certificate Authority bundle included with this API + * + * Most versions of PHP with cURL support include an outdated Certificate + * Authority (CA) bundle (the file that lists all valid certificate + * signing authorities). The SSL certificates used by the Cloud Files + * storage system are perfectly valid but have been created/signed by + * a CA not listed in these outdated cURL distributions. + * + * As a work-around, we've included an updated CA bundle obtained + * directly from cURL's web site (http://curl.haxx.se). You can direct + * the API to use this CA bundle by calling this method prior to making + * any remote calls. The best place to use this method is right after + * the CF_Authentication instance has been instantiated. + * + * You can specify your own CA bundle by passing in the full pathname + * to the bundle. You can use the included CA bundle by leaving the + * argument blank. + * + * @param string $path Specify path to CA bundle (default to included) + */ + function ssl_use_cabundle($path=NULL) + { + $this->cfs_http->ssl_use_cabundle($path); + } + + /** + * Attempt to validate Username/API Access Key + * + * Attempts to validate credentials with the authentication service. It + * either returns True or throws an Exception. Accepts a single + * (optional) argument for the storage system API version. + * + * Example: + * + * # Create the authentication instance + * # + * $auth = new CF_Authentication("username", "api_key"); + * + * # Perform authentication request + * # + * $auth->authenticate(); + * + * + * @param string $version API version for Auth service (optional) + * @return boolean True if successfully authenticated + * @throws AuthenticationException invalid credentials + * @throws InvalidResponseException invalid response + */ + function authenticate($version=DEFAULT_CF_API_VERSION) + { + list($status,$reason,$surl,$curl,$atoken) = + $this->cfs_http->authenticate($this->username, $this->api_key, + $this->account_name, $this->auth_host); + + if ($status == 401) { + throw new AuthenticationException("Invalid username or access key."); + } + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Unexpected response (".$status."): ".$reason); + } + + if (!($surl || $curl) || !$atoken) { + throw new InvalidResponseException( + "Expected headers missing from auth service."); + } + $this->storage_url = $surl; + $this->cdnm_url = $curl; + $this->auth_token = $atoken; + return True; + } + /** + * Use Cached Token and Storage URL's rather then grabbing from the Auth System + * + * Example: + * + * #Create an Auth instance + * $auth = new CF_Authentication(); + * #Pass Cached URL's and Token as Args + * $auth->load_cached_credentials("auth_token", "storage_url", "cdn_management_url"); + * + * + * @param string $auth_token A Cloud Files Auth Token (Required) + * @param string $storage_url The Cloud Files Storage URL (Required) + * @param string $cdnm_url CDN Management URL (Required) + * @return boolean True if successful + * @throws SyntaxException If any of the Required Arguments are missing + */ + function load_cached_credentials($auth_token, $storage_url, $cdnm_url) + { + if(!$storage_url || !$cdnm_url) + { + throw new SyntaxException("Missing Required Interface URL's!"); + return False; + } + if(!$auth_token) + { + throw new SyntaxException("Missing Auth Token!"); + return False; + } + + $this->storage_url = $storage_url; + $this->cdnm_url = $cdnm_url; + $this->auth_token = $auth_token; + return True; + } + /** + * Grab Cloud Files info to be Cached for later use with the load_cached_credentials method. + * + * Example: + * + * #Create an Auth instance + * $auth = new CF_Authentication("UserName","API_Key"); + * $auth->authenticate(); + * $array = $auth->export_credentials(); + * + * + * @return array of url's and an auth token. + */ + function export_credentials() + { + $arr = array(); + $arr['storage_url'] = $this->storage_url; + $arr['cdnm_url'] = $this->cdnm_url; + $arr['auth_token'] = $this->auth_token; + + return $arr; + } + + + /** + * Make sure the CF_Authentication instance has authenticated. + * + * Ensures that the instance variables necessary to communicate with + * Cloud Files have been set from a previous authenticate() call. + * + * @return boolean True if successfully authenticated + */ + function authenticated() + { + if (!($this->storage_url || $this->cdnm_url) || !$this->auth_token) { + return False; + } + return True; + } + + /** + * Toggle debugging - set cURL verbose flag + */ + function setDebug($bool) + { + $this->dbug = $bool; + $this->cfs_http->setDebug($bool); + } +} + +/** + * Class for establishing connections to the Cloud Files storage system. + * Connection instances are used to communicate with the storage system at + * the account level; listing and deleting Containers and returning Container + * instances. + * + * Example: + * + * # Create the authentication instance + * # + * $auth = new CF_Authentication("username", "api_key"); + * + * # Perform authentication request + * # + * $auth->authenticate(); + * + * # Create a connection to the storage/cdn system(s) and pass in the + * # validated CF_Authentication instance. + * # + * $conn = new CF_Connection($auth); + * + * # NOTE: Some versions of cURL include an outdated certificate authority (CA) + * # file. This API ships with a newer version obtained directly from + * # cURL's web site (http://curl.haxx.se). To use the newer CA bundle, + * # call the CF_Authentication instance's 'ssl_use_cabundle()' method. + * # + * # $conn->ssl_use_cabundle(); # bypass cURL's old CA bundle + * + * + * @package php-cloudfiles + */ +class CF_Connection +{ + public $dbug; + public $cfs_http; + public $cfs_auth; + + /** + * Pass in a previously authenticated CF_Authentication instance. + * + * Example: + * + * # Create the authentication instance + * # + * $auth = new CF_Authentication("username", "api_key"); + * + * # Perform authentication request + * # + * $auth->authenticate(); + * + * # Create a connection to the storage/cdn system(s) and pass in the + * # validated CF_Authentication instance. + * # + * $conn = new CF_Connection($auth); + * + * # If you are connecting via Rackspace servers and have access + * # to the servicenet network you can set the $servicenet to True + * # like this. + * + * $conn = new CF_Connection($auth, $servicenet=True); + * + * + * + * If the environement variable RACKSPACE_SERVICENET is defined it will + * force to connect via the servicenet. + * + * @param obj $cfs_auth previously authenticated CF_Authentication instance + * @param boolean $servicenet enable/disable access via Rackspace servicenet. + * @throws AuthenticationException not authenticated + */ + function __construct($cfs_auth, $servicenet=False) + { + if (isset($_ENV['RACKSPACE_SERVICENET'])) + $servicenet=True; + $this->cfs_http = new CF_Http(DEFAULT_CF_API_VERSION); + $this->cfs_auth = $cfs_auth; + if (!$this->cfs_auth->authenticated()) { + $e = "Need to pass in a previously authenticated "; + $e .= "CF_Authentication instance."; + throw new AuthenticationException($e); + } + $this->cfs_http->setCFAuth($this->cfs_auth, $servicenet=$servicenet); + $this->dbug = False; + } + + /** + * Toggle debugging of instance and back-end HTTP module + * + * @param boolean $bool enable/disable cURL debugging + */ + function setDebug($bool) + { + $this->dbug = (boolean) $bool; + $this->cfs_http->setDebug($this->dbug); + } + + /** + * Close a connection + * + * Example: + * + * + * $conn->close(); + * + * + * + * Will close all current cUrl active connections. + * + */ + public function close() + { + $this->cfs_http->close(); + } + + /** + * Cloud Files account information + * + * Return an array of two floats (since PHP only supports 32-bit integers); + * number of containers on the account and total bytes used for the account. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * list($quantity, $bytes) = $conn->get_info(); + * print "Number of containers: " . $quantity . "\n"; + * print "Bytes stored in container: " . $bytes . "\n"; + * + * + * @return array (number of containers, total bytes stored) + * @throws InvalidResponseException unexpected response + */ + function get_info() + { + list($status, $reason, $container_count, $total_bytes) = + $this->cfs_http->head_account(); + #if ($status == 401 && $this->_re_auth()) { + # return $this->get_info(); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return array($container_count, $total_bytes); + } + + /** + * Create a Container + * + * Given a Container name, return a Container instance, creating a new + * remote Container if it does not exit. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->create_container("my photos"); + * + * + * @param string $container_name container name + * @return CF_Container + * @throws SyntaxException invalid name + * @throws InvalidResponseException unexpected response + */ + function create_container($container_name=NULL) + { + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + if (!isset($container_name) or $container_name == "") + throw new SyntaxException("Container name not set."); + + if (strpos($container_name, "/") !== False) { + $r = "Container name '".$container_name; + $r .= "' cannot contain a '/' character."; + throw new SyntaxException($r); + } + if (strlen($container_name) > MAX_CONTAINER_NAME_LEN) { + throw new SyntaxException(sprintf( + "Container name exeeds %d bytes.", + MAX_CONTAINER_NAME_LEN)); + } + + $return_code = $this->cfs_http->create_container($container_name); + if (!$return_code) { + throw new InvalidResponseException("Invalid response (" + . $return_code. "): " . $this->cfs_http->get_error()); + } + #if ($status == 401 && $this->_re_auth()) { + # return $this->create_container($container_name); + #} + if ($return_code != 201 && $return_code != 202) { + throw new InvalidResponseException( + "Invalid response (".$return_code."): " + . $this->cfs_http->get_error()); + } + return new CF_Container($this->cfs_auth, $this->cfs_http, $container_name); + } + + /** + * Delete a Container + * + * Given either a Container instance or name, remove the remote Container. + * The Container must be empty prior to removing it. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $conn->delete_container("my photos"); + * + * + * @param string|obj $container container name or instance + * @return boolean True if successfully deleted + * @throws SyntaxException missing proper argument + * @throws InvalidResponseException invalid response + * @throws NonEmptyContainerException container not empty + * @throws NoSuchContainerException remote container does not exist + */ + function delete_container($container=NULL) + { + $container_name = NULL; + + if (is_object($container)) { + if (get_class($container) == "CF_Container") { + $container_name = $container->name; + } + } + if (is_string($container)) { + $container_name = $container; + } + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Must specify container object or name."); + + $return_code = $this->cfs_http->delete_container($container_name); + + if (!$return_code) { + throw new InvalidResponseException("Failed to obtain http response"); + } + #if ($status == 401 && $this->_re_auth()) { + # return $this->delete_container($container); + #} + if ($return_code == 409) { + throw new NonEmptyContainerException( + "Container must be empty prior to removing it."); + } + if ($return_code == 404) { + throw new NoSuchContainerException( + "Specified container did not exist to delete."); + } + if ($return_code != 204) { + throw new InvalidResponseException( + "Invalid response (".$return_code."): " + . $this->cfs_http->get_error()); + } + return True; + } + + /** + * Return a Container instance + * + * For the given name, return a Container instance if the remote Container + * exists, otherwise throw a Not Found exception. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * print "Number of Objects: " . $images->count . "\n"; + * print "Bytes stored in container: " . $images->bytes . "\n"; + * + * + * @param string $container_name name of the remote Container + * @return container CF_Container instance + * @throws NoSuchContainerException thrown if no remote Container + * @throws InvalidResponseException unexpected response + */ + function get_container($container_name=NULL) + { + list($status, $reason, $count, $bytes) = + $this->cfs_http->head_container($container_name); + #if ($status == 401 && $this->_re_auth()) { + # return $this->get_container($container_name); + #} + if ($status == 404) { + throw new NoSuchContainerException("Container not found."); + } + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response: ".$this->cfs_http->get_error()); + } + return new CF_Container($this->cfs_auth, $this->cfs_http, + $container_name, $count, $bytes); + } + + /** + * Return array of Container instances + * + * Return an array of CF_Container instances on the account. The instances + * will be fully populated with Container attributes (bytes stored and + * Object count) + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $clist = $conn->get_containers(); + * foreach ($clist as $cont) { + * print "Container name: " . $cont->name . "\n"; + * print "Number of Objects: " . $cont->count . "\n"; + * print "Bytes stored in container: " . $cont->bytes . "\n"; + * } + * + * + * @return array An array of CF_Container instances + * @throws InvalidResponseException unexpected response + */ + function get_containers($limit=0, $marker=NULL) + { + list($status, $reason, $container_info) = + $this->cfs_http->list_containers_info($limit, $marker); + #if ($status == 401 && $this->_re_auth()) { + # return $this->get_containers(); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response: ".$this->cfs_http->get_error()); + } + $containers = array(); + foreach ($container_info as $name => $info) { + $containers[] = new CF_Container($this->cfs_auth, $this->cfs_http, + $info['name'], $info["count"], $info["bytes"], False); + } + return $containers; + } + + /** + * Return list of remote Containers + * + * Return an array of strings containing the names of all remote Containers. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $container_list = $conn->list_containers(); + * print_r($container_list); + * Array + * ( + * [0] => "my photos", + * [1] => "my docs" + * ) + * + * + * @param integer $limit restrict results to $limit Containers + * @param string $marker return results greater than $marker + * @return array list of remote Containers + * @throws InvalidResponseException unexpected response + */ + function list_containers($limit=0, $marker=NULL) + { + list($status, $reason, $containers) = + $this->cfs_http->list_containers($limit, $marker); + #if ($status == 401 && $this->_re_auth()) { + # return $this->list_containers($limit, $marker); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return $containers; + } + + /** + * Return array of information about remote Containers + * + * Return a nested array structure of Container info. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * + * $container_info = $conn->list_containers_info(); + * print_r($container_info); + * Array + * ( + * ["my photos"] => + * Array + * ( + * ["bytes"] => 78, + * ["count"] => 2 + * ) + * ["docs"] => + * Array + * ( + * ["bytes"] => 37323, + * ["count"] => 12 + * ) + * ) + * + * + * @param integer $limit restrict results to $limit Containers + * @param string $marker return results greater than $marker + * @return array nested array structure of Container info + * @throws InvalidResponseException unexpected response + */ + function list_containers_info($limit=0, $marker=NULL) + { + list($status, $reason, $container_info) = + $this->cfs_http->list_containers_info($limit, $marker); + #if ($status == 401 && $this->_re_auth()) { + # return $this->list_containers_info($limit, $marker); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return $container_info; + } + + /** + * Return list of Containers that have been published to the CDN. + * + * Return an array of strings containing the names of published Containers. + * Note that this function returns the list of any Container that has + * ever been CDN-enabled regardless of it's existence in the storage + * system. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_containers = $conn->list_public_containers(); + * print_r($public_containers); + * Array + * ( + * [0] => "images", + * [1] => "css", + * [2] => "javascript" + * ) + * + * + * @param bool $enabled_only Will list all containers ever CDN enabled if * set to false or only currently enabled CDN containers if set to true. * Defaults to false. + * @return array list of published Container names + * @throws InvalidResponseException unexpected response + */ + function list_public_containers($enabled_only=False) + { + list($status, $reason, $containers) = + $this->cfs_http->list_cdn_containers($enabled_only); + #if ($status == 401 && $this->_re_auth()) { + # return $this->list_public_containers(); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return $containers; + } + + /** + * Set a user-supplied callback function to report download progress + * + * The callback function is used to report incremental progress of a data + * download functions (e.g. $container->list_objects(), $obj->read(), etc). + * The specified function will be periodically called with the number of + * bytes transferred until the entire download is complete. This callback + * function can be useful for implementing "progress bars" for large + * downloads. + * + * The specified callback function should take a single integer parameter. + * + * + * function read_callback($bytes_transferred) { + * print ">> downloaded " . $bytes_transferred . " bytes.\n"; + * # ... do other things ... + * return; + * } + * + * $conn = new CF_Connection($auth_obj); + * $conn->set_read_progress_function("read_callback"); + * print_r($conn->list_containers()); + * + * # output would look like this: + * # + * >> downloaded 10 bytes. + * >> downloaded 11 bytes. + * Array + * ( + * [0] => fuzzy.txt + * [1] => space name + * ) + * + * + * @param string $func_name the name of the user callback function + */ + function set_read_progress_function($func_name) + { + $this->cfs_http->setReadProgressFunc($func_name); + } + + /** + * Set a user-supplied callback function to report upload progress + * + * The callback function is used to report incremental progress of a data + * upload functions (e.g. $obj->write() call). The specified function will + * be periodically called with the number of bytes transferred until the + * entire upload is complete. This callback function can be useful + * for implementing "progress bars" for large uploads/downloads. + * + * The specified callback function should take a single integer parameter. + * + * + * function write_callback($bytes_transferred) { + * print ">> uploaded " . $bytes_transferred . " bytes.\n"; + * # ... do other things ... + * return; + * } + * + * $conn = new CF_Connection($auth_obj); + * $conn->set_write_progress_function("write_callback"); + * $container = $conn->create_container("stuff"); + * $obj = $container->create_object("foo"); + * $obj->write("The callback function will be called during upload."); + * + * # output would look like this: + * # >> uploaded 51 bytes. + * # + * + * + * @param string $func_name the name of the user callback function + */ + function set_write_progress_function($func_name) + { + $this->cfs_http->setWriteProgressFunc($func_name); + } + + /** + * Use the Certificate Authority bundle included with this API + * + * Most versions of PHP with cURL support include an outdated Certificate + * Authority (CA) bundle (the file that lists all valid certificate + * signing authorities). The SSL certificates used by the Cloud Files + * storage system are perfectly valid but have been created/signed by + * a CA not listed in these outdated cURL distributions. + * + * As a work-around, we've included an updated CA bundle obtained + * directly from cURL's web site (http://curl.haxx.se). You can direct + * the API to use this CA bundle by calling this method prior to making + * any remote calls. The best place to use this method is right after + * the CF_Authentication instance has been instantiated. + * + * You can specify your own CA bundle by passing in the full pathname + * to the bundle. You can use the included CA bundle by leaving the + * argument blank. + * + * @param string $path Specify path to CA bundle (default to included) + */ + function ssl_use_cabundle($path=NULL) + { + $this->cfs_http->ssl_use_cabundle($path); + } + + #private function _re_auth() + #{ + # $new_auth = new CF_Authentication( + # $this->cfs_auth->username, + # $this->cfs_auth->api_key, + # $this->cfs_auth->auth_host, + # $this->cfs_auth->account); + # $new_auth->authenticate(); + # $this->cfs_auth = $new_auth; + # $this->cfs_http->setCFAuth($this->cfs_auth); + # return True; + #} +} + +/** + * Container operations + * + * Containers are storage compartments where you put your data (objects). + * A container is similar to a directory or folder on a conventional filesystem + * with the exception that they exist in a flat namespace, you can not create + * containers inside of containers. + * + * You also have the option of marking a Container as "public" so that the + * Objects stored in the Container are publicly available via the CDN. + * + * @package php-cloudfiles + */ +class CF_Container +{ + public $cfs_auth; + public $cfs_http; + public $name; + public $object_count; + public $bytes_used; + + public $cdn_enabled; + public $cdn_streaming_uri; + public $cdn_ssl_uri; + public $cdn_uri; + public $cdn_ttl; + public $cdn_log_retention; + public $cdn_acl_user_agent; + public $cdn_acl_referrer; + + /** + * Class constructor + * + * Constructor for Container + * + * @param obj $cfs_auth CF_Authentication instance + * @param obj $cfs_http HTTP connection manager + * @param string $name name of Container + * @param int $count number of Objects stored in this Container + * @param int $bytes number of bytes stored in this Container + * @throws SyntaxException invalid Container name + */ + function __construct(&$cfs_auth, &$cfs_http, $name, $count=0, + $bytes=0, $docdn=True) + { + if (strlen($name) > MAX_CONTAINER_NAME_LEN) { + throw new SyntaxException("Container name exceeds " + . "maximum allowed length."); + } + if (strpos($name, "/") !== False) { + throw new SyntaxException( + "Container names cannot contain a '/' character."); + } + $this->cfs_auth = $cfs_auth; + $this->cfs_http = $cfs_http; + $this->name = $name; + $this->object_count = $count; + $this->bytes_used = $bytes; + $this->cdn_enabled = NULL; + $this->cdn_uri = NULL; + $this->cdn_ssl_uri = NULL; + $this->cdn_streaming_uri = NULL; + $this->cdn_ttl = NULL; + $this->cdn_log_retention = NULL; + $this->cdn_acl_user_agent = NULL; + $this->cdn_acl_referrer = NULL; + if ($this->cfs_http->getCDNMUrl() != NULL && $docdn) { + $this->_cdn_initialize(); + } + } + + /** + * String representation of Container + * + * Pretty print the Container instance. + * + * @return string Container details + */ + function __toString() + { + $me = sprintf("name: %s, count: %.0f, bytes: %.0f", + $this->name, $this->object_count, $this->bytes_used); + if ($this->cfs_http->getCDNMUrl() != NULL) { + $me .= sprintf(", cdn: %s, cdn uri: %s, cdn ttl: %.0f, logs retention: %s", + $this->is_public() ? "Yes" : "No", + $this->cdn_uri, $this->cdn_ttl, + $this->cdn_log_retention ? "Yes" : "No" + ); + + if ($this->cdn_acl_user_agent != NULL) { + $me .= ", cdn acl user agent: " . $this->cdn_acl_user_agent; + } + + if ($this->cdn_acl_referrer != NULL) { + $me .= ", cdn acl referrer: " . $this->cdn_acl_referrer; + } + + + } + return $me; + } + + /** + * Enable Container content to be served via CDN or modify CDN attributes + * + * Either enable this Container's content to be served via CDN or + * adjust its CDN attributes. This Container will always return the + * same CDN-enabled URI each time it is toggled public/private/public. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->create_container("public"); + * + * # CDN-enable the container and set it's TTL for a month + * # + * $public_container->make_public(86400/2); # 12 hours (86400 seconds/day) + * + * + * @param int $ttl the time in seconds content will be cached in the CDN + * @returns string the CDN enabled Container's URI + * @throws CDNNotEnabledException CDN functionality not returned during auth + * @throws AuthenticationException if auth token is not valid/expired + * @throws InvalidResponseException unexpected response + */ + function make_public($ttl=86400) + { + if ($this->cfs_http->getCDNMUrl() == NULL) { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + if ($this->cdn_uri != NULL) { + # previously published, assume we're setting new attributes + list($status, $reason, $cdn_uri, $cdn_ssl_uri) = + $this->cfs_http->update_cdn_container($this->name,$ttl, + $this->cdn_log_retention, + $this->cdn_acl_user_agent, + $this->cdn_acl_referrer); + #if ($status == 401 && $this->_re_auth()) { + # return $this->make_public($ttl); + #} + if ($status == 404) { + # this instance _thinks_ the container was published, but the + # cdn management system thinks otherwise - try again with a PUT + list($status, $reason, $cdn_uri, $cdn_ssl_uri) = + $this->cfs_http->add_cdn_container($this->name,$ttl); + + } + } else { + # publish it for first time + list($status, $reason, $cdn_uri, $cdn_ssl_uri) = + $this->cfs_http->add_cdn_container($this->name,$ttl); + } + #if ($status == 401 && $this->_re_auth()) { + # return $this->make_public($ttl); + #} + if (!in_array($status, array(201,202))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_enabled = True; + $this->cdn_ttl = $ttl; + $this->cdn_ssl_uri = $cdn_ssl_uri; + $this->cdn_uri = $cdn_uri; + $this->cdn_log_retention = False; + $this->cdn_acl_user_agent = ""; + $this->cdn_acl_referrer = ""; + return $this->cdn_uri; + } + /** + * Purge Containers objects from CDN Cache. + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * $container = $conn->get_container("cdn_enabled"); + * $container->purge_from_cdn("user@domain.com"); + * # or + * $container->purge_from_cdn(); + * # or + * $container->purge_from_cdn("user1@domain.com,user2@domain.com"); + * @returns boolean True if successful + * @throws CDNNotEnabledException if CDN Is not enabled on this connection + * @throws InvalidResponseException if the response expected is not returned + */ + function purge_from_cdn($email=null) + { + if (!$this->cfs_http->getCDNMUrl()) + { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + $status = $this->cfs_http->purge_from_cdn($this->name, $email); + if ($status < 199 or $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return True; + } + /** + * Enable ACL restriction by User Agent for this container. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # Enable ACL by Referrer + * $public_container->acl_referrer("Mozilla"); + * + * + * @returns boolean True if successful + * @throws CDNNotEnabledException CDN functionality not returned during auth + * @throws AuthenticationException if auth token is not valid/expired + * @throws InvalidResponseException unexpected response + */ + function acl_user_agent($cdn_acl_user_agent="") { + if ($this->cfs_http->getCDNMUrl() == NULL) { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + list($status,$reason) = + $this->cfs_http->update_cdn_container($this->name, + $this->cdn_ttl, + $this->cdn_log_retention, + $cdn_acl_user_agent, + $this->cdn_acl_referrer + ); + if (!in_array($status, array(202,404))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_acl_user_agent = $cdn_acl_user_agent; + return True; + } + + /** + * Enable ACL restriction by referer for this container. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # Enable Referrer + * $public_container->acl_referrer("http://www.example.com/gallery.php"); + * + * + * @returns boolean True if successful + * @throws CDNNotEnabledException CDN functionality not returned during auth + * @throws AuthenticationException if auth token is not valid/expired + * @throws InvalidResponseException unexpected response + */ + function acl_referrer($cdn_acl_referrer="") { + if ($this->cfs_http->getCDNMUrl() == NULL) { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + list($status,$reason) = + $this->cfs_http->update_cdn_container($this->name, + $this->cdn_ttl, + $this->cdn_log_retention, + $this->cdn_acl_user_agent, + $cdn_acl_referrer + ); + if (!in_array($status, array(202,404))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_acl_referrer = $cdn_acl_referrer; + return True; + } + + /** + * Enable log retention for this CDN container. + * + * Enable CDN log retention on the container. If enabled logs will + * be periodically (at unpredictable intervals) compressed and + * uploaded to a ".CDN_ACCESS_LOGS" container in the form of + * "container_name.YYYYMMDDHH-XXXX.gz". Requires CDN be enabled on + * the account. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # Enable logs retention. + * $public_container->log_retention(True); + * + * + * @returns boolean True if successful + * @throws CDNNotEnabledException CDN functionality not returned during auth + * @throws AuthenticationException if auth token is not valid/expired + * @throws InvalidResponseException unexpected response + */ + function log_retention($cdn_log_retention=False) { + if ($this->cfs_http->getCDNMUrl() == NULL) { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + list($status,$reason) = + $this->cfs_http->update_cdn_container($this->name, + $this->cdn_ttl, + $cdn_log_retention, + $this->cdn_acl_user_agent, + $this->cdn_acl_referrer + ); + if (!in_array($status, array(202,404))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_log_retention = $cdn_log_retention; + return True; + } + + /** + * Disable the CDN sharing for this container + * + * Use this method to disallow distribution into the CDN of this Container's + * content. + * + * NOTE: Any content already cached in the CDN will continue to be served + * from its cache until the TTL expiration transpires. The default + * TTL is typically one day, so "privatizing" the Container will take + * up to 24 hours before the content is purged from the CDN cache. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # Disable CDN accessability + * # ... still cached up to a month based on previous example + * # + * $public_container->make_private(); + * + * + * @returns boolean True if successful + * @throws CDNNotEnabledException CDN functionality not returned during auth + * @throws AuthenticationException if auth token is not valid/expired + * @throws InvalidResponseException unexpected response + */ + function make_private() + { + if ($this->cfs_http->getCDNMUrl() == NULL) { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + list($status,$reason) = $this->cfs_http->remove_cdn_container($this->name); + #if ($status == 401 && $this->_re_auth()) { + # return $this->make_private(); + #} + if (!in_array($status, array(202,404))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_enabled = False; + $this->cdn_ttl = NULL; + $this->cdn_uri = NULL; + $this->cdn_ssl_uri = NULL; + $this->cdn_streaming_uri - NULL; + $this->cdn_log_retention = NULL; + $this->cdn_acl_user_agent = NULL; + $this->cdn_acl_referrer = NULL; + return True; + } + + /** + * Check if this Container is being publicly served via CDN + * + * Use this method to determine if the Container's content is currently + * available through the CDN. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # Display CDN accessability + * # + * $public_container->is_public() ? print "Yes" : print "No"; + * + * + * @returns boolean True if enabled, False otherwise + */ + function is_public() + { + return $this->cdn_enabled == True ? True : False; + } + + /** + * Create a new remote storage Object + * + * Return a new Object instance. If the remote storage Object exists, + * the instance's attributes are populated. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # This creates a local instance of a storage object but only creates + * # it in the storage system when the object's write() method is called. + * # + * $pic = $public_container->create_object("baby.jpg"); + * + * + * @param string $obj_name name of storage Object + * @return obj CF_Object instance + */ + function create_object($obj_name=NULL) + { + return new CF_Object($this, $obj_name); + } + + /** + * Return an Object instance for the remote storage Object + * + * Given a name, return a Object instance representing the + * remote storage object. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $public_container = $conn->get_container("public"); + * + * # This call only fetches header information and not the content of + * # the storage object. Use the Object's read() or stream() methods + * # to obtain the object's data. + * # + * $pic = $public_container->get_object("baby.jpg"); + * + * + * @param string $obj_name name of storage Object + * @return obj CF_Object instance + */ + function get_object($obj_name=NULL) + { + return new CF_Object($this, $obj_name, True); + } + + /** + * Return a list of Objects + * + * Return an array of strings listing the Object names in this Container. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $images = $conn->get_container("my photos"); + * + * # Grab the list of all storage objects + * # + * $all_objects = $images->list_objects(); + * + * # Grab subsets of all storage objects + * # + * $first_ten = $images->list_objects(10); + * + * # Note the use of the previous result's last object name being + * # used as the 'marker' parameter to fetch the next 10 objects + * # + * $next_ten = $images->list_objects(10, $first_ten[count($first_ten)-1]); + * + * # Grab images starting with "birthday_party" and default limit/marker + * # to match all photos with that prefix + * # + * $prefixed = $images->list_objects(0, NULL, "birthday"); + * + * # Assuming you have created the appropriate directory marker Objects, + * # you can traverse your pseudo-hierarchical containers + * # with the "path" argument. + * # + * $animals = $images->list_objects(0,NULL,NULL,"pictures/animals"); + * $dogs = $images->list_objects(0,NULL,NULL,"pictures/animals/dogs"); + * + * + * @param int $limit optional only return $limit names + * @param int $marker optional subset of names starting at $marker + * @param string $prefix optional Objects whose names begin with $prefix + * @param string $path optional only return results under "pathname" + * @return array array of strings + * @throws InvalidResponseException unexpected response + */ + function list_objects($limit=0, $marker=NULL, $prefix=NULL, $path=NULL) + { + list($status, $reason, $obj_list) = + $this->cfs_http->list_objects($this->name, $limit, + $marker, $prefix, $path); + #if ($status == 401 && $this->_re_auth()) { + # return $this->list_objects($limit, $marker, $prefix, $path); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return $obj_list; + } + + /** + * Return an array of Objects + * + * Return an array of Object instances in this Container. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $images = $conn->get_container("my photos"); + * + * # Grab the list of all storage objects + * # + * $all_objects = $images->get_objects(); + * + * # Grab subsets of all storage objects + * # + * $first_ten = $images->get_objects(10); + * + * # Note the use of the previous result's last object name being + * # used as the 'marker' parameter to fetch the next 10 objects + * # + * $next_ten = $images->list_objects(10, $first_ten[count($first_ten)-1]); + * + * # Grab images starting with "birthday_party" and default limit/marker + * # to match all photos with that prefix + * # + * $prefixed = $images->get_objects(0, NULL, "birthday"); + * + * # Assuming you have created the appropriate directory marker Objects, + * # you can traverse your pseudo-hierarchical containers + * # with the "path" argument. + * # + * $animals = $images->get_objects(0,NULL,NULL,"pictures/animals"); + * $dogs = $images->get_objects(0,NULL,NULL,"pictures/animals/dogs"); + * + * + * @param int $limit optional only return $limit names + * @param int $marker optional subset of names starting at $marker + * @param string $prefix optional Objects whose names begin with $prefix + * @param string $path optional only return results under "pathname" + * @return array array of strings + * @throws InvalidResponseException unexpected response + */ + function get_objects($limit=0, $marker=NULL, $prefix=NULL, $path=NULL) + { + list($status, $reason, $obj_array) = + $this->cfs_http->get_objects($this->name, $limit, + $marker, $prefix, $path); + #if ($status == 401 && $this->_re_auth()) { + # return $this->get_objects($limit, $marker, $prefix, $path); + #} + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $objects = array(); + foreach ($obj_array as $obj) { + $tmp = new CF_Object($this, $obj["name"], False, False); + $tmp->content_type = $obj["content_type"]; + $tmp->content_length = (float) $obj["bytes"]; + $tmp->set_etag($obj["hash"]); + $tmp->last_modified = $obj["last_modified"]; + $objects[] = $tmp; + } + return $objects; + } + + /** + * Copy a remote storage Object to a target Container + * + * Given an Object instance or name and a target Container instance or name, copy copies the remote Object + * and all associated metadata. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * + * # Copy specific object + * # + * $images->copy_object_to("disco_dancing.jpg","container_target"); + * + * + * @param obj $obj name or instance of Object to copy + * @param obj $container_target name or instance of target Container + * @param string $dest_obj_name name of target object (optional - uses source name if omitted) + * @param array $metadata metadata array for new object (optional) + * @param array $headers header fields array for the new object (optional) + * @return boolean true if successfully copied + * @throws SyntaxException invalid Object/Container name + * @throws NoSuchObjectException remote Object does not exist + * @throws InvalidResponseException unexpected response + */ + function copy_object_to($obj,$container_target,$dest_obj_name=NULL,$metadata=NULL,$headers=NULL) + { + $obj_name = NULL; + if (is_object($obj)) { + if (get_class($obj) == "CF_Object") { + $obj_name = $obj->name; + } + } + if (is_string($obj)) { + $obj_name = $obj; + } + if (!$obj_name) { + throw new SyntaxException("Object name not set."); + } + + if ($dest_obj_name === NULL) { + $dest_obj_name = $obj_name; + } + + $container_name_target = NULL; + if (is_object($container_target)) { + if (get_class($container_target) == "CF_Container") { + $container_name_target = $container_target->name; + } + } + if (is_string($container_target)) { + $container_name_target = $container_target; + } + if (!$container_name_target) { + throw new SyntaxException("Container name target not set."); + } + + $status = $this->cfs_http->copy_object($obj_name,$dest_obj_name,$this->name,$container_name_target,$metadata,$headers); + if ($status == 404) { + $m = "Specified object '".$this->name."/".$obj_name; + $m.= "' did not exist as source to copy from or '".$container_name_target."' did not exist as target to copy to."; + throw new NoSuchObjectException($m); + } + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return true; + } + + /** + * Copy a remote storage Object from a source Container + * + * Given an Object instance or name and a source Container instance or name, copy copies the remote Object + * and all associated metadata. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * + * # Copy specific object + * # + * $images->copy_object_from("disco_dancing.jpg","container_source"); + * + * + * @param obj $obj name or instance of Object to copy + * @param obj $container_source name or instance of source Container + * @param string $dest_obj_name name of target object (optional - uses source name if omitted) + * @param array $metadata metadata array for new object (optional) + * @param array $headers header fields array for the new object (optional) + * @return boolean true if successfully copied + * @throws SyntaxException invalid Object/Container name + * @throws NoSuchObjectException remote Object does not exist + * @throws InvalidResponseException unexpected response + */ + function copy_object_from($obj,$container_source,$dest_obj_name=NULL,$metadata=NULL,$headers=NULL) + { + $obj_name = NULL; + if (is_object($obj)) { + if (get_class($obj) == "CF_Object") { + $obj_name = $obj->name; + } + } + if (is_string($obj)) { + $obj_name = $obj; + } + if (!$obj_name) { + throw new SyntaxException("Object name not set."); + } + + if ($dest_obj_name === NULL) { + $dest_obj_name = $obj_name; + } + + $container_name_source = NULL; + if (is_object($container_source)) { + if (get_class($container_source) == "CF_Container") { + $container_name_source = $container_source->name; + } + } + if (is_string($container_source)) { + $container_name_source = $container_source; + } + if (!$container_name_source) { + throw new SyntaxException("Container name source not set."); + } + + $status = $this->cfs_http->copy_object($obj_name,$dest_obj_name,$container_name_source,$this->name,$metadata,$headers); + if ($status == 404) { + $m = "Specified object '".$container_name_source."/".$obj_name; + $m.= "' did not exist as source to copy from or '".$this->name."/".$obj_name."' did not exist as target to copy to."; + throw new NoSuchObjectException($m); + } + if ($status < 200 || $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + + return true; + } + + /** + * Move a remote storage Object to a target Container + * + * Given an Object instance or name and a target Container instance or name, move copies the remote Object + * and all associated metadata and deletes the source Object afterwards + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * + * # Move specific object + * # + * $images->move_object_to("disco_dancing.jpg","container_target"); + * + * + * @param obj $obj name or instance of Object to move + * @param obj $container_target name or instance of target Container + * @param string $dest_obj_name name of target object (optional - uses source name if omitted) + * @param array $metadata metadata array for new object (optional) + * @param array $headers header fields array for the new object (optional) + * @return boolean true if successfully moved + * @throws SyntaxException invalid Object/Container name + * @throws NoSuchObjectException remote Object does not exist + * @throws InvalidResponseException unexpected response + */ + function move_object_to($obj,$container_target,$dest_obj_name=NULL,$metadata=NULL,$headers=NULL) + { + $retVal = false; + + if(self::copy_object_to($obj,$container_target,$dest_obj_name,$metadata,$headers)) { + $retVal = self::delete_object($obj,$this->name); + } + + return $retVal; + } + + /** + * Move a remote storage Object from a source Container + * + * Given an Object instance or name and a source Container instance or name, move copies the remote Object + * and all associated metadata and deletes the source Object afterwards + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * + * # Move specific object + * # + * $images->move_object_from("disco_dancing.jpg","container_target"); + * + * + * @param obj $obj name or instance of Object to move + * @param obj $container_source name or instance of target Container + * @param string $dest_obj_name name of target object (optional - uses source name if omitted) + * @param array $metadata metadata array for new object (optional) + * @param array $headers header fields array for the new object (optional) + * @return boolean true if successfully moved + * @throws SyntaxException invalid Object/Container name + * @throws NoSuchObjectException remote Object does not exist + * @throws InvalidResponseException unexpected response + */ + function move_object_from($obj,$container_source,$dest_obj_name=NULL,$metadata=NULL,$headers=NULL) + { + $retVal = false; + + if(self::copy_object_from($obj,$container_source,$dest_obj_name,$metadata,$headers)) { + $retVal = self::delete_object($obj,$container_source); + } + + return $retVal; + } + + /** + * Delete a remote storage Object + * + * Given an Object instance or name, permanently remove the remote Object + * and all associated metadata. + * + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * + * $images = $conn->get_container("my photos"); + * + * # Delete specific object + * # + * $images->delete_object("disco_dancing.jpg"); + * + * + * @param obj $obj name or instance of Object to delete + * @param obj $container name or instance of Container in which the object resides (optional) + * @return boolean True if successfully removed + * @throws SyntaxException invalid Object name + * @throws NoSuchObjectException remote Object does not exist + * @throws InvalidResponseException unexpected response + */ + function delete_object($obj,$container=NULL) + { + $obj_name = NULL; + if (is_object($obj)) { + if (get_class($obj) == "CF_Object") { + $obj_name = $obj->name; + } + } + if (is_string($obj)) { + $obj_name = $obj; + } + if (!$obj_name) { + throw new SyntaxException("Object name not set."); + } + + $container_name = NULL; + + if($container === NULL) { + $container_name = $this->name; + } + else { + if (is_object($container)) { + if (get_class($container) == "CF_Container") { + $container_name = $container->name; + } + } + if (is_string($container)) { + $container_name = $container; + } + if (!$container_name) { + throw new SyntaxException("Container name source not set."); + } + } + + $status = $this->cfs_http->delete_object($container_name, $obj_name); + #if ($status == 401 && $this->_re_auth()) { + # return $this->delete_object($obj); + #} + if ($status == 404) { + $m = "Specified object '".$container_name."/".$obj_name; + $m.= "' did not exist to delete."; + throw new NoSuchObjectException($m); + } + if ($status != 204) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + return True; + } + + /** + * Helper function to create "path" elements for a given Object name + * + * Given an Object whos name contains '/' path separators, this function + * will create the "directory marker" Objects of one byte with the + * Content-Type of "application/directory". + * + * It assumes the last element of the full path is the "real" Object + * and does NOT create a remote storage Object for that last element. + */ + function create_paths($path_name) + { + if ($path_name[0] == '/') { + $path_name = mb_substr($path_name, 0, 1); + } + $elements = explode('/', $path_name, -1); + $build_path = ""; + foreach ($elements as $idx => $val) { + if (!$build_path) { + $build_path = $val; + } else { + $build_path .= "/" . $val; + } + $obj = new CF_Object($this, $build_path); + $obj->content_type = "application/directory"; + $obj->write(".", 1); + } + } + + /** + * Internal method to grab CDN/Container info if appropriate to do so + * + * @throws InvalidResponseException unexpected response + */ + private function _cdn_initialize() + { + list($status, $reason, $cdn_enabled, $cdn_ssl_uri, $cdn_streaming_uri, $cdn_uri, $cdn_ttl, + $cdn_log_retention, $cdn_acl_user_agent, $cdn_acl_referrer) = + $this->cfs_http->head_cdn_container($this->name); + #if ($status == 401 && $this->_re_auth()) { + # return $this->_cdn_initialize(); + #} + if (!in_array($status, array(204,404))) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->cfs_http->get_error()); + } + $this->cdn_enabled = $cdn_enabled; + $this->cdn_streaming_uri = $cdn_streaming_uri; + $this->cdn_ssl_uri = $cdn_ssl_uri; + $this->cdn_uri = $cdn_uri; + $this->cdn_ttl = $cdn_ttl; + $this->cdn_log_retention = $cdn_log_retention; + $this->cdn_acl_user_agent = $cdn_acl_user_agent; + $this->cdn_acl_referrer = $cdn_acl_referrer; + } + + #private function _re_auth() + #{ + # $new_auth = new CF_Authentication( + # $this->cfs_auth->username, + # $this->cfs_auth->api_key, + # $this->cfs_auth->auth_host, + # $this->cfs_auth->account); + # $new_auth->authenticate(); + # $this->cfs_auth = $new_auth; + # $this->cfs_http->setCFAuth($this->cfs_auth); + # return True; + #} +} + + +/** + * Object operations + * + * An Object is analogous to a file on a conventional filesystem. You can + * read data from, or write data to your Objects. You can also associate + * arbitrary metadata with them. + * + * @package php-cloudfiles + */ +class CF_Object +{ + public $container; + public $name; + public $last_modified; + public $content_type; + public $content_length; + public $metadata; + public $headers; + public $manifest; + private $etag; + + /** + * Class constructor + * + * @param obj $container CF_Container instance + * @param string $name name of Object + * @param boolean $force_exists if set, throw an error if Object doesn't exist + */ + function __construct(&$container, $name, $force_exists=False, $dohead=True) + { + if ($name[0] == "/") { + $r = "Object name '".$name; + $r .= "' cannot contain begin with a '/' character."; + throw new SyntaxException($r); + } + if (strlen($name) > MAX_OBJECT_NAME_LEN) { + throw new SyntaxException("Object name exceeds " + . "maximum allowed length."); + } + $this->container = $container; + $this->name = $name; + $this->etag = NULL; + $this->_etag_override = False; + $this->last_modified = NULL; + $this->content_type = NULL; + $this->content_length = 0; + $this->metadata = array(); + $this->headers = array(); + $this->manifest = NULL; + if ($dohead) { + if (!$this->_initialize() && $force_exists) { + throw new NoSuchObjectException("No such object '".$name."'"); + } + } + } + + /** + * String representation of Object + * + * Pretty print the Object's location and name + * + * @return string Object information + */ + function __toString() + { + return $this->container->name . "/" . $this->name; + } + + /** + * Internal check to get the proper mimetype. + * + * This function would go over the available PHP methods to get + * the MIME type. + * + * By default it will try to use the PHP fileinfo library which is + * available from PHP 5.3 or as an PECL extension + * (http://pecl.php.net/package/Fileinfo). + * + * It will get the magic file by default from the system wide file + * which is usually available in /usr/share/magic on Unix or try + * to use the file specified in the source directory of the API + * (share directory). + * + * if fileinfo is not available it will try to use the internal + * mime_content_type function. + * + * @param string $handle name of file or buffer to guess the type from + * @return boolean True if successful + * @throws BadContentTypeException + */ + function _guess_content_type($handle) { + if ($this->content_type) + return; + +// if (function_exists("finfo_open")) { +// $local_magic = dirname(__FILE__) . "/share/magic"; +// $finfo = @finfo_open(FILEINFO_MIME, $local_magic); +// +// if (!$finfo) +// $finfo = @finfo_open(FILEINFO_MIME); +// +// if ($finfo) { +// +// if (is_file((string)$handle)) +// $ct = @finfo_file($finfo, $handle); +// else +// $ct = @finfo_buffer($finfo, $handle); +// +// /* PHP 5.3 fileinfo display extra information like +// charset so we remove everything after the ; since +// we are not into that stuff */ +// if ($ct) { +// $extra_content_type_info = strpos($ct, "; "); +// if ($extra_content_type_info) +// $ct = substr($ct, 0, $extra_content_type_info); +// } +// +// if ($ct && $ct != 'application/octet-stream') +// $this->content_type = $ct; +// +// @finfo_close($finfo); +// } +// } +// +// if (!$this->content_type && (string)is_file($handle) && function_exists("mime_content_type")) { +// $this->content_type = @mime_content_type($handle); +// } + + //use OC's mimetype detection for files + if(is_file($handle)){ + $this->content_type=OC_Helper::getMimeType($handle); + }else{ + $this->content_type=OC_Helper::getStringMimeType($handle); + } + + if (!$this->content_type) { + throw new BadContentTypeException("Required Content-Type not set"); + } + return True; + } + + /** + * String representation of the Object's public URI + * + * A string representing the Object's public URI assuming that it's + * parent Container is CDN-enabled. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * # Print out the Object's CDN URI (if it has one) in an HTML img-tag + * # + * print "\n"; + * + * + * @return string Object's public URI or NULL + */ + function public_uri() + { + if ($this->container->cdn_enabled) { + return $this->container->cdn_uri . "/" . $this->name; + } + return NULL; + } + + /** + * String representation of the Object's public SSL URI + * + * A string representing the Object's public SSL URI assuming that it's + * parent Container is CDN-enabled. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * # Print out the Object's CDN SSL URI (if it has one) in an HTML img-tag + * # + * print "\n"; + * + * + * @return string Object's public SSL URI or NULL + */ + function public_ssl_uri() + { + if ($this->container->cdn_enabled) { + return $this->container->cdn_ssl_uri . "/" . $this->name; + } + return NULL; + } + /** + * String representation of the Object's public Streaming URI + * + * A string representing the Object's public Streaming URI assuming that it's + * parent Container is CDN-enabled. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * # Print out the Object's CDN Streaming URI (if it has one) in an HTML img-tag + * # + * print "\n"; + * + * + * @return string Object's public Streaming URI or NULL + */ + function public_streaming_uri() + { + if ($this->container->cdn_enabled) { + return $this->container->cdn_streaming_uri . "/" . $this->name; + } + return NULL; + } + + /** + * Read the remote Object's data + * + * Returns the Object's data. This is useful for smaller Objects such + * as images or office documents. Object's with larger content should use + * the stream() method below. + * + * Pass in $hdrs array to set specific custom HTTP headers such as + * If-Match, If-None-Match, If-Modified-Since, Range, etc. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * $data = $doc->read(); # read image content into a string variable + * print $data; + * + * # Or see stream() below for a different example. + * # + * + * + * @param array $hdrs user-defined headers (Range, If-Match, etc.) + * @return string Object's data + * @throws InvalidResponseException unexpected response + */ + function read($hdrs=array()) + { + list($status, $reason, $data) = + $this->container->cfs_http->get_object_to_string($this, $hdrs); + #if ($status == 401 && $this->_re_auth()) { + # return $this->read($hdrs); + #} + if (($status < 200) || ($status > 299 + && $status != 412 && $status != 304)) { + throw new InvalidResponseException("Invalid response (".$status."): " + . $this->container->cfs_http->get_error()); + } + return $data; + } + + /** + * Streaming read of Object's data + * + * Given an open PHP resource (see PHP's fopen() method), fetch the Object's + * data and write it to the open resource handle. This is useful for + * streaming an Object's content to the browser (videos, images) or for + * fetching content to a local file. + * + * Pass in $hdrs array to set specific custom HTTP headers such as + * If-Match, If-None-Match, If-Modified-Since, Range, etc. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * # Assuming this is a web script to display the README to the + * # user's browser: + * # + * get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * // Hand it back to user's browser with appropriate content-type + * // + * header("Content-Type: " . $doc->content_type); + * $output = fopen("php://output", "w"); + * $doc->stream($output); # stream object content to PHP's output buffer + * fclose($output); + * ?> + * + * # See read() above for a more simple example. + * # + * + * + * @param resource $fp open resource for writing data to + * @param array $hdrs user-defined headers (Range, If-Match, etc.) + * @return string Object's data + * @throws InvalidResponseException unexpected response + */ + function stream(&$fp, $hdrs=array()) + { + list($status, $reason) = + $this->container->cfs_http->get_object_to_stream($this,$fp,$hdrs); + #if ($status == 401 && $this->_re_auth()) { + # return $this->stream($fp, $hdrs); + #} + if (($status < 200) || ($status > 299 + && $status != 412 && $status != 304)) { + throw new InvalidResponseException("Invalid response (".$status."): " + .$reason); + } + return True; + } + + /** + * Store new Object metadata + * + * Write's an Object's metadata to the remote Object. This will overwrite + * an prior Object metadata. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * # Define new metadata for the object + * # + * $doc->metadata = array( + * "Author" => "EJ", + * "Subject" => "How to use the PHP tests", + * "Version" => "1.2.2" + * ); + * + * # Define additional headers for the object + * # + * $doc->headers = array( + * "Content-Disposition" => "attachment", + * ); + * + * # Push the new metadata up to the storage system + * # + * $doc->sync_metadata(); + * + * + * @return boolean True if successful, False otherwise + * @throws InvalidResponseException unexpected response + */ + function sync_metadata() + { + if (!empty($this->metadata) || !empty($this->headers) || $this->manifest) { + $status = $this->container->cfs_http->update_object($this); + #if ($status == 401 && $this->_re_auth()) { + # return $this->sync_metadata(); + #} + if ($status != 202) { + throw new InvalidResponseException("Invalid response (" + .$status."): ".$this->container->cfs_http->get_error()); + } + return True; + } + return False; + } + /** + * Store new Object manifest + * + * Write's an Object's manifest to the remote Object. This will overwrite + * an prior Object manifest. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * # Define new manifest for the object + * # + * $doc->manifest = "container/prefix"; + * + * # Push the new manifest up to the storage system + * # + * $doc->sync_manifest(); + * + * + * @return boolean True if successful, False otherwise + * @throws InvalidResponseException unexpected response + */ + + function sync_manifest() + { + return $this->sync_metadata(); + } + /** + * Upload Object's data to Cloud Files + * + * Write data to the remote Object. The $data argument can either be a + * PHP resource open for reading (see PHP's fopen() method) or an in-memory + * variable. If passing in a PHP resource, you must also include the $bytes + * parameter. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * # Upload placeholder text in my README + * # + * $doc->write("This is just placeholder text for now..."); + * + * + * @param string|resource $data string or open resource + * @param float $bytes amount of data to upload (required for resources) + * @param boolean $verify generate, send, and compare MD5 checksums + * @return boolean True when data uploaded successfully + * @throws SyntaxException missing required parameters + * @throws BadContentTypeException if no Content-Type was/could be set + * @throws MisMatchedChecksumException $verify is set and checksums unequal + * @throws InvalidResponseException unexpected response + */ + function write($data=NULL, $bytes=0, $verify=True) + { + if (!$data && !is_string($data)) { + throw new SyntaxException("Missing data source."); + } + if ($bytes > MAX_OBJECT_SIZE) { + throw new SyntaxException("Bytes exceeds maximum object size."); + } + if ($verify) { + if (!$this->_etag_override) { + $this->etag = $this->compute_md5sum($data); + } + } else { + $this->etag = NULL; + } + + $close_fh = False; + if (!is_resource($data)) { + # A hack to treat string data as a file handle. php://memory feels + # like a better option, but it seems to break on Windows so use + # a temporary file instead. + # + $fp = fopen("php://temp", "wb+"); + #$fp = fopen("php://memory", "wb+"); + fwrite($fp, $data, strlen($data)); + rewind($fp); + $close_fh = True; + $this->content_length = (float) strlen($data); + if ($this->content_length > MAX_OBJECT_SIZE) { + throw new SyntaxException("Data exceeds maximum object size"); + } + $ct_data = substr($data, 0, 64); + } else { + $this->content_length = $bytes; + $fp = $data; + $ct_data = fread($data, 64); + rewind($data); + } + + $this->_guess_content_type($ct_data); + + list($status, $reason, $etag) = + $this->container->cfs_http->put_object($this, $fp); + #if ($status == 401 && $this->_re_auth()) { + # return $this->write($data, $bytes, $verify); + #} + if ($status == 412) { + if ($close_fh) { fclose($fp); } + throw new SyntaxException("Missing Content-Type header"); + } + if ($status == 422) { + if ($close_fh) { fclose($fp); } + throw new MisMatchedChecksumException( + "Supplied and computed checksums do not match."); + } + if ($status != 201) { + if ($close_fh) { fclose($fp); } + throw new InvalidResponseException("Invalid response (".$status."): " + . $this->container->cfs_http->get_error()); + } + if (!$verify) { + $this->etag = $etag; + } + if ($close_fh) { fclose($fp); } + return True; + } + + /** + * Upload Object data from local filename + * + * This is a convenience function to upload the data from a local file. A + * True value for $verify will cause the method to compute the Object's MD5 + * checksum prior to uploading. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * # Upload my local README's content + * # + * $doc->load_from_filename("/home/ej/cloudfiles/readme"); + * + * + * @param string $filename full path to local file + * @param boolean $verify enable local/remote MD5 checksum validation + * @return boolean True if data uploaded successfully + * @throws SyntaxException missing required parameters + * @throws BadContentTypeException if no Content-Type was/could be set + * @throws MisMatchedChecksumException $verify is set and checksums unequal + * @throws InvalidResponseException unexpected response + * @throws IOException error opening file + */ + function load_from_filename($filename, $verify=True) + { + $fp = @fopen($filename, "r"); + if (!$fp) { + throw new IOException("Could not open file for reading: ".$filename); + } + + clearstatcache(); + + $size = (float) sprintf("%u", filesize($filename)); + if ($size > MAX_OBJECT_SIZE) { + throw new SyntaxException("File size exceeds maximum object size."); + } + + $this->_guess_content_type($filename); + + $this->write($fp, $size, $verify); + fclose($fp); + return True; + } + + /** + * Save Object's data to local filename + * + * Given a local filename, the Object's data will be written to the newly + * created file. + * + * Example: + * + * # ... authentication/connection/container code excluded + * # ... see previous examples + * + * # Whoops! I deleted my local README, let me download/save it + * # + * $my_docs = $conn->get_container("documents"); + * $doc = $my_docs->get_object("README"); + * + * $doc->save_to_filename("/home/ej/cloudfiles/readme.restored"); + * + * + * @param string $filename name of local file to write data to + * @return boolean True if successful + * @throws IOException error opening file + * @throws InvalidResponseException unexpected response + */ + function save_to_filename($filename) + { + $fp = @fopen($filename, "wb"); + if (!$fp) { + throw new IOException("Could not open file for writing: ".$filename); + } + $result = $this->stream($fp); + fclose($fp); + return $result; + } + /** + * Purge this Object from CDN Cache. + * Example: + * + * # ... authentication code excluded (see previous examples) ... + * # + * $conn = new CF_Authentication($auth); + * $container = $conn->get_container("cdn_enabled"); + * $obj = $container->get_object("object"); + * $obj->purge_from_cdn("user@domain.com"); + * # or + * $obj->purge_from_cdn(); + * # or + * $obj->purge_from_cdn("user1@domain.com,user2@domain.com"); + * @returns boolean True if successful + * @throws CDNNotEnabledException if CDN Is not enabled on this connection + * @throws InvalidResponseException if the response expected is not returned + */ + function purge_from_cdn($email=null) + { + if (!$this->container->cfs_http->getCDNMUrl()) + { + throw new CDNNotEnabledException( + "Authentication response did not indicate CDN availability"); + } + $status = $this->container->cfs_http->purge_from_cdn($this->container->name . "/" . $this->name, $email); + if ($status < 199 or $status > 299) { + throw new InvalidResponseException( + "Invalid response (".$status."): ".$this->container->cfs_http->get_error()); + } + return True; + } + + /** + * Set Object's MD5 checksum + * + * Manually set the Object's ETag. Including the ETag is mandatory for + * Cloud Files to perform end-to-end verification. Omitting the ETag forces + * the user to handle any data integrity checks. + * + * @param string $etag MD5 checksum hexidecimal string + */ + function set_etag($etag) + { + $this->etag = $etag; + $this->_etag_override = True; + } + + /** + * Object's MD5 checksum + * + * Accessor method for reading Object's private ETag attribute. + * + * @return string MD5 checksum hexidecimal string + */ + function getETag() + { + return $this->etag; + } + + /** + * Compute the MD5 checksum + * + * Calculate the MD5 checksum on either a PHP resource or data. The argument + * may either be a local filename, open resource for reading, or a string. + * + * WARNING: if you are uploading a big file over a stream + * it could get very slow to compute the md5 you probably want to + * set the $verify parameter to False in the write() method and + * compute yourself the md5 before if you have it. + * + * @param filename|obj|string $data filename, open resource, or string + * @return string MD5 checksum hexidecimal string + */ + function compute_md5sum(&$data) + { + + if (function_exists("hash_init") && is_resource($data)) { + $ctx = hash_init('md5'); + while (!feof($data)) { + $buffer = fgets($data, 65536); + hash_update($ctx, $buffer); + } + $md5 = hash_final($ctx, false); + rewind($data); + } elseif ((string)is_file($data)) { + $md5 = md5_file($data); + } else { + $md5 = md5($data); + } + return $md5; + } + + /** + * PRIVATE: fetch information about the remote Object if it exists + */ + private function _initialize() + { + list($status, $reason, $etag, $last_modified, $content_type, + $content_length, $metadata, $manifest, $headers) = + $this->container->cfs_http->head_object($this); + #if ($status == 401 && $this->_re_auth()) { + # return $this->_initialize(); + #} + if ($status == 404) { + return False; + } + if ($status < 200 || $status > 299) { + throw new InvalidResponseException("Invalid response (".$status."): " + . $this->container->cfs_http->get_error()); + } + $this->etag = $etag; + $this->last_modified = $last_modified; + $this->content_type = $content_type; + $this->content_length = $content_length; + $this->metadata = $metadata; + $this->headers = $headers; + $this->manifest = $manifest; + return True; + } + + #private function _re_auth() + #{ + # $new_auth = new CF_Authentication( + # $this->cfs_auth->username, + # $this->cfs_auth->api_key, + # $this->cfs_auth->auth_host, + # $this->cfs_auth->account); + # $new_auth->authenticate(); + # $this->container->cfs_auth = $new_auth; + # $this->container->cfs_http->setCFAuth($this->cfs_auth); + # return True; + #} +} + +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * c-hanging-comment-ender-p: nil + * End: + */ +?> diff --git a/3rdparty/php-cloudfiles/cloudfiles_exceptions.php b/3rdparty/php-cloudfiles/cloudfiles_exceptions.php new file mode 100644 index 00000000000..5624d6b8634 --- /dev/null +++ b/3rdparty/php-cloudfiles/cloudfiles_exceptions.php @@ -0,0 +1,41 @@ + + * @copyright Copyright (c) 2008, Rackspace US, Inc. + * @package php-cloudfiles-exceptions + */ + +/** + * Custom Exceptions for the CloudFiles API + * @package php-cloudfiles-exceptions + */ +class SyntaxException extends Exception { } +class AuthenticationException extends Exception { } +class InvalidResponseException extends Exception { } +class NonEmptyContainerException extends Exception { } +class NoSuchObjectException extends Exception { } +class NoSuchContainerException extends Exception { } +class NoSuchAccountException extends Exception { } +class MisMatchedChecksumException extends Exception { } +class IOException extends Exception { } +class CDNNotEnabledException extends Exception { } +class BadContentTypeException extends Exception { } +class InvalidUTF8Exception extends Exception { } +class ConnectionNotOpenException extends Exception { } + +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * c-hanging-comment-ender-p: nil + * End: + */ +?> diff --git a/3rdparty/php-cloudfiles/cloudfiles_http.php b/3rdparty/php-cloudfiles/cloudfiles_http.php new file mode 100644 index 00000000000..0e5d9717e81 --- /dev/null +++ b/3rdparty/php-cloudfiles/cloudfiles_http.php @@ -0,0 +1,1488 @@ + + * @copyright Copyright (c) 2008, Rackspace US, Inc. + * @package php-cloudfiles-http + */ + +/** + */ +require_once("cloudfiles_exceptions.php"); + +define("PHP_CF_VERSION", "1.7.10"); +define("USER_AGENT", sprintf("PHP-CloudFiles/%s", PHP_CF_VERSION)); +define("MAX_HEADER_NAME_LEN", 128); +define("MAX_HEADER_VALUE_LEN", 256); +define("ACCOUNT_CONTAINER_COUNT", "X-Account-Container-Count"); +define("ACCOUNT_BYTES_USED", "X-Account-Bytes-Used"); +define("CONTAINER_OBJ_COUNT", "X-Container-Object-Count"); +define("CONTAINER_BYTES_USED", "X-Container-Bytes-Used"); +define("MANIFEST_HEADER", "X-Object-Manifest"); +define("METADATA_HEADER_PREFIX", "X-Object-Meta-"); +define("CONTENT_HEADER_PREFIX", "Content-"); +define("ACCESS_CONTROL_HEADER_PREFIX", "Access-Control-"); +define("ORIGIN_HEADER", "Origin"); +define("CDN_URI", "X-CDN-URI"); +define("CDN_SSL_URI", "X-CDN-SSL-URI"); +define("CDN_STREAMING_URI", "X-CDN-Streaming-URI"); +define("CDN_ENABLED", "X-CDN-Enabled"); +define("CDN_LOG_RETENTION", "X-Log-Retention"); +define("CDN_ACL_USER_AGENT", "X-User-Agent-ACL"); +define("CDN_ACL_REFERRER", "X-Referrer-ACL"); +define("CDN_TTL", "X-TTL"); +define("CDNM_URL", "X-CDN-Management-Url"); +define("STORAGE_URL", "X-Storage-Url"); +define("AUTH_TOKEN", "X-Auth-Token"); +define("AUTH_USER_HEADER", "X-Auth-User"); +define("AUTH_KEY_HEADER", "X-Auth-Key"); +define("AUTH_USER_HEADER_LEGACY", "X-Storage-User"); +define("AUTH_KEY_HEADER_LEGACY", "X-Storage-Pass"); +define("AUTH_TOKEN_LEGACY", "X-Storage-Token"); +define("CDN_EMAIL", "X-Purge-Email"); +define("DESTINATION", "Destination"); +define("ETAG_HEADER", "ETag"); +define("LAST_MODIFIED_HEADER", "Last-Modified"); +define("CONTENT_TYPE_HEADER", "Content-Type"); +define("CONTENT_LENGTH_HEADER", "Content-Length"); +define("USER_AGENT_HEADER", "User-Agent"); + +/** + * HTTP/cURL wrapper for Cloud Files + * + * This class should not be used directly. It's only purpose is to abstract + * out the HTTP communication from the main API. + * + * @package php-cloudfiles-http + */ +class CF_Http +{ + private $error_str; + private $dbug; + private $cabundle_path; + private $api_version; + + # Authentication instance variables + # + private $storage_url; + private $cdnm_url; + private $auth_token; + + # Request/response variables + # + private $response_status; + private $response_reason; + private $connections; + + # Variables used for content/header callbacks + # + private $_user_read_progress_callback_func; + private $_user_write_progress_callback_func; + private $_write_callback_type; + private $_text_list; + private $_account_container_count; + private $_account_bytes_used; + private $_container_object_count; + private $_container_bytes_used; + private $_obj_etag; + private $_obj_last_modified; + private $_obj_content_type; + private $_obj_content_length; + private $_obj_metadata; + private $_obj_headers; + private $_obj_manifest; + private $_obj_write_resource; + private $_obj_write_string; + private $_cdn_enabled; + private $_cdn_ssl_uri; + private $_cdn_streaming_uri; + private $_cdn_uri; + private $_cdn_ttl; + private $_cdn_log_retention; + private $_cdn_acl_user_agent; + private $_cdn_acl_referrer; + + function __construct($api_version) + { + $this->dbug = False; + $this->cabundle_path = NULL; + $this->api_version = $api_version; + $this->error_str = NULL; + + $this->storage_url = NULL; + $this->cdnm_url = NULL; + $this->auth_token = NULL; + + $this->response_status = NULL; + $this->response_reason = NULL; + + # Curl connections array - since there is no way to "re-set" the + # connection paramaters for a cURL handle, we keep an array of + # the unique use-cases and funnel all of those same type + # requests through the appropriate curl connection. + # + $this->connections = array( + "GET_CALL" => NULL, # GET objects/containers/lists + "PUT_OBJ" => NULL, # PUT object + "HEAD" => NULL, # HEAD requests + "PUT_CONT" => NULL, # PUT container + "DEL_POST" => NULL, # DELETE containers/objects, POST objects + "COPY" => null, # COPY objects + ); + + $this->_user_read_progress_callback_func = NULL; + $this->_user_write_progress_callback_func = NULL; + $this->_write_callback_type = NULL; + $this->_text_list = array(); + $this->_return_list = NULL; + $this->_account_container_count = 0; + $this->_account_bytes_used = 0; + $this->_container_object_count = 0; + $this->_container_bytes_used = 0; + $this->_obj_write_resource = NULL; + $this->_obj_write_string = ""; + $this->_obj_etag = NULL; + $this->_obj_last_modified = NULL; + $this->_obj_content_type = NULL; + $this->_obj_content_length = NULL; + $this->_obj_metadata = array(); + $this->_obj_manifest = NULL; + $this->_obj_headers = NULL; + $this->_cdn_enabled = NULL; + $this->_cdn_ssl_uri = NULL; + $this->_cdn_streaming_uri = NULL; + $this->_cdn_uri = NULL; + $this->_cdn_ttl = NULL; + $this->_cdn_log_retention = NULL; + $this->_cdn_acl_user_agent = NULL; + $this->_cdn_acl_referrer = NULL; + + # The OS list with a PHP without an updated CA File for CURL to + # connect to SSL Websites. It is the first 3 letters of the PHP_OS + # variable. + $OS_CAFILE_NONUPDATED=array( + "win","dar" + ); + + if (in_array((strtolower (substr(PHP_OS, 0,3))), $OS_CAFILE_NONUPDATED)) + $this->ssl_use_cabundle(); + + } + + function ssl_use_cabundle($path=NULL) + { + if ($path) { + $this->cabundle_path = $path; + } else { + $this->cabundle_path = dirname(__FILE__) . "/share/cacert.pem"; + } + if (!file_exists($this->cabundle_path)) { + throw new IOException("Could not use CA bundle: " + . $this->cabundle_path); + } + return; + } + + # Uses separate cURL connection to authenticate + # + function authenticate($user, $pass, $acct=NULL, $host=NULL) + { + $path = array(); + if (isset($acct)){ + $headers = array( + sprintf("%s: %s", AUTH_USER_HEADER_LEGACY, $user), + sprintf("%s: %s", AUTH_KEY_HEADER_LEGACY, $pass), + ); + $path[] = $host; + $path[] = rawurlencode(sprintf("v%d",$this->api_version)); + $path[] = rawurlencode($acct); + } else { + $headers = array( + sprintf("%s: %s", AUTH_USER_HEADER, $user), + sprintf("%s: %s", AUTH_KEY_HEADER, $pass), + ); + $path[] = $host; + } + $path[] = "v1.0"; + $url = implode("/", $path); + + $curl_ch = curl_init(); + if (!is_null($this->cabundle_path)) { + curl_setopt($curl_ch, CURLOPT_SSL_VERIFYPEER, True); + curl_setopt($curl_ch, CURLOPT_CAINFO, $this->cabundle_path); + } + curl_setopt($curl_ch, CURLOPT_VERBOSE, $this->dbug); + curl_setopt($curl_ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curl_ch, CURLOPT_MAXREDIRS, 4); + curl_setopt($curl_ch, CURLOPT_HEADER, 0); + curl_setopt($curl_ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($curl_ch, CURLOPT_USERAGENT, USER_AGENT); + curl_setopt($curl_ch, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($curl_ch, CURLOPT_HEADERFUNCTION,array(&$this,'_auth_hdr_cb')); + curl_setopt($curl_ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($curl_ch, CURLOPT_URL, $url); + curl_exec($curl_ch); + curl_close($curl_ch); + + return array($this->response_status, $this->response_reason, + $this->storage_url, $this->cdnm_url, $this->auth_token); + } + + # (CDN) GET /v1/Account + # + function list_cdn_containers($enabled_only) + { + $conn_type = "GET_CALL"; + $url_path = $this->_make_path("CDN"); + + $this->_write_callback_type = "TEXT_LIST"; + if ($enabled_only) + { + $return_code = $this->_send_request($conn_type, $url_path . + '/?enabled_only=true'); + } + else + { + $return_code = $this->_send_request($conn_type, $url_path); + } + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,array()); + } + if ($return_code == 401) { + return array($return_code,"Unauthorized",array()); + } + if ($return_code == 404) { + return array($return_code,"Account not found.",array()); + } + if ($return_code == 204) { + return array($return_code,"Account has no CDN enabled Containers.", + array()); + } + if ($return_code == 200) { + $this->create_array(); + return array($return_code,$this->response_reason,$this->_text_list); + } + $this->error_str = "Unexpected HTTP response: ".$this->response_reason; + return array($return_code,$this->error_str,array()); + } + + # (CDN) DELETE /v1/Account/Container or /v1/Account/Container/Object + # + function purge_from_cdn($path, $email=null) + { + if(!$path) + throw new SyntaxException("Path not set"); + $url_path = $this->_make_path("CDN", NULL, $path); + if($email) + { + $hdrs = array(CDN_EMAIL => $email); + $return_code = $this->_send_request("DEL_POST",$url_path,$hdrs,"DELETE"); + } + else + $return_code = $this->_send_request("DEL_POST",$url_path,null,"DELETE"); + return $return_code; + } + + # (CDN) POST /v1/Account/Container + function update_cdn_container($container_name, $ttl=86400, $cdn_log_retention=False, + $cdn_acl_user_agent="", $cdn_acl_referrer) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $url_path = $this->_make_path("CDN", $container_name); + $hdrs = array( + CDN_ENABLED => "True", + CDN_TTL => $ttl, + CDN_LOG_RETENTION => $cdn_log_retention ? "True" : "False", + CDN_ACL_USER_AGENT => $cdn_acl_user_agent, + CDN_ACL_REFERRER => $cdn_acl_referrer, + ); + $return_code = $this->_send_request("DEL_POST",$url_path,$hdrs,"POST"); + if ($return_code == 401) { + $this->error_str = "Unauthorized"; + return array($return_code, $this->error_str, NULL); + } + if ($return_code == 404) { + $this->error_str = "Container not found."; + return array($return_code, $this->error_str, NULL); + } + if ($return_code != 202) { + $this->error_str="Unexpected HTTP response: ".$this->response_reason; + return array($return_code, $this->error_str, NULL); + } + return array($return_code, "Accepted", $this->_cdn_uri, $this->_cdn_ssl_uri); + + } + + # (CDN) PUT /v1/Account/Container + # + function add_cdn_container($container_name, $ttl=86400) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $url_path = $this->_make_path("CDN", $container_name); + $hdrs = array( + CDN_ENABLED => "True", + CDN_TTL => $ttl, + ); + $return_code = $this->_send_request("PUT_CONT", $url_path, $hdrs); + if ($return_code == 401) { + $this->error_str = "Unauthorized"; + return array($return_code,$this->response_reason,False); + } + if (!in_array($return_code, array(201,202))) { + $this->error_str="Unexpected HTTP response: ".$this->response_reason; + return array($return_code,$this->response_reason,False); + } + return array($return_code,$this->response_reason,$this->_cdn_uri, + $this->_cdn_ssl_uri); + } + + # (CDN) POST /v1/Account/Container + # + function remove_cdn_container($container_name) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $url_path = $this->_make_path("CDN", $container_name); + $hdrs = array(CDN_ENABLED => "False"); + $return_code = $this->_send_request("DEL_POST",$url_path,$hdrs,"POST"); + if ($return_code == 401) { + $this->error_str = "Unauthorized"; + return array($return_code, $this->error_str); + } + if ($return_code == 404) { + $this->error_str = "Container not found."; + return array($return_code, $this->error_str); + } + if ($return_code != 202) { + $this->error_str="Unexpected HTTP response: ".$this->response_reason; + return array($return_code, $this->error_str); + } + return array($return_code, "Accepted"); + } + + # (CDN) HEAD /v1/Account + # + function head_cdn_container($container_name) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $conn_type = "HEAD"; + $url_path = $this->_make_path("CDN", $container_name); + $return_code = $this->_send_request($conn_type, $url_path, NULL, "GET", True); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); + } + if ($return_code == 401) { + return array($return_code,"Unauthorized",NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); + } + if ($return_code == 404) { + return array($return_code,"Account not found.",NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); + } + if ($return_code == 204) { + return array($return_code,$this->response_reason, + $this->_cdn_enabled, $this->_cdn_ssl_uri, + $this->_cdn_streaming_uri, + $this->_cdn_uri, $this->_cdn_ttl, + $this->_cdn_log_retention, + $this->_cdn_acl_user_agent, + $this->_cdn_acl_referrer + ); + } + return array($return_code,$this->response_reason, + NULL,NULL,NULL,NULL, + $this->_cdn_log_retention, + $this->_cdn_acl_user_agent, + $this->_cdn_acl_referrer, + NULL + ); + } + + # GET /v1/Account + # + function list_containers($limit=0, $marker=NULL) + { + $conn_type = "GET_CALL"; + $url_path = $this->_make_path(); + + $limit = intval($limit); + $params = array(); + if ($limit > 0) { + $params[] = "limit=$limit"; + } + if ($marker) { + $params[] = "marker=".rawurlencode($marker); + } + if (!empty($params)) { + $url_path .= "?" . implode("&", $params); + } + + $this->_write_callback_type = "TEXT_LIST"; + $return_code = $this->_send_request($conn_type, $url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,array()); + } + if ($return_code == 204) { + return array($return_code, "Account has no containers.", array()); + } + if ($return_code == 404) { + $this->error_str = "Invalid account name for authentication token."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 200) { + $this->create_array(); + return array($return_code, $this->response_reason, $this->_text_list); + } + $this->error_str = "Unexpected HTTP response: ".$this->response_reason; + return array($return_code,$this->error_str,array()); + } + + # GET /v1/Account?format=json + # + function list_containers_info($limit=0, $marker=NULL) + { + $conn_type = "GET_CALL"; + $url_path = $this->_make_path() . "?format=json"; + + $limit = intval($limit); + $params = array(); + if ($limit > 0) { + $params[] = "limit=$limit"; + } + if ($marker) { + $params[] = "marker=".rawurlencode($marker); + } + if (!empty($params)) { + $url_path .= "&" . implode("&", $params); + } + + $this->_write_callback_type = "OBJECT_STRING"; + $return_code = $this->_send_request($conn_type, $url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,array()); + } + if ($return_code == 204) { + return array($return_code, "Account has no containers.", array()); + } + if ($return_code == 404) { + $this->error_str = "Invalid account name for authentication token."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 200) { + $json_body = json_decode($this->_obj_write_string, True); + return array($return_code, $this->response_reason, $json_body); + } + $this->error_str = "Unexpected HTTP response: ".$this->response_reason; + return array($return_code,$this->error_str,array()); + } + + # HEAD /v1/Account + # + function head_account() + { + $conn_type = "HEAD"; + + $url_path = $this->_make_path(); + $return_code = $this->_send_request($conn_type,$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,0,0); + } + if ($return_code == 404) { + return array($return_code,"Account not found.",0,0); + } + if ($return_code == 204) { + return array($return_code,$this->response_reason, + $this->_account_container_count, $this->_account_bytes_used); + } + return array($return_code,$this->response_reason,0,0); + } + + # PUT /v1/Account/Container + # + function create_container($container_name) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $url_path = $this->_make_path("STORAGE", $container_name); + $return_code = $this->_send_request("PUT_CONT",$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return False; + } + return $return_code; + } + + # DELETE /v1/Account/Container + # + function delete_container($container_name) + { + if ($container_name == "") + throw new SyntaxException("Container name not set."); + + if ($container_name != "0" and !isset($container_name)) + throw new SyntaxException("Container name not set."); + + $url_path = $this->_make_path("STORAGE", $container_name); + $return_code = $this->_send_request("DEL_POST",$url_path,array(),"DELETE"); + + switch ($return_code) { + case 204: + break; + case 0: + $this->error_str .= ": Failed to obtain valid HTTP response.";; + break; + case 409: + $this->error_str = "Container must be empty prior to removing it."; + break; + case 404: + $this->error_str = "Specified container did not exist to delete."; + break; + default: + $this->error_str = "Unexpected HTTP return code: $return_code."; + } + return $return_code; + } + + # GET /v1/Account/Container + # + function list_objects($cname,$limit=0,$marker=NULL,$prefix=NULL,$path=NULL) + { + if (!$cname) { + $this->error_str = "Container name not set."; + return array(0, $this->error_str, array()); + } + + $url_path = $this->_make_path("STORAGE", $cname); + + $limit = intval($limit); + $params = array(); + if ($limit > 0) { + $params[] = "limit=$limit"; + } + if ($marker) { + $params[] = "marker=".rawurlencode($marker); + } + if ($prefix) { + $params[] = "prefix=".rawurlencode($prefix); + } + if ($path) { + $params[] = "path=".rawurlencode($path); + } + if (!empty($params)) { + $url_path .= "?" . implode("&", $params); + } + + $conn_type = "GET_CALL"; + $this->_write_callback_type = "TEXT_LIST"; + $return_code = $this->_send_request($conn_type,$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,array()); + } + if ($return_code == 204) { + $this->error_str = "Container has no Objects."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 404) { + $this->error_str = "Container has no Objects."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 200) { + $this->create_array(); + return array($return_code,$this->response_reason, $this->_text_list); + } + $this->error_str = "Unexpected HTTP response code: $return_code"; + return array(0,$this->error_str,array()); + } + + # GET /v1/Account/Container?format=json + # + function get_objects($cname,$limit=0,$marker=NULL,$prefix=NULL,$path=NULL) + { + if (!$cname) { + $this->error_str = "Container name not set."; + return array(0, $this->error_str, array()); + } + + $url_path = $this->_make_path("STORAGE", $cname); + + $limit = intval($limit); + $params = array(); + $params[] = "format=json"; + if ($limit > 0) { + $params[] = "limit=$limit"; + } + if ($marker) { + $params[] = "marker=".rawurlencode($marker); + } + if ($prefix) { + $params[] = "prefix=".rawurlencode($prefix); + } + if ($path) { + $params[] = "path=".rawurlencode($path); + } + if (!empty($params)) { + $url_path .= "?" . implode("&", $params); + } + + $conn_type = "GET_CALL"; + $this->_write_callback_type = "OBJECT_STRING"; + $return_code = $this->_send_request($conn_type,$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,array()); + } + if ($return_code == 204) { + $this->error_str = "Container has no Objects."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 404) { + $this->error_str = "Container has no Objects."; + return array($return_code,$this->error_str,array()); + } + if ($return_code == 200) { + $json_body = json_decode($this->_obj_write_string, True); + return array($return_code,$this->response_reason, $json_body); + } + $this->error_str = "Unexpected HTTP response code: $return_code"; + return array(0,$this->error_str,array()); + } + + + # HEAD /v1/Account/Container + # + function head_container($container_name) + { + + if ($container_name == "") { + $this->error_str = "Container name not set."; + return False; + } + + if ($container_name != "0" and !isset($container_name)) { + $this->error_str = "Container name not set."; + return False; + } + + $conn_type = "HEAD"; + + $url_path = $this->_make_path("STORAGE", $container_name); + $return_code = $this->_send_request($conn_type,$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,0,0); + } + if ($return_code == 404) { + return array($return_code,"Container not found.",0,0); + } + if ($return_code == 204 || $return_code == 200) { + return array($return_code,$this->response_reason, + $this->_container_object_count, $this->_container_bytes_used); + } + return array($return_code,$this->response_reason,0,0); + } + + # GET /v1/Account/Container/Object + # + function get_object_to_string(&$obj, $hdrs=array()) + { + if (!is_object($obj) || get_class($obj) != "CF_Object") { + throw new SyntaxException( + "Method argument is not a valid CF_Object."); + } + + $conn_type = "GET_CALL"; + + $url_path = $this->_make_path("STORAGE", $obj->container->name,$obj->name); + $this->_write_callback_type = "OBJECT_STRING"; + $return_code = $this->_send_request($conn_type,$url_path,$hdrs); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array($return_code0,$this->error_str,NULL); + } + if ($return_code == 404) { + $this->error_str = "Object not found."; + return array($return_code0,$this->error_str,NULL); + } + if (($return_code < 200) || ($return_code > 299 + && $return_code != 412 && $return_code != 304)) { + $this->error_str = "Unexpected HTTP return code: $return_code"; + return array($return_code,$this->error_str,NULL); + } + return array($return_code,$this->response_reason, $this->_obj_write_string); + } + + # GET /v1/Account/Container/Object + # + function get_object_to_stream(&$obj, &$resource=NULL, $hdrs=array()) + { + if (!is_object($obj) || get_class($obj) != "CF_Object") { + throw new SyntaxException( + "Method argument is not a valid CF_Object."); + } + if (!is_resource($resource)) { + throw new SyntaxException( + "Resource argument not a valid PHP resource."); + } + + $conn_type = "GET_CALL"; + + $url_path = $this->_make_path("STORAGE", $obj->container->name,$obj->name); + $this->_obj_write_resource = $resource; + $this->_write_callback_type = "OBJECT_STREAM"; + $return_code = $this->_send_request($conn_type,$url_path,$hdrs); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array($return_code,$this->error_str); + } + if ($return_code == 404) { + $this->error_str = "Object not found."; + return array($return_code,$this->error_str); + } + if (($return_code < 200) || ($return_code > 299 + && $return_code != 412 && $return_code != 304)) { + $this->error_str = "Unexpected HTTP return code: $return_code"; + return array($return_code,$this->error_str); + } + return array($return_code,$this->response_reason); + } + + # PUT /v1/Account/Container/Object + # + function put_object(&$obj, &$fp) + { + if (!is_object($obj) || get_class($obj) != "CF_Object") { + throw new SyntaxException( + "Method argument is not a valid CF_Object."); + } + if (!is_resource($fp)) { + throw new SyntaxException( + "File pointer argument is not a valid resource."); + } + + $conn_type = "PUT_OBJ"; + $url_path = $this->_make_path("STORAGE", $obj->container->name,$obj->name); + + $hdrs = $this->_headers($obj); + + $etag = $obj->getETag(); + if (isset($etag)) { + $hdrs[] = "ETag: " . $etag; + } + if (!$obj->content_type) { + $hdrs[] = "Content-Type: application/octet-stream"; + } else { + $hdrs[] = "Content-Type: " . $obj->content_type; + } + + $this->_init($conn_type); + curl_setopt($this->connections[$conn_type], + CURLOPT_INFILE, $fp); + if (!$obj->content_length) { + # We don''t know the Content-Length, so assumed "chunked" PUT + # + curl_setopt($this->connections[$conn_type], CURLOPT_UPLOAD, True); + $hdrs[] = 'Transfer-Encoding: chunked'; + } else { + # We know the Content-Length, so use regular transfer + # + curl_setopt($this->connections[$conn_type], + CURLOPT_INFILESIZE, $obj->content_length); + } + $return_code = $this->_send_request($conn_type,$url_path,$hdrs); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0,$this->error_str,NULL); + } + if ($return_code == 412) { + $this->error_str = "Missing Content-Type header"; + return array($return_code,$this->error_str,NULL); + } + if ($return_code == 422) { + $this->error_str = "Derived and computed checksums do not match."; + return array($return_code,$this->error_str,NULL); + } + if ($return_code != 201) { + $this->error_str = "Unexpected HTTP return code: $return_code"; + return array($return_code,$this->error_str,NULL); + } + return array($return_code,$this->response_reason,$this->_obj_etag); + } + + # POST /v1/Account/Container/Object + # + function update_object(&$obj) + { + if (!is_object($obj) || get_class($obj) != "CF_Object") { + throw new SyntaxException( + "Method argument is not a valid CF_Object."); + } + + # TODO: The is_array check isn't in sync with the error message + if (!$obj->manifest && !(is_array($obj->metadata) || is_array($obj->headers))) { + $this->error_str = "Metadata and headers arrays are empty."; + return 0; + } + + $url_path = $this->_make_path("STORAGE", $obj->container->name,$obj->name); + + $hdrs = $this->_headers($obj); + $return_code = $this->_send_request("DEL_POST",$url_path,$hdrs,"POST"); + switch ($return_code) { + case 202: + break; + case 0: + $this->error_str .= ": Failed to obtain valid HTTP response."; + $return_code = 0; + break; + case 404: + $this->error_str = "Account, Container, or Object not found."; + break; + default: + $this->error_str = "Unexpected HTTP return code: $return_code"; + break; + } + return $return_code; + } + + # HEAD /v1/Account/Container/Object + # + function head_object(&$obj) + { + if (!is_object($obj) || get_class($obj) != "CF_Object") { + throw new SyntaxException( + "Method argument is not a valid CF_Object."); + } + + $conn_type = "HEAD"; + + $url_path = $this->_make_path("STORAGE", $obj->container->name,$obj->name); + $return_code = $this->_send_request($conn_type,$url_path); + + if (!$return_code) { + $this->error_str .= ": Failed to obtain valid HTTP response."; + return array(0, $this->error_str." ".$this->response_reason, + NULL, NULL, NULL, NULL, array(), NULL, array()); + } + + if ($return_code == 404) { + return array($return_code, $this->response_reason, + NULL, NULL, NULL, NULL, array(), NULL, array()); + } + if ($return_code == 204 || $return_code == 200) { + return array($return_code,$this->response_reason, + $this->_obj_etag, + $this->_obj_last_modified, + $this->_obj_content_type, + $this->_obj_content_length, + $this->_obj_metadata, + $this->_obj_manifest, + $this->_obj_headers); + } + $this->error_str = "Unexpected HTTP return code: $return_code"; + return array($return_code, $this->error_str." ".$this->response_reason, + NULL, NULL, NULL, NULL, array(), NULL, array()); + } + + # COPY /v1/Account/Container/Object + # + function copy_object($src_obj_name, $dest_obj_name, $container_name_source, $container_name_target, $metadata=NULL, $headers=NULL) + { + if (!$src_obj_name) { + $this->error_str = "Object name not set."; + return 0; + } + + if ($container_name_source == "") { + $this->error_str = "Container name source not set."; + return 0; + } + + if ($container_name_source != "0" and !isset($container_name_source)) { + $this->error_str = "Container name source not set."; + return 0; + } + + if ($container_name_target == "") { + $this->error_str = "Container name target not set."; + return 0; + } + + if ($container_name_target != "0" and !isset($container_name_target)) { + $this->error_str = "Container name target not set."; + return 0; + } + + $conn_type = "COPY"; + + $url_path = $this->_make_path("STORAGE", $container_name_source, rawurlencode($src_obj_name)); + $destination = rawurlencode($container_name_target."/".$dest_obj_name); + + $hdrs = self::_process_headers($metadata, $headers); + $hdrs[DESTINATION] = $destination; + + $return_code = $this->_send_request($conn_type,$url_path,$hdrs,"COPY"); + switch ($return_code) { + case 201: + break; + case 0: + $this->error_str .= ": Failed to obtain valid HTTP response."; + $return_code = 0; + break; + case 404: + $this->error_str = "Specified container/object did not exist."; + break; + default: + $this->error_str = "Unexpected HTTP return code: $return_code."; + } + return $return_code; + } + + # DELETE /v1/Account/Container/Object + # + function delete_object($container_name, $object_name) + { + if ($container_name == "") { + $this->error_str = "Container name not set."; + return 0; + } + + if ($container_name != "0" and !isset($container_name)) { + $this->error_str = "Container name not set."; + return 0; + } + + if (!$object_name) { + $this->error_str = "Object name not set."; + return 0; + } + + $url_path = $this->_make_path("STORAGE", $container_name,$object_name); + $return_code = $this->_send_request("DEL_POST",$url_path,NULL,"DELETE"); + switch ($return_code) { + case 204: + break; + case 0: + $this->error_str .= ": Failed to obtain valid HTTP response."; + $return_code = 0; + break; + case 404: + $this->error_str = "Specified container did not exist to delete."; + break; + default: + $this->error_str = "Unexpected HTTP return code: $return_code."; + } + return $return_code; + } + + function get_error() + { + return $this->error_str; + } + + function setDebug($bool) + { + $this->dbug = $bool; + foreach ($this->connections as $k => $v) { + if (!is_null($v)) { + curl_setopt($this->connections[$k], CURLOPT_VERBOSE, $this->dbug); + } + } + } + + function getCDNMUrl() + { + return $this->cdnm_url; + } + + function getStorageUrl() + { + return $this->storage_url; + } + + function getAuthToken() + { + return $this->auth_token; + } + + function setCFAuth($cfs_auth, $servicenet=False) + { + if ($servicenet) { + $this->storage_url = "https://snet-" . substr($cfs_auth->storage_url, 8); + } else { + $this->storage_url = $cfs_auth->storage_url; + } + $this->auth_token = $cfs_auth->auth_token; + $this->cdnm_url = $cfs_auth->cdnm_url; + } + + function setReadProgressFunc($func_name) + { + $this->_user_read_progress_callback_func = $func_name; + } + + function setWriteProgressFunc($func_name) + { + $this->_user_write_progress_callback_func = $func_name; + } + + private function _header_cb($ch, $header) + { + $header_len = strlen($header); + + if (preg_match("/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches)) { + $this->response_status = $matches[2]; + $this->response_reason = $matches[3]; + return $header_len; + } + + if (strpos($header, ":") === False) + return $header_len; + list($name, $value) = explode(":", $header, 2); + $value = trim($value); + + switch (strtolower($name)) { + case strtolower(CDN_ENABLED): + $this->_cdn_enabled = strtolower($value) == "true"; + break; + case strtolower(CDN_URI): + $this->_cdn_uri = $value; + break; + case strtolower(CDN_SSL_URI): + $this->_cdn_ssl_uri = $value; + break; + case strtolower(CDN_STREAMING_URI): + $this->_cdn_streaming_uri = $value; + break; + case strtolower(CDN_TTL): + $this->_cdn_ttl = $value; + break; + case strtolower(MANIFEST_HEADER): + $this->_obj_manifest = $value; + break; + case strtolower(CDN_LOG_RETENTION): + $this->_cdn_log_retention = strtolower($value) == "true"; + break; + case strtolower(CDN_ACL_USER_AGENT): + $this->_cdn_acl_user_agent = $value; + break; + case strtolower(CDN_ACL_REFERRER): + $this->_cdn_acl_referrer = $value; + break; + case strtolower(ACCOUNT_CONTAINER_COUNT): + $this->_account_container_count = (float)$value+0; + break; + case strtolower(ACCOUNT_BYTES_USED): + $this->_account_bytes_used = (float)$value+0; + break; + case strtolower(CONTAINER_OBJ_COUNT): + $this->_container_object_count = (float)$value+0; + break; + case strtolower(CONTAINER_BYTES_USED): + $this->_container_bytes_used = (float)$value+0; + break; + case strtolower(ETAG_HEADER): + $this->_obj_etag = $value; + break; + case strtolower(LAST_MODIFIED_HEADER): + $this->_obj_last_modified = $value; + break; + case strtolower(CONTENT_TYPE_HEADER): + $this->_obj_content_type = $value; + break; + case strtolower(CONTENT_LENGTH_HEADER): + $this->_obj_content_length = (float)$value+0; + break; + case strtolower(ORIGIN_HEADER): + $this->_obj_headers[ORIGIN_HEADER] = $value; + break; + default: + if (strncasecmp($name, METADATA_HEADER_PREFIX, strlen(METADATA_HEADER_PREFIX)) == 0) { + $name = substr($name, strlen(METADATA_HEADER_PREFIX)); + $this->_obj_metadata[$name] = $value; + } + elseif ((strncasecmp($name, CONTENT_HEADER_PREFIX, strlen(CONTENT_HEADER_PREFIX)) == 0) || + (strncasecmp($name, ACCESS_CONTROL_HEADER_PREFIX, strlen(ACCESS_CONTROL_HEADER_PREFIX)) == 0)) { + $this->_obj_headers[$name] = $value; + } + } + return $header_len; + } + + private function _read_cb($ch, $fd, $length) + { + $data = fread($fd, $length); + $len = strlen($data); + if (isset($this->_user_write_progress_callback_func)) { + call_user_func($this->_user_write_progress_callback_func, $len); + } + return $data; + } + + private function _write_cb($ch, $data) + { + $dlen = strlen($data); + switch ($this->_write_callback_type) { + case "TEXT_LIST": + $this->_return_list = $this->_return_list . $data; + //= explode("\n",$data); # keep tab,space + //his->_text_list[] = rtrim($data,"\n\r\x0B"); # keep tab,space + break; + case "OBJECT_STREAM": + fwrite($this->_obj_write_resource, $data, $dlen); + break; + case "OBJECT_STRING": + $this->_obj_write_string .= $data; + break; + } + if (isset($this->_user_read_progress_callback_func)) { + call_user_func($this->_user_read_progress_callback_func, $dlen); + } + return $dlen; + } + + private function _auth_hdr_cb($ch, $header) + { + preg_match("/^HTTP\/1\.[01] (\d{3}) (.*)/", $header, $matches); + if (isset($matches[1])) { + $this->response_status = $matches[1]; + } + if (isset($matches[2])) { + $this->response_reason = $matches[2]; + } + if (stripos($header, STORAGE_URL) === 0) { + $this->storage_url = trim(substr($header, strlen(STORAGE_URL)+1)); + } + if (stripos($header, CDNM_URL) === 0) { + $this->cdnm_url = trim(substr($header, strlen(CDNM_URL)+1)); + } + if (stripos($header, AUTH_TOKEN) === 0) { + $this->auth_token = trim(substr($header, strlen(AUTH_TOKEN)+1)); + } + if (stripos($header, AUTH_TOKEN_LEGACY) === 0) { + $this->auth_token = trim(substr($header,strlen(AUTH_TOKEN_LEGACY)+1)); + } + return strlen($header); + } + + private function _make_headers($hdrs=NULL) + { + $new_headers = array(); + $has_stoken = False; + $has_uagent = False; + if (is_array($hdrs)) { + foreach ($hdrs as $h => $v) { + if (is_int($h)) { + list($h, $v) = explode(":", $v, 2); + } + + if (strncasecmp($h, AUTH_TOKEN, strlen(AUTH_TOKEN)) === 0) { + $has_stoken = True; + } + if (strncasecmp($h, USER_AGENT_HEADER, strlen(USER_AGENT_HEADER)) === 0) { + $has_uagent = True; + } + $new_headers[] = $h . ": " . trim($v); + } + } + if (!$has_stoken) { + $new_headers[] = AUTH_TOKEN . ": " . $this->auth_token; + } + if (!$has_uagent) { + $new_headers[] = USER_AGENT_HEADER . ": " . USER_AGENT; + } + return $new_headers; + } + + private function _init($conn_type, $force_new=False) + { + if (!array_key_exists($conn_type, $this->connections)) { + $this->error_str = "Invalid CURL_XXX connection type"; + return False; + } + + if (is_null($this->connections[$conn_type]) || $force_new) { + $ch = curl_init(); + } else { + return; + } + + if ($this->dbug) { curl_setopt($ch, CURLOPT_VERBOSE, 1); } + + if (!is_null($this->cabundle_path)) { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, True); + curl_setopt($ch, CURLOPT_CAINFO, $this->cabundle_path); + } + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, True); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_MAXREDIRS, 4); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this, '_header_cb')); + + if ($conn_type == "GET_CALL") { + curl_setopt($ch, CURLOPT_WRITEFUNCTION, array(&$this, '_write_cb')); + } + + if ($conn_type == "PUT_OBJ") { + curl_setopt($ch, CURLOPT_PUT, 1); + curl_setopt($ch, CURLOPT_READFUNCTION, array(&$this, '_read_cb')); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + } + if ($conn_type == "HEAD") { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "HEAD"); + curl_setopt($ch, CURLOPT_NOBODY, 1); + } + if ($conn_type == "PUT_CONT") { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($ch, CURLOPT_INFILESIZE, 0); + curl_setopt($ch, CURLOPT_NOBODY, 1); + } + if ($conn_type == "DEL_POST") { + curl_setopt($ch, CURLOPT_NOBODY, 1); + } + if ($conn_type == "COPY") { + curl_setopt($ch, CURLOPT_NOBODY, 1); + } + $this->connections[$conn_type] = $ch; + return; + } + + private function _reset_callback_vars() + { + $this->_text_list = array(); + $this->_return_list = NULL; + $this->_account_container_count = 0; + $this->_account_bytes_used = 0; + $this->_container_object_count = 0; + $this->_container_bytes_used = 0; + $this->_obj_etag = NULL; + $this->_obj_last_modified = NULL; + $this->_obj_content_type = NULL; + $this->_obj_content_length = NULL; + $this->_obj_metadata = array(); + $this->_obj_manifest = NULL; + $this->_obj_headers = NULL; + $this->_obj_write_string = ""; + $this->_cdn_streaming_uri = NULL; + $this->_cdn_enabled = NULL; + $this->_cdn_ssl_uri = NULL; + $this->_cdn_uri = NULL; + $this->_cdn_ttl = NULL; + $this->response_status = 0; + $this->response_reason = ""; + } + + private function _make_path($t="STORAGE",$c=NULL,$o=NULL) + { + $path = array(); + switch ($t) { + case "STORAGE": + $path[] = $this->storage_url; break; + case "CDN": + $path[] = $this->cdnm_url; break; + } + if ($c == "0") + $path[] = rawurlencode($c); + + if ($c) { + $path[] = rawurlencode($c); + } + if ($o) { + # mimic Python''s urllib.quote() feature of a "safe" '/' character + # + $path[] = str_replace("%2F","/",rawurlencode($o)); + } + return implode("/",$path); + } + + private function _headers(&$obj) + { + $hdrs = self::_process_headers($obj->metadata, $obj->headers); + if ($obj->manifest) + $hdrs[MANIFEST_HEADER] = $obj->manifest; + + return $hdrs; + } + + private function _process_headers($metadata=null, $headers=null) + { + $rules = array( + array( + 'prefix' => METADATA_HEADER_PREFIX, + ), + array( + 'prefix' => '', + 'filter' => array( # key order is important, first match decides + CONTENT_TYPE_HEADER => false, + CONTENT_LENGTH_HEADER => false, + CONTENT_HEADER_PREFIX => true, + ACCESS_CONTROL_HEADER_PREFIX => true, + ORIGIN_HEADER => true, + ), + ), + ); + + $hdrs = array(); + $argc = func_num_args(); + $argv = func_get_args(); + for ($argi = 0; $argi < $argc; $argi++) { + if(!is_array($argv[$argi])) continue; + + $rule = $rules[$argi]; + foreach ($argv[$argi] as $k => $v) { + $k = trim($k); + $v = trim($v); + if (strpos($k, ":") !== False) throw new SyntaxException( + "Header names cannot contain a ':' character."); + + if (array_key_exists('filter', $rule)) { + $result = null; + foreach ($rule['filter'] as $p => $f) { + if (strncasecmp($k, $p, strlen($p)) == 0) { + $result = $f; + break; + } + } + if (!$result) throw new SyntaxException(sprintf( + "Header name %s is not allowed", $k)); + } + + $k = $rule['prefix'] . $k; + if (strlen($k) > MAX_HEADER_NAME_LEN || strlen($v) > MAX_HEADER_VALUE_LEN) + throw new SyntaxException(sprintf( + "Header %s exceeds maximum length: %d/%d", + $k, strlen($k), strlen($v))); + + $hdrs[$k] = $v; + } + } + + return $hdrs; + } + + private function _send_request($conn_type, $url_path, $hdrs=NULL, $method="GET", $force_new=False) + { + $this->_init($conn_type, $force_new); + $this->_reset_callback_vars(); + $headers = $this->_make_headers($hdrs); + + if (gettype($this->connections[$conn_type]) == "unknown type") + throw new ConnectionNotOpenException ( + "Connection is not open." + ); + + switch ($method) { + case "COPY": + curl_setopt($this->connections[$conn_type], + CURLOPT_CUSTOMREQUEST, "COPY"); + break; + case "DELETE": + curl_setopt($this->connections[$conn_type], + CURLOPT_CUSTOMREQUEST, "DELETE"); + break; + case "POST": + curl_setopt($this->connections[$conn_type], + CURLOPT_CUSTOMREQUEST, "POST"); + default: + break; + } + + curl_setopt($this->connections[$conn_type], + CURLOPT_HTTPHEADER, $headers); + + curl_setopt($this->connections[$conn_type], + CURLOPT_URL, $url_path); + + if (!curl_exec($this->connections[$conn_type]) && curl_errno($this->connections[$conn_type]) !== 0) { + $this->error_str = "(curl error: " + . curl_errno($this->connections[$conn_type]) . ") "; + $this->error_str .= curl_error($this->connections[$conn_type]); + return False; + } + return curl_getinfo($this->connections[$conn_type], CURLINFO_HTTP_CODE); + } + + function close() + { + foreach ($this->connections as $cnx) { + if (isset($cnx)) { + curl_close($cnx); + $this->connections[$cnx] = NULL; + } + } + } + private function create_array() + { + $this->_text_list = explode("\n",rtrim($this->_return_list,"\n\x0B")); + return True; + } + +} + +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * c-hanging-comment-ender-p: nil + * End: + */ +?> diff --git a/apps/files_external/appinfo/app.php b/apps/files_external/appinfo/app.php index 95770b44b75..784ed032d47 100644 --- a/apps/files_external/appinfo/app.php +++ b/apps/files_external/appinfo/app.php @@ -9,3 +9,4 @@ OC::$CLASSPATH['OC_Filestorage_FTP']='apps/files_external/lib/ftp.php'; OC::$CLASSPATH['OC_Filestorage_DAV']='apps/files_external/lib/webdav.php'; OC::$CLASSPATH['OC_Filestorage_Google']='apps/files_external/lib/google.php'; +OC::$CLASSPATH['OC_Filestorage_SWIFT']='apps/files_external/lib/swift.php'; diff --git a/apps/files_external/lib/swift.php b/apps/files_external/lib/swift.php new file mode 100644 index 00000000000..ec09742c449 --- /dev/null +++ b/apps/files_external/lib/swift.php @@ -0,0 +1,488 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('php-cloudfiles/cloudfiles.php'); + +class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ + private $host; + private $root; + private $user; + private $token; + private $secure; + /** + * @var CF_Authentication auth + */ + private $auth; + /** + * @var CF_Connection conn + */ + private $conn; + /** + * @var CF_Container rootContainer + */ + private $rootContainer; + + private static $tempFiles=array(); + + const SUBCONTAINER_FILE='.subcontainers'; + + /** + * translate directory path to container name + * @param string path + * @return string + */ + private function getContainerName($path){ + $path=trim($this->root.$path,'/'); + return md5($path); + } + + /** + * get container by path + * @param string path + * @return CF_Container + */ + private function getContainer($path){ + if($path=='' or $path=='/'){ + return $this->rootContainer; + } + try{ + $container=$this->conn->get_container($this->getContainerName($path)); + return $container; + }catch(NoSuchContainerException $e){ + return null; + } + } + + /** + * create container + * @param string path + * @return CF_Container + */ + private function createContainer($path){ + if($path=='' or $path=='/'){ + return $this->conn->create_container($this->getContainerName($path)); + } + $parent=dirname($path); + if($parent=='' or $parent=='/'){ + $parentContainer=$this->rootContainer; + }else{ + if(!$this->containerExists($parent)){ + $parentContainer=$this->createContainer($parent); + }else{ + $parentContainer=$this->getContainer($parent); + } + } + $this->addSubContainer($parentContainer,basename($path)); + return $this->conn->create_container($this->getContainerName($path)); + } + + /** + * get object by path + * @param string path + * @return CF_Object + */ + private function getObject($path){ + $container=$this->getContainer(dirname($path)); + if(is_null($container)){ + return null; + }else{ + try{ + $obj=$container->get_object(basename($path)); + return $obj; + }catch(NoSuchObjectException $e){ + return null; + } + } + } + + /** + * get the names of all objects in a container + * @param CF_Container + * @return array + */ + private function getObjects($container){ + if(is_null($container)){ + return array(); + }else{ + $files=$container->get_objects(); + foreach($files as &$file){ + $file=$file->name; + } + return $files; + } + } + + /** + * create object + * @param string path + * @return CF_Object + */ + private function createObject($path){ + $container=$this->getContainer(dirname($path)); + if(!is_null($container)){ + $container=$this->createContainer($path); + } + return $container->create_object(basename($path)); + } + + /** + * check if an object exists + * @param string + * @return bool + */ + private function objectExists($path){ + return !is_null($this->getObject($path)); + } + + /** + * check if container for path exists + * @param string path + * @return bool + */ + private function containerExists($path){ + return !is_null($this->getContainer($path)); + } + + /** + * get the list of emulated sub containers + * @param CF_Container container + * @return array + */ + private function getSubContainers($container){ + $tmpFile=OC_Helper::tmpFile(); + $obj=$this->getSubContainerFile($container); + try{ + $obj->save_to_filename($tmpFile); + }catch(Exception $e){ + return array(); + } + $obj->save_to_filename($tmpFile); + $containers=file($tmpFile); + unlink($tmpFile); + foreach($containers as &$sub){ + $sub=trim($sub); + } + return $containers; + } + + /** + * add an emulated sub container + * @param CF_Container container + * @param string name + * @return bool + */ + private function addSubContainer($container,$name){ + if(!$name){ + return false; + } + $tmpFile=OC_Helper::tmpFile(); + $obj=$this->getSubContainerFile($container); + try{ + $obj->save_to_filename($tmpFile); + $containers=file($tmpFile); + foreach($containers as &$sub){ + $sub=trim($sub); + } + if(array_search($name,$containers)!==false){ + unlink($tmpFile); + return false; + }else{ + $fh=fopen($tmpFile,'a'); + fwrite($fh,$name."\n"); + } + }catch(Exception $e){ + $containers=array(); + file_put_contents($tmpFile,$name."\n"); + } + + $obj->load_from_filename($tmpFile); + unlink($tmpFile); + return true; + } + + /** + * remove an emulated sub container + * @param CF_Container container + * @param string name + * @return bool + */ + private function removeSubContainer($container,$name){ + if(!$name){ + return false; + } + $tmpFile=OC_Helper::tmpFile(); + $obj=$this->getSubContainerFile($container); + try{ + $obj->save_to_filename($tmpFile); + $containers=file($tmpFile); + }catch(Exception $e){ + return false; + } + foreach($containers as &$sub){ + $sub=trim($sub); + } + $i=array_search($name,$containers); + if($i===false){ + unlink($tmpFile); + return false; + }else{ + unset($containers[$i]); + file_put_contents($tmpFile,implode("\n",$containers)."\n"); + } + + $obj->load_from_filename($tmpFile); + unlink($tmpFile); + return true; + } + + /** + * ensure a subcontainer file exists and return it's object + * @param CF_Container container + * @return CF_Object + */ + private function getSubContainerFile($container){ + try{ + return $container->get_object(self::SUBCONTAINER_FILE); + }catch(NoSuchObjectException $e){ + return $container->create_object(self::SUBCONTAINER_FILE); + } + } + + public function __construct($params){ + $this->token=$params['token']; + $this->host=$params['host']; + $this->user=$params['user']; + $this->root=isset($params['root'])?$params['root']:'/'; + $this->secure=isset($params['secure'])?(bool)$params['secure']:true; + if(substr($this->root,0,1)!='/'){ + $this->root='/'.$this->root; + } + $this->auth = new CF_Authentication($this->user, $this->token, null, $this->host); + $this->auth->authenticate(); + + $this->conn = new CF_Connection($this->auth); + + if(!$this->containerExists($this->root)){ + $this->rootContainer=$this->createContainer('/'); + }else{ + $this->rootContainer=$this->getContainer('/'); + } + } + + + public function mkdir($path){ + if($this->containerExists($path)){ + return false; + }else{ + $this->createContainer($path); + return true; + } + } + + public function rmdir($path){ + if(!$this->containerExists($path)){ + return false; + }else{ + $this->emptyContainer($path); + if($path!='' and $path!='/'){ + $parentContainer=$this->getContainer(dirname($path)); + $this->removeSubContainer($parentContainer,basename($path)); + } + + $this->conn->delete_container($this->getContainerName($path)); + return true; + } + } + + private function emptyContainer($path){ + $container=$this->getContainer($path); + if(is_null($container)){ + return; + } + $subContainers=$this->getSubContainers($container); + foreach($subContainers as $sub){ + if($sub){ + $this->emptyContainer($path.'/'.$sub); + $this->conn->delete_container($this->getContainerName($path.'/'.$sub)); + } + } + + $objects=$this->getObjects($container); + foreach($objects as $object){ + $container->delete_object($object); + } + } + + public function opendir($path){ + $container=$this->getContainer($path); + $files=$this->getObjects($container); + $i=array_search(self::SUBCONTAINER_FILE,$files); + if($i!==false){ + unset($files[$i]); + } + $subContainers=$this->getSubContainers($container); + $files=array_merge($files,$subContainers); + $id=$this->getContainerName($path); + OC_FakeDirStream::$dirs[$id]=$files; + return opendir('fakedir://'.$id); + } + + public function filetype($path){ + if($this->containerExists($path)){ + return 'dir'; + }else{ + return 'file'; + } + } + + public function is_readable($path){ + return true; + } + + public function is_writable($path){ + return true; + } + + public function file_exists($path){ + if($this->is_dir($path)){ + return true; + }else{ + return $this->objectExists($path); + } + } + + public function file_get_contents($path){ + $obj=$this->getObject($path); + if(is_null($obj)){ + return false; + } + return $obj->read(); + } + + public function file_put_contents($path,$content){ + $obj=$this->getObject($path); + if(is_null($obj)){ + $container=$this->getContainer(dirname($path)); + if(is_null($container)){ + return false; + } + $obj=$container->create_object(basename($path)); + } + return $obj->write($content); + } + + public function unlink($path){ + if($this->objectExists($path)){ + $container=$this->getContainer(dirname($path)); + $container->delete_object(basename($path)); + }else{ + return false; + } + } + + public function fopen($path,$mode){ + $obj=$this->getObject($path); + if(is_null($obj)){ + return false; + } + switch($mode){ + case 'r': + case 'rb': + $fp = fopen('php://temp', 'r+'); + $obj->stream($fp); + + rewind($fp); + return $fp; + case 'w': + case 'wb': + case 'a': + case 'ab': + case 'r+': + case 'w+': + case 'wb+': + case 'a+': + case 'x': + case 'x+': + case 'c': + case 'c+': + $tmpFile=$this->getTmpFile($path); + OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); + self::$tempFiles[$tmpFile]=$path; + return fopen('close://'.$tmpFile,$mode); + } + } + + public function writeBack($tmpFile){ + if(isset(self::$tempFiles[$tmpFile])){ + $this->fromTmpFile($tmpFile,self::$tempFiles[$tmpFile]); + unlink($tmpFile); + } + } + + public function free_space($path){ + return 0; + } + + public function touch($path,$mtime=null){ + if(!is_null($mtime)){ + return false; + } + $obj=$this->getObject($path); + if(is_null($obj)){ + return false; + } + $fp = fopen('php://temp', 'r+'); + $obj->stream($fp); + rewind($fp); + $obj->write($fp); + fclose($fp); + } + + public function rename($path1,$path2){ + $sourceContainer=$this->getContainer(dirname($path1)); + $targetContainer=$this->getContainer(dirname($path2)); + return $sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2)); + } + + public function copy($path1,$path2){ + $sourceContainer=$this->getContainer(dirname($path1)); + $targetContainer=$this->getContainer(dirname($path2)); + return $sourceContainer->copy_object_to(basename($path1),$targetContainer,basename($path2)); + } + + public function stat($path){ + $obj=$this->getObject($path); + if(is_null($obj)){ + return false; + } + return array( + 'mtime'=>strtotime($obj->last_modified), + 'size'=>$obj->content_length, + 'ctime'=>-1, + ); + } + + private function getTmpFile($path){ + $obj=$this->getObject($path); + if(!is_null($obj)){ + $tmpFile=OC_Helper::tmpFile(); + $obj->save_to_filename($tmpFile); + return $tmpFile; + }else{ + return false; + } + } + + private function fromTmpFile($tmpFile,$path){ + $obj=$this->getObject($path); + if(is_null($obj)){ + $obj=$this->createObject($path); + } + $obj->load_from_filename($tmpFile); + } +} diff --git a/apps/files_external/tests/config.php b/apps/files_external/tests/config.php index fa4c74a6e26..edbbe9dfec8 100644 --- a/apps/files_external/tests/config.php +++ b/apps/files_external/tests/config.php @@ -21,5 +21,12 @@ return array( 'token'=>'test', 'token_secret'=>'test', 'root'=>'/google', - ) + ), + 'swift'=>array( + 'run'=>true, + 'user'=>'test:tester', + 'token'=>'testing', + 'host'=>'localhost:8080/auth', + 'root'=>'/', + ), ); diff --git a/apps/files_external/tests/swift.php b/apps/files_external/tests/swift.php new file mode 100644 index 00000000000..f0bde6ed605 --- /dev/null +++ b/apps/files_external/tests/swift.php @@ -0,0 +1,32 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +$config=include('apps/files_external/tests/config.php'); +if(!is_array($config) or !isset($config['swift']) or !$config['swift']['run']){ + abstract class Test_Filestorage_SWIFT extends Test_FileStorage{} + return; +}else{ + class Test_Filestorage_SWIFT extends Test_FileStorage { + private $config; + private $id; + + public function setUp(){ + $id=uniqid(); + $this->config=include('apps/files_external/tests/config.php'); + $this->config['swift']['root'].='/'.$id;//make sure we have an new empty folder to work in + $this->instance=new OC_Filestorage_SWIFT($this->config['swift']); + } + + + public function tearDown(){ + $this->instance->rmdir(''); + } + + } +} + -- GitLab From 5cefd3466056475f9433d33a74acba0b3ae092e3 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 19 Apr 2012 00:25:47 +0200 Subject: [PATCH 195/430] emulate touch with custom mtime for swift backend --- apps/files_external/lib/swift.php | 50 ++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/apps/files_external/lib/swift.php b/apps/files_external/lib/swift.php index ec09742c449..e53eb1ff3b6 100644 --- a/apps/files_external/lib/swift.php +++ b/apps/files_external/lib/swift.php @@ -373,6 +373,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ } $obj=$container->create_object(basename($path)); } + $this->resetMTime($obj); return $obj->write($content); } @@ -429,30 +430,39 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ } public function touch($path,$mtime=null){ - if(!is_null($mtime)){ - return false; - } $obj=$this->getObject($path); if(is_null($obj)){ return false; } - $fp = fopen('php://temp', 'r+'); - $obj->stream($fp); - rewind($fp); - $obj->write($fp); - fclose($fp); + if(is_null($mtime)){ + $mtime=time(); + } + + //emulate setting mtime with metadata + $obj->metadata['Mtime']=$mtime; + $obj->sync_metadata(); } public function rename($path1,$path2){ $sourceContainer=$this->getContainer(dirname($path1)); $targetContainer=$this->getContainer(dirname($path2)); - return $sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2)); + $result=$sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2)); + if($result){ + $targetObj=$this->getObject($path2); + $this->resetMTime($targetObj); + } + return $result; } public function copy($path1,$path2){ $sourceContainer=$this->getContainer(dirname($path1)); $targetContainer=$this->getContainer(dirname($path2)); - return $sourceContainer->copy_object_to(basename($path1),$targetContainer,basename($path2)); + $result=$sourceContainer->copy_object_to(basename($path1),$targetContainer,basename($path2)); + if($result){ + $targetObj=$this->getObject($path2); + $this->resetMTime($targetObj); + } + return $result; } public function stat($path){ @@ -460,8 +470,14 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ if(is_null($obj)){ return false; } + + if(isset($obj->metadata['Mtime']) and $obj->metadata['Mtime']>-1){ + $mtime=$obj->metadata['Mtime']; + }else{ + $mtime=strtotime($obj->last_modified); + } return array( - 'mtime'=>strtotime($obj->last_modified), + 'mtime'=>$mtime, 'size'=>$obj->content_length, 'ctime'=>-1, ); @@ -484,5 +500,17 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ $obj=$this->createObject($path); } $obj->load_from_filename($tmpFile); + $this->resetMTime($obj); + } + + /** + * remove custom mtime metadata + * @param CF_Object obj + */ + private function resetMTime($obj){ + if(isset($obj->metadata['Mtime'])){ + $obj->metadata['Mtime']=-1; + $obj->sync_metadata(); + } } } -- GitLab From 9abb70245aecba79d6b99f5006b06ad78399a77a Mon Sep 17 00:00:00 2001 From: Jan-Christoph Borchardt Date: Thu, 19 Apr 2012 16:41:18 +0200 Subject: [PATCH 196/430] showing the file extensions more visible by default. I still think it's shitty design, but I get worse nightmares over thinking that showing file extensions would become a configuration option. --- files/css/files.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/files/css/files.css b/files/css/files.css index 713adf7b5fd..fd551b27625 100644 --- a/files/css/files.css +++ b/files/css/files.css @@ -42,8 +42,8 @@ tbody tr:hover, tbody tr:active, tbody tr.selected { background-color:#f8f8f8; } tbody tr.selected { background-color:#eee; } tbody a { color:#000; } span.extension, td.date { color:#999; } -span.extension { text-transform:lowercase; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter:alpha(opacity=0); opacity:0; -webkit-transition:opacity 300ms; -moz-transition:opacity 300ms; -o-transition:opacity 300ms; transition:opacity 300ms; } -tr:hover span.extension { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; } +span.extension { text-transform:lowercase; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"; filter:alpha(opacity=70); opacity:.7; -webkit-transition:opacity 300ms; -moz-transition:opacity 300ms; -o-transition:opacity 300ms; transition:opacity 300ms; } +tr:hover span.extension { -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter:alpha(opacity=100); opacity:1; color:#777; } div.crumb { float:left; display:block; background:no-repeat right 0; padding:.75em 1.5em 0 1em; height:2.9em; } div.crumb:first-child { padding-left:1em; } div.crumb.last { font-weight:bold; } -- GitLab From 85019887dfed3762025d3fc936a61f085ab4e440 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 19 Apr 2012 16:44:49 +0200 Subject: [PATCH 197/430] add loading of files --- index.php | 7 ++++++- lib/base.php | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/index.php b/index.php index 1858865875b..b85c49c76c2 100644 --- a/index.php +++ b/index.php @@ -57,7 +57,12 @@ elseif(OC_User::isLoggedIn()) { exit(); } else { - OC::loadapp(); + if(is_null(OC::$REQUESTEDFILE)){ + OC::loadapp(); + }else{ + OC::loadfile(); + } + } } diff --git a/lib/base.php b/lib/base.php index c21ab973593..2924a1da182 100644 --- a/lib/base.php +++ b/lib/base.php @@ -276,6 +276,17 @@ class OC{ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP)){ OC_App::loadApps(); require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/index.php'); + }else{ + trigger_error('The requested App was not found.', E_USER_ERROR); + } + } + + public static function loadfile(){ + if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ + OC_App::loadApps(); + require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); + }else{ + header('404 Not Found'); } } -- GitLab From 909282c81edb98db304e1be09c8fd69a350a1cce Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 19 Apr 2012 22:25:21 +0200 Subject: [PATCH 198/430] remove parameters in file var before call require once --- lib/base.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/base.php b/lib/base.php index 2924a1da182..5478f084392 100644 --- a/lib/base.php +++ b/lib/base.php @@ -283,10 +283,9 @@ class OC{ public static function loadfile(){ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ - OC_App::loadApps(); require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); }else{ - header('404 Not Found'); + header('404 Not found'); } } @@ -401,7 +400,12 @@ class OC{ register_shutdown_function(array('OC_Helper','cleanTmp')); self::$REQUESTEDAPP = (isset($_GET['app'])?strip_tags($_GET['app']):'files'); - self::$REQUESTEDFILE = (isset($_GET['file'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . $_GET['file'], OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?$_GET['file']:null):null); + self::$REQUESTEDFILE = $_GET['file']; + if(substr_count(self::$REQUESTEDFILE, '?') != 0){ + $pos = strpos(self::$REQUESTEDFILE, '?'); + self::$REQUESTEDFILE = substr(self::$REQUESTEDFILE, 0, $pos); + } + self::$REQUESTEDFILE = (isset($_GET['file'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . self::$REQUESTEDFILE, OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?self::$REQUESTEDFILE:null):null); } } -- GitLab From 2e8531370102b33a072c6b981d2b1e6a1c9cf40e Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 19 Apr 2012 22:26:36 +0200 Subject: [PATCH 199/430] optimize code --- index.php | 1 + lib/base.php | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/index.php b/index.php index b85c49c76c2..a3835c6d2f3 100644 --- a/index.php +++ b/index.php @@ -57,6 +57,7 @@ elseif(OC_User::isLoggedIn()) { exit(); } else { + OC_App::loadApps(); if(is_null(OC::$REQUESTEDFILE)){ OC::loadapp(); }else{ diff --git a/lib/base.php b/lib/base.php index 5478f084392..fa5287631d8 100644 --- a/lib/base.php +++ b/lib/base.php @@ -274,7 +274,6 @@ class OC{ public static function loadapp(){ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP)){ - OC_App::loadApps(); require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/index.php'); }else{ trigger_error('The requested App was not found.', E_USER_ERROR); -- GitLab From 2fbc92bd4bfd69ef7f9c23a620f28daaef83086f Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Fri, 20 Apr 2012 20:49:35 +0200 Subject: [PATCH 200/430] new OC_Mail class to handle all mail sending. The benefit is that is way mor flexible than the standard mail command. can be configured to use a remote smtp relay for example. also port the lostpassword code --- config/config.sample.php | 5 ++ core/lostpassword/index.php | 5 +- lib/mail.php | 116 ++++++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 lib/mail.php diff --git a/config/config.sample.php b/config/config.sample.php index 199c9248c51..9f6d674fc0e 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -19,6 +19,11 @@ $CONFIG = array( "knowledgebaseurl" => "", "appstoreenabled" => true, "appstoreurl" => "", +"mail_smtpmode" => "sendmail", +"mail_smtphost" => "127.0.0.1", +"mail_smtpauth" => "false", +"mail_smtpname" => "", +"mail_smtppassword" => "", // "datadirectory" => "" ); ?> diff --git a/core/lostpassword/index.php b/core/lostpassword/index.php index 89bb6cfa794..b6cdd601d66 100644 --- a/core/lostpassword/index.php +++ b/core/lostpassword/index.php @@ -22,7 +22,10 @@ if (isset($_POST['user'])) { $msg = $tmpl->fetchPage(); $l = OC_L10N::get('core'); $from = 'lostpassword-noreply@' . $_SERVER['HTTP_HOST']; - mail($email, $l->t('Owncloud password reset'), $msg, 'From:' . $from); + $r=mail($email, $l->t('Owncloud password reset'), $msg, 'From:' . $from); +//if($r==false) echo('error'); else echo('works!!!!!!!'); + OC_MAIL::send($email,$_POST['user'],$l->t('Owncloud password reset'),$msg,$from,'ownCloud'); + } OC_Template::printGuestPage('core/lostpassword', 'lostpassword', array('error' => false, 'requested' => true)); } else { diff --git a/lib/mail.php b/lib/mail.php new file mode 100644 index 00000000000..0045f8de6da --- /dev/null +++ b/lib/mail.php @@ -0,0 +1,116 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * OC_Mail + * + * A class to handle mail sending. + */ + +require_once('class.phpmailer.php'); + +class OC_Mail { + + /** + * send an email + * + * @param string $toaddress + * @param string $toname + * @param string $subject + * @param string $mailtext + * @param string $fromaddress + * @param string $fromname + * @param bool $html + */ + public static function send($toaddress,$toname,$subject,$mailtext,$fromaddress,$fromname,$html=0,$altbody='',$ccaddress='',$ccname='',$bcc='') { + + $SMTPMODE = OC_Config::getValue( 'mail_smtpmode', 'sendmail' ); + $SMTPHOST = OC_Config::getValue( 'mail_smtphost', '127.0.0.1' ); + $SMTPAUTH = OC_Config::getValue( 'mail_smtpauth', 'false' ); + $SMTPUSERNAME = OC_Config::getValue( 'mail_smtpname', '' ); + $SMTPPASSWORD = OC_Config::getValue( 'mail_smtppassword', '' ); + + + $mailo = new PHPMailer(); + if($SMTPMODE=='sendmail') { + $mailo->IsSendmail(); + }elseif($SMTPMODE=='smtp'){ + $mailo->IsSMTP(); + }elseif($SMTPMODE=='qmail'){ + $mailo->IsQmail(); + }else{ + $mailo->IsMail(); + } + + + $mailo->Host = $SMTPHOST; + $mailo->SMTPAuth = $SMTPAUTH; + $mailo->Username = $SMTPUSERNAME; + $mailo->Password = $SMTPPASSWORD; + + $mailo->From =$fromaddress; + $mailo->FromName = $fromname;; + $a=explode(' ',$toaddress); + foreach($a as $ad) { + $mailo->AddAddress($ad,$toname); + } + + if($ccaddress<>'') $mailo->AddCC($ccaddress,$ccname); + if($bcc<>'') $mailo->AddBCC($bcc); + + $mailo->AddReplyTo($fromaddress, $fromname); + + $mailo->WordWrap = 50; + if($html==1) $mailo->IsHTML(true); else $mailo->IsHTML(false); + + $mailo->Subject = $subject; + if($altbody=='') { + $mailo->Body = $mailtext.OC_MAIL::getfooter(); + $mailo->AltBody = ''; + }else{ + $mailo->Body = $mailtext; + $mailo->AltBody = $altbody; + } + $mailo->CharSet = 'UTF-8'; + + $mailo->Send(); + unset($mailo); + + OC_Log::write('Mail from '.$fromname.' ('.$fromaddress.')'.' to: '.$toname.'('.$toaddress.')'.' subject: '.$subject,'mail',OC_Log::DEBUG); + + } + + + + /** + * sending a mail based on a template + * + * @param texttemplate $texttemplate + * @param htmltemplate $htmltemplate + * @param data $data + * @param To $toaddress + * @param ToName $toname + * @param Subject $subject + * @param From $fromaddress + * @param FromName $fromname + * @param ccaddress $ccaddress + * @param ccname $ccname + * @param bcc $bcc + */ + public static function getfooter() { + + $txt="\n--\n"; + $txt.="ownCloud\n"; + $txt.="Your Cloud, Your Data, Your Way!\n"; + return($txt); + + } + + + +} -- GitLab From c3cb000cb23ef9e17f0443b16f2291a0a885126c Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Fri, 20 Apr 2012 20:53:36 +0200 Subject: [PATCH 201/430] add phpmailer to 3rdparty --- 3rdparty/class.phpmailer.php | 2473 ++++++++++++++++++++++++++++++++++ 3rdparty/class.smtp.php | 817 +++++++++++ 2 files changed, 3290 insertions(+) create mode 100644 3rdparty/class.phpmailer.php create mode 100644 3rdparty/class.smtp.php diff --git a/3rdparty/class.phpmailer.php b/3rdparty/class.phpmailer.php new file mode 100644 index 00000000000..4589cd791e9 --- /dev/null +++ b/3rdparty/class.phpmailer.php @@ -0,0 +1,2473 @@ +exceptions = ($exceptions == true); + } + + /** + * Sets message type to HTML. + * @param bool $ishtml + * @return void + */ + public function IsHTML($ishtml = true) { + if ($ishtml) { + $this->ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Sets Mailer to send message using SMTP. + * @return void + */ + public function IsSMTP() { + $this->Mailer = 'smtp'; + } + + /** + * Sets Mailer to send message using PHP mail() function. + * @return void + */ + public function IsMail() { + $this->Mailer = 'mail'; + } + + /** + * Sets Mailer to send message using the $Sendmail program. + * @return void + */ + public function IsSendmail() { + if (!stristr(ini_get('sendmail_path'), 'sendmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Sets Mailer to send message using the qmail MTA. + * @return void + */ + public function IsQmail() { + if (stristr(ini_get('sendmail_path'), 'qmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + ///////////////////////////////////////////////// + // METHODS, RECIPIENTS + ///////////////////////////////////////////////// + + /** + * Adds a "To" address. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddAddress($address, $name = '') { + return $this->AddAnAddress('to', $address, $name); + } + + /** + * Adds a "Cc" address. + * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddCC($address, $name = '') { + return $this->AddAnAddress('cc', $address, $name); + } + + /** + * Adds a "Bcc" address. + * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddBCC($address, $name = '') { + return $this->AddAnAddress('bcc', $address, $name); + } + + /** + * Adds a "Reply-to" address. + * @param string $address + * @param string $name + * @return boolean + */ + public function AddReplyTo($address, $name = '') { + return $this->AddAnAddress('ReplyTo', $address, $name); + } + + /** + * Adds an address to one of the recipient arrays + * Addresses that have been added already return false, but do not throw exceptions + * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' + * @param string $address The email address to send to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + * @access protected + */ + protected function AddAnAddress($kind, $address, $name = '') { + if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) { + $this->SetError($this->Lang('Invalid recipient array').': '.$kind); + if ($this->exceptions) { + throw new phpmailerException('Invalid recipient array: ' . $kind); + } + echo $this->Lang('Invalid recipient array').': '.$kind; + return false; + } + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!self::ValidateAddress($address)) { + $this->SetError($this->Lang('invalid_address').': '. $address); + if ($this->exceptions) { + throw new phpmailerException($this->Lang('invalid_address').': '.$address); + } + echo $this->Lang('invalid_address').': '.$address; + return false; + } + if ($kind != 'ReplyTo') { + if (!isset($this->all_recipients[strtolower($address)])) { + array_push($this->$kind, array($address, $name)); + $this->all_recipients[strtolower($address)] = true; + return true; + } + } else { + if (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = array($address, $name); + return true; + } + } + return false; +} + +/** + * Set the From and FromName properties + * @param string $address + * @param string $name + * @return boolean + */ + public function SetFrom($address, $name = '', $auto = 1) { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!self::ValidateAddress($address)) { + $this->SetError($this->Lang('invalid_address').': '. $address); + if ($this->exceptions) { + throw new phpmailerException($this->Lang('invalid_address').': '.$address); + } + echo $this->Lang('invalid_address').': '.$address; + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto) { + if (empty($this->ReplyTo)) { + $this->AddAnAddress('ReplyTo', $address, $name); + } + if (empty($this->Sender)) { + $this->Sender = $address; + } + } + return true; + } + + /** + * Check that a string looks roughly like an email address should + * Static so it can be used without instantiation + * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator + * Conforms approximately to RFC2822 + * @link http://www.hexillion.com/samples/#Regex Original pattern found here + * @param string $address The email address to check + * @return boolean + * @static + * @access public + */ + public static function ValidateAddress($address) { + if (function_exists('filter_var')) { //Introduced in PHP 5.2 + if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { + return false; + } else { + return true; + } + } else { + return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); + } + } + + ///////////////////////////////////////////////// + // METHODS, MAIL SENDING + ///////////////////////////////////////////////// + + /** + * Creates message and assigns Mailer. If the message is + * not sent successfully then it returns false. Use the ErrorInfo + * variable to view description of the error. + * @return bool + */ + public function Send() { + try { + if(!$this->PreSend()) return false; + return $this->PostSend(); + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + protected function PreSend() { + try { + if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); + } + + // Set whether the message is multipart/alternative + if(!empty($this->AltBody)) { + $this->ContentType = 'multipart/alternative'; + } + + $this->error_count = 0; // reset errors + $this->SetMessageType(); + //Refuse to send an empty message + if (empty($this->Body)) { + throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); + } + + $this->MIMEHeader = $this->CreateHeader(); + $this->MIMEBody = $this->CreateBody(); + + + // digitally sign with DKIM if enabled + if ($this->DKIM_domain && $this->DKIM_private) { + $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); + $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; + } + + return true; + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + return false; + } + } + + protected function PostSend() { + try { + // Choose the mailer and send through it + switch($this->Mailer) { + case 'sendmail': + return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); + default: + return $this->MailSend($this->MIMEHeader, $this->MIMEBody); + } + + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + echo $e->getMessage()."\n"; + return false; + } + } + + /** + * Sends mail using the $Sendmail program. + * @param string $header The message headers + * @param string $body The message body + * @access protected + * @return bool + */ + protected function SendmailSend($header, $body) { + if ($this->Sender != '') { + $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); + } else { + $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); + } + if ($this->SingleTo === true) { + foreach ($this->SingleToArray as $key => $val) { + if(!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, "To: " . $val . "\n"); + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); + if($result != 0) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + if(!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); + if($result != 0) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + return true; + } + + /** + * Sends mail using the PHP mail() function. + * @param string $header The message headers + * @param string $body The message body + * @access protected + * @return bool + */ + protected function MailSend($header, $body) { + $toArr = array(); + foreach($this->to as $t) { + $toArr[] = $this->AddrFormat($t); + } + $to = implode(', ', $toArr); + + if (empty($this->Sender)) { + $params = "-oi -f %s"; + } else { + $params = sprintf("-oi -f %s", $this->Sender); + } + if ($this->Sender != '' and !ini_get('safe_mode')) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); + } + } else { + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); + } + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if(!$rt) { + throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); + } + return true; + } + + /** + * Sends mail via SMTP using PhpSMTP + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * @param string $header The message headers + * @param string $body The message body + * @uses SMTP + * @access protected + * @return bool + */ + protected function SmtpSend($header, $body) { + require_once $this->PluginDir . 'class.smtp.php'; + $bad_rcpt = array(); + + if(!$this->SmtpConnect()) { + throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; + if(!$this->smtp->Mail($smtp_from)) { + throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL); + } + + // Attempt to send attach all recipients + foreach($this->to as $to) { + if (!$this->smtp->Recipient($to[0])) { + $bad_rcpt[] = $to[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); + } + } + foreach($this->cc as $cc) { + if (!$this->smtp->Recipient($cc[0])) { + $bad_rcpt[] = $cc[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); + } + } + foreach($this->bcc as $bcc) { + if (!$this->smtp->Recipient($bcc[0])) { + $bad_rcpt[] = $bcc[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); + } + } + + + if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses + $badaddresses = implode(', ', $bad_rcpt); + throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); + } + if(!$this->smtp->Data($header . $body)) { + throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); + } + if($this->SMTPKeepAlive == true) { + $this->smtp->Reset(); + } + return true; + } + + /** + * Initiates a connection to an SMTP server. + * Returns false if the operation failed. + * @uses SMTP + * @access public + * @return bool + */ + public function SmtpConnect() { + if(is_null($this->smtp)) { + $this->smtp = new SMTP(); + } + + $this->smtp->do_debug = $this->SMTPDebug; + $hosts = explode(';', $this->Host); + $index = 0; + $connection = $this->smtp->Connected(); + + // Retry while there is no connection + try { + while($index < count($hosts) && !$connection) { + $hostinfo = array(); + if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { + $host = $hostinfo[1]; + $port = $hostinfo[2]; + } else { + $host = $hosts[$index]; + $port = $this->Port; + } + + $tls = ($this->SMTPSecure == 'tls'); + $ssl = ($this->SMTPSecure == 'ssl'); + + if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { + + $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); + $this->smtp->Hello($hello); + + if ($tls) { + if (!$this->smtp->StartTLS()) { + throw new phpmailerException($this->Lang('tls')); + } + + //We must resend HELO after tls negotiation + $this->smtp->Hello($hello); + } + + $connection = true; + if ($this->SMTPAuth) { + if (!$this->smtp->Authenticate($this->Username, $this->Password)) { + throw new phpmailerException($this->Lang('authenticate')); + } + } + } + $index++; + if (!$connection) { + throw new phpmailerException($this->Lang('connect_host')); + } + } + } catch (phpmailerException $e) { + $this->smtp->Reset(); + throw $e; + } + return true; + } + + /** + * Closes the active SMTP session if one exists. + * @return void + */ + public function SmtpClose() { + if(!is_null($this->smtp)) { + if($this->smtp->Connected()) { + $this->smtp->Quit(); + $this->smtp->Close(); + } + } + } + + /** + * Sets the language for all class error messages. + * Returns false if it cannot load the language file. The default language is English. + * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") + * @param string $lang_path Path to the language file directory + * @access public + */ + function SetLanguage($langcode = 'en', $lang_path = 'language/') { + //Define full set of translatable strings + $PHPMAILER_LANG = array( + 'provide_address' => 'You must provide at least one recipient email address.', + 'mailer_not_supported' => ' mailer is not supported.', + 'execute' => 'Could not execute: ', + 'instantiate' => 'Could not instantiate mail function.', + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'from_failed' => 'The following From address failed: ', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'data_not_accepted' => 'SMTP Error: Data not accepted.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'encoding' => 'Unknown encoding: ', + 'signing' => 'Signing Error: ', + 'smtp_error' => 'SMTP server error: ', + 'empty_message' => 'Message body empty', + 'invalid_address' => 'Invalid address', + 'variable_set' => 'Cannot set or reset variable: ' + ); + //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! + $l = true; + if ($langcode != 'en') { //There is no English translation file + $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; + } + $this->language = $PHPMAILER_LANG; + return ($l == true); //Returns false if language not found + } + + /** + * Return the current array of language strings + * @return array + */ + public function GetTranslations() { + return $this->language; + } + + ///////////////////////////////////////////////// + // METHODS, MESSAGE CREATION + ///////////////////////////////////////////////// + + /** + * Creates recipient headers. + * @access public + * @return string + */ + public function AddrAppend($type, $addr) { + $addr_str = $type . ': '; + $addresses = array(); + foreach ($addr as $a) { + $addresses[] = $this->AddrFormat($a); + } + $addr_str .= implode(', ', $addresses); + $addr_str .= $this->LE; + + return $addr_str; + } + + /** + * Formats an address correctly. + * @access public + * @return string + */ + public function AddrFormat($addr) { + if (empty($addr[1])) { + return $this->SecureHeader($addr[0]); + } else { + return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; + } + } + + /** + * Wraps message for use with mailers that do not + * automatically perform wrapping and for quoted-printable. + * Original written by philippe. + * @param string $message The message to wrap + * @param integer $length The line length to wrap to + * @param boolean $qp_mode Whether to run in Quoted-Printable mode + * @access public + * @return string + */ + public function WrapText($message, $length, $qp_mode = false) { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == "utf-8"); + + $message = $this->FixEOL($message); + if (substr($message, -1) == $this->LE) { + $message = substr($message, 0, -1); + } + + $line = explode($this->LE, $message); + $message = ''; + for ($i = 0 ;$i < count($line); $i++) { + $line_part = explode(' ', $line[$i]); + $buf = ''; + for ($e = 0; $e $length)) { + $space_left = $length - strlen($buf) - 1; + if ($e != 0) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf("=%s", $this->LE); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + $len = $length; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf("=%s", $this->LE); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (' ' . $word); + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . $this->LE; + } + + return $message; + } + + /** + * Finds last character boundary prior to maxLength in a utf-8 + * quoted (printable) encoded string. + * Original written by Colin Brown. + * @access public + * @param string $encodedText utf-8 QP text + * @param int $maxLength find last character boundary prior to this length + * @return int + */ + public function UTF8CharBoundary($encodedText, $maxLength) { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, "="); + if ($encodedCharPos !== false) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + $maxLength = ($encodedCharPos == 0) ? $maxLength : + $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec >= 192) { // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + + /** + * Set the body wrapping. + * @access public + * @return void + */ + public function SetWordWrap() { + if($this->WordWrap < 1) { + return; + } + + switch($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->WrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assembles message header. + * @access public + * @return string The assembled header + */ + public function CreateHeader() { + $result = ''; + + // Set the boundaries + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = 'b1_' . $uniq_id; + $this->boundary[2] = 'b2_' . $uniq_id; + $this->boundary[3] = 'b3_' . $uniq_id; + + $result .= $this->HeaderLine('Date', self::RFCDate()); + if($this->Sender == '') { + $result .= $this->HeaderLine('Return-Path', trim($this->From)); + } else { + $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); + } + + // To be created automatically by mail() + if($this->Mailer != 'mail') { + if ($this->SingleTo === true) { + foreach($this->to as $t) { + $this->SingleToArray[] = $this->AddrFormat($t); + } + } else { + if(count($this->to) > 0) { + $result .= $this->AddrAppend('To', $this->to); + } elseif (count($this->cc) == 0) { + $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); + } + } + } + + $from = array(); + $from[0][0] = trim($this->From); + $from[0][1] = $this->FromName; + $result .= $this->AddrAppend('From', $from); + + // sendmail and mail() extract Cc from the header before sending + if(count($this->cc) > 0) { + $result .= $this->AddrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { + $result .= $this->AddrAppend('Bcc', $this->bcc); + } + + if(count($this->ReplyTo) > 0) { + $result .= $this->AddrAppend('Reply-to', $this->ReplyTo); + } + + // mail() sets the subject itself + if($this->Mailer != 'mail') { + $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); + } + + if($this->MessageID != '') { + $result .= $this->HeaderLine('Message-ID', $this->MessageID); + } else { + $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); + } + $result .= $this->HeaderLine('X-Priority', $this->Priority); + if($this->XMailer) { + $result .= $this->HeaderLine('X-Mailer', $this->XMailer); + } else { + $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)'); + } + + if($this->ConfirmReadingTo != '') { + $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); + } + + // Add custom headers + for($index = 0; $index < count($this->CustomHeader); $index++) { + $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); + } + if (!$this->sign_key_file) { + $result .= $this->HeaderLine('MIME-Version', '1.0'); + $result .= $this->GetMailMIME(); + } + + return $result; + } + + /** + * Returns the message MIME. + * @access public + * @return string + */ + public function GetMailMIME() { + $result = ''; + switch($this->message_type) { + case 'plain': + $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); + $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"'); + break; + case 'inline': + $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + } + + if($this->Mailer != 'mail') { + $result .= $this->LE.$this->LE; + } + + return $result; + } + + /** + * Assembles the message body. Returns an empty string on failure. + * @access public + * @return string The assembled message body + */ + public function CreateBody() { + $body = ''; + + if ($this->sign_key_file) { + $body .= $this->GetMailMIME(); + } + + $this->SetWordWrap(); + + switch($this->message_type) { + case 'plain': + $body .= $this->EncodeString($this->Body, $this->Encoding); + break; + case 'inline': + $body .= $this->GetBoundary($this->boundary[1], '', '', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->AttachAll("inline", $this->boundary[1]); + break; + case 'attach': + $body .= $this->GetBoundary($this->boundary[1], '', '', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->AttachAll("attachment", $this->boundary[1]); + break; + case 'inline_attach': + $body .= $this->TextLine("--" . $this->boundary[1]); + $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); + $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', '', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->AttachAll("inline", $this->boundary[2]); + $body .= $this->LE; + $body .= $this->AttachAll("attachment", $this->boundary[1]); + break; + case 'alt': + $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->EndBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->TextLine("--" . $this->boundary[1]); + $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); + $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->AttachAll("inline", $this->boundary[2]); + $body .= $this->LE; + $body .= $this->EndBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $this->TextLine("--" . $this->boundary[1]); + $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); + $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->EndBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->AttachAll("attachment", $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $this->TextLine("--" . $this->boundary[1]); + $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); + $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->TextLine("--" . $this->boundary[2]); + $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); + $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"'); + $body .= $this->LE; + $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->AttachAll("inline", $this->boundary[3]); + $body .= $this->LE; + $body .= $this->EndBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->AttachAll("attachment", $this->boundary[1]); + break; + } + + if ($this->IsError()) { + $body = ''; + } elseif ($this->sign_key_file) { + try { + $file = tempnam('', 'mail'); + file_put_contents($file, $body); //TODO check this worked + $signed = tempnam("", "signed"); + if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) { + @unlink($file); + @unlink($signed); + $body = file_get_contents($signed); + } else { + @unlink($file); + @unlink($signed); + throw new phpmailerException($this->Lang("signing").openssl_error_string()); + } + } catch (phpmailerException $e) { + $body = ''; + if ($this->exceptions) { + throw $e; + } + } + } + + return $body; + } + + /** + * Returns the start of a message boundary. + * @access protected + * @return string + */ + protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { + $result = ''; + if($charSet == '') { + $charSet = $this->CharSet; + } + if($contentType == '') { + $contentType = $this->ContentType; + } + if($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->TextLine('--' . $boundary); + $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet); + $result .= $this->LE; + $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Returns the end of a message boundary. + * @access protected + * @return string + */ + protected function EndBoundary($boundary) { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Sets the message type. + * @access protected + * @return void + */ + protected function SetMessageType() { + $this->message_type = array(); + if($this->AlternativeExists()) $this->message_type[] = "alt"; + if($this->InlineImageExists()) $this->message_type[] = "inline"; + if($this->AttachmentExists()) $this->message_type[] = "attach"; + $this->message_type = implode("_", $this->message_type); + if($this->message_type == "") $this->message_type = "plain"; + } + + /** + * Returns a formatted header line. + * @access public + * @return string + */ + public function HeaderLine($name, $value) { + return $name . ': ' . $value . $this->LE; + } + + /** + * Returns a formatted mail line. + * @access public + * @return string + */ + public function TextLine($value) { + return $value . $this->LE; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, ATTACHMENTS + ///////////////////////////////////////////////// + + /** + * Adds an attachment from a path on the filesystem. + * Returns false if the file could not be found + * or accessed. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + try { + if ( !@is_file($path) ) { + throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); + } + $filename = basename($path); + if ( $name == '' ) { + $name = $filename; + } + + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => 'attachment', + 7 => 0 + ); + + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + echo $e->getMessage()."\n"; + if ( $e->getCode() == self::STOP_CRITICAL ) { + return false; + } + } + return true; + } + + /** + * Return the current array of attachments + * @return array + */ + public function GetAttachments() { + return $this->attachment; + } + + /** + * Attaches all fs, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access protected + * @return string + */ + protected function AttachAll($disposition_type, $boundary) { + // Return text of body + $mime = array(); + $cidUniq = array(); + $incl = array(); + + // Add all attachments + foreach ($this->attachment as $attachment) { + // CHECK IF IT IS A VALID DISPOSITION_FILTER + if($attachment[6] == $disposition_type) { + // Check for string attachment + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = md5(serialize($attachment)); + if (in_array($inclhash, $incl)) { continue; } + $incl[] = $inclhash; + $filename = $attachment[1]; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } + $cidUniq[$cid] = true; + + $mime[] = sprintf("--%s%s", $boundary, $this->LE); + $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if($disposition == 'inline') { + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + } + + $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); + + // Encode as string attachment + if($bString) { + $mime[] = $this->EncodeString($string, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } else { + $mime[] = $this->EncodeFile($path, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } + } + } + + $mime[] = sprintf("--%s--%s", $boundary, $this->LE); + + return implode("", $mime); + } + + /** + * Encodes attachment in requested format. + * Returns an empty string on failure. + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @see EncodeFile() + * @access protected + * @return string + */ + protected function EncodeFile($path, $encoding = 'base64') { + try { + if (!is_readable($path)) { + throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); + } + if (function_exists('get_magic_quotes')) { + function get_magic_quotes() { + return false; + } + } + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + $magic_quotes = get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + } + $file_buffer = file_get_contents($path); + $file_buffer = $this->EncodeString($file_buffer, $encoding); + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime($magic_quotes); + } + return $file_buffer; + } catch (Exception $e) { + $this->SetError($e->getMessage()); + return ''; + } + } + + /** + * Encodes string to requested format. + * Returns an empty string on failure. + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @access public + * @return string + */ + public function EncodeString($str, $encoding = 'base64') { + $encoded = ''; + switch(strtolower($encoding)) { + case 'base64': + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->FixEOL($str); + //Make sure it ends with a line break + if (substr($encoded, -(strlen($this->LE))) != $this->LE) + $encoded .= $this->LE; + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->EncodeQP($str); + break; + default: + $this->SetError($this->Lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string to best (shortest) of Q, B, quoted or none. + * @access public + * @return string + */ + public function EncodeHeader($str, $position = 'text') { + $x = 0; + + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know what value has magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + // Fall-through + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) { + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if (strlen($str)/3 < $x) { + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->Base64EncodeWrapMB($str); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->EncodeQ($str, $position); + $encoded = $this->WrapText($encoded, $maxlen, true); + $encoded = str_replace('='.$this->LE, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Checks if a string contains multibyte characters. + * @access public + * @param string $str multi-byte text to wrap encode + * @return bool + */ + public function HasMultiBytes($str) { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + } + + /** + * Correctly encodes and wraps long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php + * @access public + * @param string $str multi-byte text to wrap encode + * @return string + */ + public function Base64EncodeWrapMB($str) { + $start = "=?".$this->CharSet."?B?"; + $end = "?="; + $encoded = ""; + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $offset = $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } + while (strlen($chunk) > $length); + + $encoded .= $chunk . $this->LE; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($this->LE)); + return $encoded; + } + + /** + * Encode string to quoted-printable. + * Only uses standard PHP, slow, but will always work + * @access public + * @param string $string the text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @return string + */ + public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) { + $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); + $lines = preg_split('/(?:\r\n|\r|\n)/', $input); + $eol = "\r\n"; + $escape = '='; + $output = ''; + while( list(, $line) = each($lines) ) { + $linlen = strlen($line); + $newline = ''; + for($i = 0; $i < $linlen; $i++) { + $c = substr( $line, $i, 1 ); + $dec = ord( $c ); + if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E + $c = '=2E'; + } + if ( $dec == 32 ) { + if ( $i == ( $linlen - 1 ) ) { // convert space at eol only + $c = '=20'; + } else if ( $space_conv ) { + $c = '=20'; + } + } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required + $h2 = floor($dec/16); + $h1 = floor($dec%16); + $c = $escape.$hex[$h2].$hex[$h1]; + } + if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted + $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay + $newline = ''; + // check if newline first character will be point or not + if ( $dec == 46 ) { + $c = '=2E'; + } + } + $newline .= $c; + } // end of for + $output .= $newline.$eol; + } // end of while + return $output; + } + + /** + * Encode string to RFC2045 (6.7) quoted-printable format + * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version + * Also results in same content as you started with after decoding + * @see EncodeQPphp() + * @access public + * @param string $string the text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function + * @return string + * @author Marcus Bointon + */ + public function EncodeQP($string, $line_max = 76, $space_conv = false) { + if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) + return quoted_printable_encode($string); + } + $filters = stream_get_filters(); + if (!in_array('convert.*', $filters)) { //Got convert stream filter? + return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation + } + $fp = fopen('php://temp/', 'r+'); + $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks + $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); + $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); + fputs($fp, $string); + rewind($fp); + $out = stream_get_contents($fp); + stream_filter_remove($s); + $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange + fclose($fp); + return $out; + } + + /** + * Encode string to q encoding. + * @link http://tools.ietf.org/html/rfc2047 + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * @access public + * @return string + */ + public function EncodeQ($str, $position = 'text') { + // There should not be any EOL in the string + $encoded = preg_replace('/[\r\n]*/', '', $str); + + switch (strtolower($position)) { + case 'phrase': + $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + break; + case 'comment': + $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + case 'text': + default: + // Replace every high ascii, control =, ? and _ characters + //TODO using /e (equivalent to eval()) is probably not a good idea + $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', + "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded); + break; + } + + // Replace every spaces to _ (more readable than =20) + $encoded = str_replace(' ', '_', $encoded); + + return $encoded; + } + + /** + * Adds a string or binary attachment (non-filesystem) to the list. + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return void + */ + public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => 'attachment', + 7 => 0 + ); + } + + /** + * Adds an embedded attachment. This can include images, sounds, and + * just about any other document. Make sure to set the $type to an + * image type. For JPEG images use "image/jpeg" and for GIF images + * use "image/gif". + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment. Use this to identify + * the Id for accessing the image in an HTML form. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + + if ( !@is_file($path) ) { + $this->SetError($this->Lang('file_access') . $path); + return false; + } + + $filename = basename($path); + if ( $name == '' ) { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => 'inline', + 7 => $cid + ); + + return true; + } + + public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') { + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => 'inline', + 7 => $cid + ); + } + + /** + * Returns true if an inline attachment is present. + * @access public + * @return bool + */ + public function InlineImageExists() { + foreach($this->attachment as $attachment) { + if ($attachment[6] == 'inline') { + return true; + } + } + return false; + } + + public function AttachmentExists() { + foreach($this->attachment as $attachment) { + if ($attachment[6] == 'attachment') { + return true; + } + } + return false; + } + + public function AlternativeExists() { + return strlen($this->AltBody)>0; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MESSAGE RESET + ///////////////////////////////////////////////// + + /** + * Clears all recipients assigned in the TO array. Returns void. + * @return void + */ + public function ClearAddresses() { + foreach($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = array(); + } + + /** + * Clears all recipients assigned in the CC array. Returns void. + * @return void + */ + public function ClearCCs() { + foreach($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = array(); + } + + /** + * Clears all recipients assigned in the BCC array. Returns void. + * @return void + */ + public function ClearBCCs() { + foreach($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = array(); + } + + /** + * Clears all recipients assigned in the ReplyTo array. Returns void. + * @return void + */ + public function ClearReplyTos() { + $this->ReplyTo = array(); + } + + /** + * Clears all recipients assigned in the TO, CC and BCC + * array. Returns void. + * @return void + */ + public function ClearAllRecipients() { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + $this->all_recipients = array(); + } + + /** + * Clears all previously set filesystem, string, and binary + * attachments. Returns void. + * @return void + */ + public function ClearAttachments() { + $this->attachment = array(); + } + + /** + * Clears all custom headers. Returns void. + * @return void + */ + public function ClearCustomHeaders() { + $this->CustomHeader = array(); + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MISCELLANEOUS + ///////////////////////////////////////////////// + + /** + * Adds the error message to the error container. + * @access protected + * @return void + */ + protected function SetError($msg) { + $this->error_count++; + if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { + $msg .= '

    ' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

    \n"; + } + } + $this->ErrorInfo = $msg; + } + + /** + * Returns the proper RFC 822 formatted date. + * @access public + * @return string + * @static + */ + public static function RFCDate() { + $tz = date('Z'); + $tzs = ($tz < 0) ? '-' : '+'; + $tz = abs($tz); + $tz = (int)($tz/3600)*100 + ($tz%3600)/60; + $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); + + return $result; + } + + /** + * Returns the server hostname or 'localhost.localdomain' if unknown. + * @access protected + * @return string + */ + protected function ServerHostname() { + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER['SERVER_NAME'])) { + $result = $_SERVER['SERVER_NAME']; + } else { + $result = 'localhost.localdomain'; + } + + return $result; + } + + /** + * Returns a message in the appropriate language. + * @access protected + * @return string + */ + protected function Lang($key) { + if(count($this->language) < 1) { + $this->SetLanguage('en'); // set the default language + } + + if(isset($this->language[$key])) { + return $this->language[$key]; + } else { + return 'Language string failed to load: ' . $key; + } + } + + /** + * Returns true if an error occurred. + * @access public + * @return bool + */ + public function IsError() { + return ($this->error_count > 0); + } + + /** + * Changes every end of line from CR or LF to CRLF. + * @access public + * @return string + */ + public function FixEOL($str) { + $str = str_replace("\r\n", "\n", $str); + $str = str_replace("\r", "\n", $str); + $str = str_replace("\n", $this->LE, $str); + return $str; + } + + /** + * Adds a custom header. + * @access public + * @return void + */ + public function AddCustomHeader($custom_header) { + $this->CustomHeader[] = explode(':', $custom_header, 2); + } + + /** + * Evaluates the message and returns modifications for inline images and backgrounds + * @access public + * @return $message + */ + public function MsgHTML($message, $basedir = '') { + preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images); + if(isset($images[2])) { + foreach($images[2] as $i => $url) { + // do not change urls for absolute images (thanks to corvuscorax) + if (!preg_match('#^[A-z]+://#', $url)) { + $filename = basename($url); + $directory = dirname($url); + ($directory == '.') ? $directory='': ''; + $cid = 'cid:' . md5($filename); + $ext = pathinfo($filename, PATHINFO_EXTENSION); + $mimeType = self::_mime_types($ext); + if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } + if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } + if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) { + $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message); + } + } + } + } + $this->IsHTML(true); + $this->Body = $message; + $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message))); + if (!empty($textMsg) && empty($this->AltBody)) { + $this->AltBody = html_entity_decode($textMsg); + } + if (empty($this->AltBody)) { + $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; + } + } + + /** + * Gets the MIME type of the embedded or inline image + * @param string File extension + * @access public + * @return string MIME type of ext + * @static + */ + public static function _mime_types($ext = '') { + $mimes = array( + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'doc' => 'application/msword', + 'bin' => 'application/macbinary', + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'class' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mpga' => 'audio/mpeg', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'rv' => 'video/vnd.rn-realvideo', + 'wav' => 'audio/x-wav', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'txt' => 'text/plain', + 'text' => 'text/plain', + 'log' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'xl' => 'application/excel', + 'eml' => 'message/rfc822' + ); + return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; + } + + /** + * Set (or reset) Class Objects (variables) + * + * Usage Example: + * $page->set('X-Priority', '3'); + * + * @access public + * @param string $name Parameter Name + * @param mixed $value Parameter Value + * NOTE: will not work with arrays, there are no arrays to set/reset + * @todo Should this not be using __set() magic function? + */ + public function set($name, $value = '') { + try { + if (isset($this->$name) ) { + $this->$name = $value; + } else { + throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); + } + } catch (Exception $e) { + $this->SetError($e->getMessage()); + if ($e->getCode() == self::STOP_CRITICAL) { + return false; + } + } + return true; + } + + /** + * Strips newlines to prevent header injection. + * @access public + * @param string $str String + * @return string + */ + public function SecureHeader($str) { + $str = str_replace("\r", '', $str); + $str = str_replace("\n", '', $str); + return trim($str); + } + + /** + * Set the private key file and password to sign the message. + * + * @access public + * @param string $key_filename Parameter File Name + * @param string $key_pass Password for private key + */ + public function Sign($cert_filename, $key_filename, $key_pass) { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + } + + /** + * Set the private key file and password to sign the message. + * + * @access public + * @param string $key_filename Parameter File Name + * @param string $key_pass Password for private key + */ + public function DKIM_QP($txt) { + $tmp = ''; + $line = ''; + for ($i = 0; $i < strlen($txt); $i++) { + $ord = ord($txt[$i]); + if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { + $line .= $txt[$i]; + } else { + $line .= "=".sprintf("%02X", $ord); + } + } + return $line; + } + + /** + * Generate DKIM signature + * + * @access public + * @param string $s Header + */ + public function DKIM_Sign($s) { + $privKeyStr = file_get_contents($this->DKIM_private); + if ($this->DKIM_passphrase != '') { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); + } else { + $privKey = $privKeyStr; + } + if (openssl_sign($s, $signature, $privKey)) { + return base64_encode($signature); + } + } + + /** + * Generate DKIM Canonicalization Header + * + * @access public + * @param string $s Header + */ + public function DKIM_HeaderC($s) { + $s = preg_replace("/\r\n\s+/", " ", $s); + $lines = explode("\r\n", $s); + foreach ($lines as $key => $line) { + list($heading, $value) = explode(":", $line, 2); + $heading = strtolower($heading); + $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces + $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value + } + $s = implode("\r\n", $lines); + return $s; + } + + /** + * Generate DKIM Canonicalization Body + * + * @access public + * @param string $body Message Body + */ + public function DKIM_BodyC($body) { + if ($body == '') return "\r\n"; + // stabilize line endings + $body = str_replace("\r\n", "\n", $body); + $body = str_replace("\n", "\r\n", $body); + // END stabilize line endings + while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { + $body = substr($body, 0, strlen($body) - 2); + } + return $body; + } + + /** + * Create the DKIM header, body, as new header + * + * @access public + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + */ + public function DKIM_Add($headers_line, $subject, $body) { + $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) + $subject_header = "Subject: $subject"; + $headers = explode($this->LE, $headers_line); + foreach($headers as $header) { + if (strpos($header, 'From:') === 0) { + $from_header = $header; + } elseif (strpos($header, 'To:') === 0) { + $to_header = $header; + } + } + $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); + $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); + $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable + $body = $this->DKIM_BodyC($body); + $DKIMlen = strlen($body) ; // Length of body + $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body + $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; + $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". + "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". + "\th=From:To:Subject;\r\n". + "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". + "\tz=$from\r\n". + "\t|$to\r\n". + "\t|$subject;\r\n". + "\tbh=" . $DKIMb64 . ";\r\n". + "\tb="; + $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); + $signed = $this->DKIM_Sign($toSign); + return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n"; + } + + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) { + if (!empty($this->action_function) && function_exists($this->action_function)) { + $params = array($isSent, $to, $cc, $bcc, $subject, $body); + call_user_func_array($this->action_function, $params); + } + } +} + +class phpmailerException extends Exception { + public function errorMessage() { + $errorMsg = '' . $this->getMessage() . "
    \n"; + return $errorMsg; + } +} +?> diff --git a/3rdparty/class.smtp.php b/3rdparty/class.smtp.php new file mode 100644 index 00000000000..07c275936cf --- /dev/null +++ b/3rdparty/class.smtp.php @@ -0,0 +1,817 @@ +smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + ///////////////////////////////////////////////// + // CONNECTION FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Connect to the server specified on the port specified. + * If the port is not specified use the default SMTP_PORT. + * If tval is specified then a connection will try and be + * established with the server for that number of seconds. + * If tval is not specified the default is 30 seconds to + * try on the connection. + * + * SMTP CODE SUCCESS: 220 + * SMTP CODE FAILURE: 421 + * @access public + * @return bool + */ + public function Connect($host, $port = 0, $tval = 30) { + // set the error val to null so there is no confusion + $this->error = null; + + // make sure we are __not__ connected + if($this->connected()) { + // already connected, generate error + $this->error = array("error" => "Already connected to a server"); + return false; + } + + if(empty($port)) { + $port = $this->SMTP_PORT; + } + + // connect to the smtp server + $this->smtp_conn = @fsockopen($host, // the host of the server + $port, // the port to use + $errno, // error number if any + $errstr, // error message if any + $tval); // give up after ? secs + // verify we connected properly + if(empty($this->smtp_conn)) { + $this->error = array("error" => "Failed to connect to server", + "errno" => $errno, + "errstr" => $errstr); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '
    '; + } + return false; + } + + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if(substr(PHP_OS, 0, 3) != "WIN") + socket_set_timeout($this->smtp_conn, $tval, 0); + + // get any announcement + $announce = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '
    '; + } + + return true; + } + + /** + * Initiate a TLS communication with the server. + * + * SMTP CODE 220 Ready to start TLS + * SMTP CODE 501 Syntax error (no parameters allowed) + * SMTP CODE 454 TLS not available due to temporary reason + * @access public + * @return bool success + */ + public function StartTLS() { + $this->error = null; # to avoid confusion + + if(!$this->connected()) { + $this->error = array("error" => "Called StartTLS() without being connected"); + return false; + } + + fputs($this->smtp_conn,"STARTTLS" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 220) { + $this->error = + array("error" => "STARTTLS not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + // Begin encrypted connection + if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { + return false; + } + + return true; + } + + /** + * Performs SMTP authentication. Must be run after running the + * Hello() method. Returns true if successfully authenticated. + * @access public + * @return bool + */ + public function Authenticate($username, $password) { + // Start authentication + fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "AUTH not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + // Send encoded username + fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "Username not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + // Send encoded password + fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 235) { + $this->error = + array("error" => "Password not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + return true; + } + + /** + * Returns true if connected to a server otherwise false + * @access public + * @return bool + */ + public function Connected() { + if(!empty($this->smtp_conn)) { + $sock_status = socket_get_status($this->smtp_conn); + if($sock_status["eof"]) { + // the socket is valid but we are not connected + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; + } + $this->Close(); + return false; + } + return true; // everything looks good + } + return false; + } + + /** + * Closes the socket and cleans up the state of the class. + * It is not considered good to use this function without + * first trying to use QUIT. + * @access public + * @return void + */ + public function Close() { + $this->error = null; // so there is no confusion + $this->helo_rply = null; + if(!empty($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + ///////////////////////////////////////////////// + // SMTP COMMANDS + ///////////////////////////////////////////////// + + /** + * Issues a data command and sends the msg_data to the server + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being seperated by and additional . + * + * Implements rfc 821: DATA + * + * SMTP CODE INTERMEDIATE: 354 + * [data] + * . + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 552,554,451,452 + * SMTP CODE FAILURE: 451,554 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Data($msg_data) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Data() without being connected"); + return false; + } + + fputs($this->smtp_conn,"DATA" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 354) { + $this->error = + array("error" => "DATA command not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + /* the server is ready to accept data! + * according to rfc 821 we should not send more than 1000 + * including the CRLF + * characters on a single line so we will break the data up + * into lines by \r and/or \n then if needed we will break + * each of those into smaller lines to fit within the limit. + * in addition we will be looking for lines that start with + * a period '.' and append and additional period '.' to that + * line. NOTE: this does not count towards limit. + */ + + // normalize the line breaks so we know the explode works + $msg_data = str_replace("\r\n","\n",$msg_data); + $msg_data = str_replace("\r","\n",$msg_data); + $lines = explode("\n",$msg_data); + + /* we need to find a good way to determine is headers are + * in the msg_data or if it is a straight msg body + * currently I am assuming rfc 822 definitions of msg headers + * and if the first field of the first line (':' sperated) + * does not contain a space then it _should_ be a header + * and we can process all lines before a blank "" line as + * headers. + */ + + $field = substr($lines[0],0,strpos($lines[0],":")); + $in_headers = false; + if(!empty($field) && !strstr($field," ")) { + $in_headers = true; + } + + $max_line_length = 998; // used below; set here for ease in change + + while(list(,$line) = @each($lines)) { + $lines_out = null; + if($line == "" && $in_headers) { + $in_headers = false; + } + // ok we need to break this line up into several smaller lines + while(strlen($line) > $max_line_length) { + $pos = strrpos(substr($line,0,$max_line_length)," "); + + // Patch to fix DOS attack + if(!$pos) { + $pos = $max_line_length - 1; + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos); + } else { + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos + 1); + } + + /* if processing headers add a LWSP-char to the front of new line + * rfc 822 on long msg headers + */ + if($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + // send the lines to the server + while(list(,$line_out) = @each($lines_out)) { + if(strlen($line_out) > 0) + { + if(substr($line_out, 0, 1) == ".") { + $line_out = "." . $line_out; + } + } + fputs($this->smtp_conn,$line_out . $this->CRLF); + } + } + + // message data has been sent + fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 250) { + $this->error = + array("error" => "DATA not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + return true; + } + + /** + * Sends the HELO command to the smtp server. + * This makes sure that we and the server are in + * the same known state. + * + * Implements from rfc 821: HELO + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 501, 504, 421 + * @access public + * @return bool + */ + public function Hello($host = '') { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Hello() without being connected"); + return false; + } + + // if hostname for HELO was not specified send default + if(empty($host)) { + // determine appropriate default to send to server + $host = "localhost"; + } + + // Send extended hello first (RFC 2821) + if(!$this->SendHello("EHLO", $host)) { + if(!$this->SendHello("HELO", $host)) { + return false; + } + } + + return true; + } + + /** + * Sends a HELO/EHLO command. + * @access private + * @return bool + */ + private function SendHello($hello, $host) { + fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '
    '; + } + + if($code != 250) { + $this->error = + array("error" => $hello . " not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + $this->helo_rply = $rply; + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. + * + * Implements rfc 821: MAIL FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,421 + * @access public + * @return bool + */ + public function Mail($from) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Mail() without being connected"); + return false; + } + + $useVerp = ($this->do_verp ? "XVERP" : ""); + fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 250) { + $this->error = + array("error" => "MAIL not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + return true; + } + + /** + * Sends the quit command to the server and then closes the socket + * if there is no error or the $close_on_error argument is true. + * + * Implements from rfc 821: QUIT + * + * SMTP CODE SUCCESS: 221 + * SMTP CODE ERROR : 500 + * @access public + * @return bool + */ + public function Quit($close_on_error = true) { + $this->error = null; // so there is no confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Quit() without being connected"); + return false; + } + + // send the quit command to the server + fputs($this->smtp_conn,"quit" . $this->CRLF); + + // get any good-bye messages + $byemsg = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '
    '; + } + + $rval = true; + $e = null; + + $code = substr($byemsg,0,3); + if($code != 221) { + // use e as a tmp var cause Close will overwrite $this->error + $e = array("error" => "SMTP server rejected quit command", + "smtp_code" => $code, + "smtp_rply" => substr($byemsg,4)); + $rval = false; + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
    '; + } + } + + if(empty($e) || $close_on_error) { + $this->Close(); + } + + return $rval; + } + + /** + * Sends the command RCPT to the SMTP server with the TO: argument of $to. + * Returns true if the recipient was accepted false if it was rejected. + * + * Implements from rfc 821: RCPT TO: + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,552,553,450,451,452 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Recipient($to) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Recipient() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "RCPT not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + return true; + } + + /** + * Sends the RSET command to abort and transaction that is + * currently in progress. Returns true if successful false + * otherwise. + * + * Implements rfc 821: RSET + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500,501,504,421 + * @access public + * @return bool + */ + public function Reset() { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Reset() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RSET" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 250) { + $this->error = + array("error" => "RSET failed", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * + * Implements rfc 821: SAML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + public function SendAndMail($from) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendAndMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
    '; + } + + if($code != 250) { + $this->error = + array("error" => "SAML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
    '; + } + return false; + } + return true; + } + + /** + * This is an optional command for SMTP that this class does not + * support. This method is here to make the RFC821 Definition + * complete for this class and __may__ be implimented in the future + * + * Implements from rfc 821: TURN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 502 + * SMTP CODE ERROR : 500, 503 + * @access public + * @return bool + */ + public function Turn() { + $this->error = array("error" => "This method, TURN, of the SMTP ". + "is not implemented"); + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '
    '; + } + return false; + } + + /** + * Get the current error + * @access public + * @return array + */ + public function getError() { + return $this->error; + } + + ///////////////////////////////////////////////// + // INTERNAL FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Read in as many lines as possible + * either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access private + * @return string + */ + private function get_lines() { + $data = ""; + while($str = @fgets($this->smtp_conn,515)) { + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
    '; + echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
    '; + } + $data .= $str; + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
    '; + } + // if 4th character is a space, we are done reading, break the loop + if(substr($str,3,1) == " ") { break; } + } + return $data; + } + +} + +?> -- GitLab From 0f5864d864f63a7142064d142661c46644b2d0db Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Fri, 20 Apr 2012 21:49:57 +0200 Subject: [PATCH 202/430] support searching the knowledge base --- lib/ocsclient.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/ocsclient.php b/lib/ocsclient.php index d830a4f3e7e..9ad9ef21c66 100755 --- a/lib/ocsclient.php +++ b/lib/ocsclient.php @@ -199,7 +199,7 @@ class OC_OCSClient{ * * This function returns a list of all the knowledgebase entries from the OCS server */ - public static function getKnownledgebaseEntries($page,$pagesize){ + public static function getKnownledgebaseEntries($page,$pagesize,$search=''){ if(OC_Config::getValue('knowledgebaseenabled', true)==false){ $kbe=array(); $kbe['totalitems']=0; @@ -208,7 +208,8 @@ class OC_OCSClient{ $p= (int) $page; $s= (int) $pagesize; - $url=OC_OCSClient::getKBURL().'/knowledgebase/data?type=150&page='.$p.'&pagesize='.$s; + if($search<>'') $searchcmd='&search='.urlencode($search); else $searchcmd=''; + $url=OC_OCSClient::getKBURL().'/knowledgebase/data?type=150&page='.$p.'&pagesize='.$s.$searchcmd; $kbe=array(); $xml=@file_get_contents($url); -- GitLab From 99a473bd628c08dc2f232c98b9220a029ad5ab99 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Fri, 20 Apr 2012 22:33:30 +0200 Subject: [PATCH 203/430] support file calls with parameter --- lib/base.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/base.php b/lib/base.php index fa5287631d8..df240dca6df 100644 --- a/lib/base.php +++ b/lib/base.php @@ -401,8 +401,12 @@ class OC{ self::$REQUESTEDAPP = (isset($_GET['app'])?strip_tags($_GET['app']):'files'); self::$REQUESTEDFILE = $_GET['file']; if(substr_count(self::$REQUESTEDFILE, '?') != 0){ - $pos = strpos(self::$REQUESTEDFILE, '?'); - self::$REQUESTEDFILE = substr(self::$REQUESTEDFILE, 0, $pos); + $pos_questionmark = strpos(self::$REQUESTEDFILE, '?'); + $pos_equal = strpos(self::$REQUESTEDFILE, '='); + $pos_and = strpos(self::$REQUESTEDFILE, '?'); + $_GET[substr(self::$REQUESTEDFILE, $pos_questionmark + 1, $pos_equal - $pos_questionmark - 1)] = substr(self::$REQUESTEDFILE, $pos_equal + 1, $pos_and); + self::$REQUESTEDFILE = substr(self::$REQUESTEDFILE, 0, $pos_questionmark); + $_GET['file'] = OC::$REQUESTEDFILE; } self::$REQUESTEDFILE = (isset($_GET['file'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . self::$REQUESTEDFILE, OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?self::$REQUESTEDFILE:null):null); } -- GitLab From c3d78cf77aa18b54cb2d1c9d0e16874a0fea804e Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Fri, 20 Apr 2012 22:34:13 +0200 Subject: [PATCH 204/430] remove require once lib base in files scan.php --- apps/files/ajax/scan.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/files/ajax/scan.php b/apps/files/ajax/scan.php index db09b7d5c64..488f68e6b3c 100644 --- a/apps/files/ajax/scan.php +++ b/apps/files/ajax/scan.php @@ -1,7 +1,5 @@ Date: Fri, 20 Apr 2012 22:35:12 +0200 Subject: [PATCH 205/430] modify OC.filepath for movable apps --- core/js/js.js | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/core/js/js.js b/core/js/js.js index 019c40a0e1b..9b0a159b5c2 100644 --- a/core/js/js.js +++ b/core/js/js.js @@ -32,7 +32,7 @@ t.cache={}; OC={ webroot:oc_webroot, currentUser:(typeof oc_current_user!=='undefined')?oc_current_user:false, - coreApps:['files','admin','log','search','settings','core','3rdparty'], + coreApps:['admin','log','search','settings','core','3rdparty'], /** * get an absolute url to a file in an appen * @param app the id of the app the file belongs to @@ -51,16 +51,21 @@ OC={ */ filePath:function(app,type,file){ var isCore=OC.coreApps.indexOf(app)!=-1; - app+='/'; - var link=OC.webroot+'/'; - if(!isCore){ - link+='apps/'; - } - link+=app; - if(type){ - link+=type+'/'; + var link=OC.webroot; + if(file.substring(file.length-3) == 'php' && !isCore){ + link+='/?app=' + app + '&file=' + type + '/' + file; + }else{ + link+='/'; + app+='/'; + if(!isCore){ + link+='apps/'; + } + link+=app; + if(type){ + link+=type+'/'; + } + link+=file; } - link+=file; return link; }, /** -- GitLab From d1fe3c2314c29363fc6835e67522df10d45c2dae Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 00:18:47 +0200 Subject: [PATCH 206/430] add a button to open the online documentation --- settings/templates/help.php | 1 + 1 file changed, 1 insertion(+) diff --git a/settings/templates/help.php b/settings/templates/help.php index 754bf8b6376..df640d97469 100644 --- a/settings/templates/help.php +++ b/settings/templates/help.php @@ -5,6 +5,7 @@ */?>
    + t( 'Documentation' ); ?> t( 'Ask a question' ); ?> Date: Sat, 21 Apr 2012 00:33:24 +0200 Subject: [PATCH 207/430] add a link to the desktop and mobile clients download. --- settings/templates/personal.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/settings/templates/personal.php b/settings/templates/personal.php index 986cfe55ae5..df5791bd524 100644 --- a/settings/templates/personal.php +++ b/settings/templates/personal.php @@ -8,6 +8,12 @@

    t('You use');?> t('of the available');?>

    +
    + t('Desktop and Mobile Syncing Clients');?> + t('Download');?> +
    + +
    t('Your password got changed');?>
    -- GitLab From 6bfe2289be05e9f54272a86a0f957ec41ef32e28 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 15:30:58 +0200 Subject: [PATCH 208/430] improve the app installer. show a label if an app is an internal app or a third party app from the app store. show a preview image of the app if available --- lib/ocsclient.php | 1 + settings/apps.php | 7 +++++++ settings/css/settings.css | 3 ++- settings/js/apps.js | 3 +++ settings/templates/apps.php | 6 ++++-- settings/trans.png | Bin 0 -> 187 bytes 6 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 settings/trans.png diff --git a/lib/ocsclient.php b/lib/ocsclient.php index 9ad9ef21c66..aef51f38fb7 100755 --- a/lib/ocsclient.php +++ b/lib/ocsclient.php @@ -162,6 +162,7 @@ class OC_OCSClient{ $app['preview3']=$tmp->smallpreviewpic3; $app['changed']=strtotime($tmp->changed); $app['description']=$tmp->description; + $app['detailpage']=$tmp->detailpage; return $app; } diff --git a/settings/apps.php b/settings/apps.php index 0889b0c45ed..cc161026020 100644 --- a/settings/apps.php +++ b/settings/apps.php @@ -39,6 +39,9 @@ foreach($registeredApps as $app){ $info=OC_App::getAppInfo($app); $active=(OC_Appconfig::getValue($app,'enabled','no')=='yes')?true:false; $info['active']=$active; + $info['internal']=true; + $info['internallabel']='Internal App'; + $info['preview']='trans.png'; $apps[]=$info; } } @@ -64,6 +67,7 @@ usort($apps, 'app_sort'); } if(!$local) { + if($app['preview']=='') $pre='trans.png'; else $pre=$app['preview']; $apps[]=array( 'name'=>$app['name'], 'id'=>$app['id'], @@ -71,6 +75,9 @@ usort($apps, 'app_sort'); 'description'=>$app['description'], 'author'=>$app['personid'], 'license'=>$app['license'], + 'preview'=>$pre, + 'internal'=>false, + 'internallabel'=>'3rd Party App', ); } } diff --git a/settings/css/settings.css b/settings/css/settings.css index 42576953d04..62e84654d55 100644 --- a/settings/css/settings.css +++ b/settings/css/settings.css @@ -40,7 +40,8 @@ select.quota.active { background: #fff; } /* APPS */ li { color:#888; } li.active { color:#000; } +small.externalapp { color:#FFF; background-color:#BBB; font-weight:bold; font-size:6pt; padding:4px; border-radius: 4px;} span.version { margin-left:3em; color:#ddd; } /* LOF */ -#log { white-space:normal; } \ No newline at end of file +#log { white-space:normal; } diff --git a/settings/js/apps.js b/settings/js/apps.js index 12d09ac69db..df5300911aa 100644 --- a/settings/js/apps.js +++ b/settings/js/apps.js @@ -13,8 +13,11 @@ $(document).ready(function(){ var app=$(this).data('app'); $('#rightcontent p').show(); $('#rightcontent span.name').text(app.name); + $('#rightcontent small.externalapp').text(app.internallabel); $('#rightcontent span.version').text(app.version); $('#rightcontent p.description').text(app.description); + $('#rightcontent img.preview').attr('src',app.preview); + $('#rightcontent small.externalapp').attr('style','visibility:visible'); $('#rightcontent span.author').text(app.author); $('#rightcontent span.licence').text(app.licence); diff --git a/settings/templates/apps.php b/settings/templates/apps.php index 1e49b4c8928..d25ca1bc7fb 100644 --- a/settings/templates/apps.php +++ b/settings/templates/apps.php @@ -5,7 +5,7 @@ */?>
      @@ -14,12 +14,14 @@ + 3rd party' ?>
    -

    t('Select an App');?>

    +

    t('Select an App');?>

    +
    diff --git a/settings/trans.png b/settings/trans.png new file mode 100644 index 0000000000000000000000000000000000000000..e6920168bf2dbb9405040360e42095922b9e124a GIT binary patch literal 187 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1|;Q0k92}K#X;^)4C~IxyaaOClDyqr82*Fc zg1yTp14TFsJR*x37`TN&n2}-D90{Nxdx@v7EBhT5QEm(I#bpa!fI> Date: Sat, 21 Apr 2012 22:27:19 +0200 Subject: [PATCH 209/430] fix a php notice --- apps/calendar/templates/part.choosecalendar.php | 6 ++++++ apps/calendar/templates/part.choosecalendar.rowfields.php | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/calendar/templates/part.choosecalendar.php b/apps/calendar/templates/part.choosecalendar.php index d93a85aeca0..4f6680bb497 100644 --- a/apps/calendar/templates/part.choosecalendar.php +++ b/apps/calendar/templates/part.choosecalendar.php @@ -7,6 +7,12 @@ for($i = 0; $i < count($option_calendars); $i++){ echo ""; $tmpl = new OC_Template('calendar', 'part.choosecalendar.rowfields'); $tmpl->assign('calendar', $option_calendars[$i]); + if(OC_Calendar_Share::allUsersSharedwith($option_calendars[$i]['id'], OC_Calendar_Share::CALENDAR) == array()){ + $shared = false; + }else{ + $shared = true; + } + $tmpl->assign('shared', $shared); $tmpl->printpage(); echo ""; } diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.php b/apps/calendar/templates/part.choosecalendar.rowfields.php index 21fb3f8a097..cf85f0dc53e 100644 --- a/apps/calendar/templates/part.choosecalendar.rowfields.php +++ b/apps/calendar/templates/part.choosecalendar.rowfields.php @@ -1,7 +1,7 @@ '; echo ''; -echo ''; +echo ''; echo ''; echo ''; echo ''; -- GitLab From a86d89f5ca8d71febd764b20e939010901be4974 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 22:47:56 +0200 Subject: [PATCH 210/430] Add a static code checker for evil patterns in apps. Disabled by default for now. We will check for private api calls here later once the public api is in place --- config/config.sample.php | 1 + lib/installer.php | 59 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/config/config.sample.php b/config/config.sample.php index 9f6d674fc0e..0900937c690 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -24,6 +24,7 @@ $CONFIG = array( "mail_smtpauth" => "false", "mail_smtpname" => "", "mail_smtppassword" => "", +"appcodechecker" => "", // "datadirectory" => "" ); ?> diff --git a/lib/installer.php b/lib/installer.php index 6edf4ce1b74..d5592273815 100644 --- a/lib/installer.php +++ b/lib/installer.php @@ -47,6 +47,7 @@ class OC_Installer{ * This function works as follows * -# fetching the file * -# unzipping it + * -# check the code * -# installing the database at appinfo/database.xml * -# including appinfo/install.php * -# setting the installed version @@ -91,6 +92,7 @@ class OC_Installer{ //extract the archive in a temporary folder $extractDir=OC_Helper::tmpFolder(); + OC_Helper::rmdirr($extractDir); mkdir($extractDir); if($archive=OC_Archive::open($path)){ $archive->extract($extractDir); @@ -102,7 +104,7 @@ class OC_Installer{ } return false; } - + //load the info.xml file of the app if(!is_file($extractDir.'/appinfo/info.xml')){ //try to find it in a subdir @@ -125,6 +127,12 @@ class OC_Installer{ } $info=OC_App::getAppInfo($extractDir.'/appinfo/info.xml',true); $basedir=OC::$APPSROOT.'/apps/'.$info['id']; + + // check the code for not allowed calls + if(!OC_Installer::checkCode($info['id'],$extractDir)){ + OC_Helper::rmdirr($extractDir); + return false; + } //check if an app with the same id is already installed if(self::isInstalled( $info['id'] )){ @@ -151,8 +159,8 @@ class OC_Installer{ } //copy the app to the correct place - if(!mkdir($basedir)){ - OC_Log::write('core','Can\'t create app folder ('.$basedir.')',OC_Log::ERROR); + if(@!mkdir($basedir)){ + OC_Log::write('core','Can\'t create app folder. Please fix permissions. ('.$basedir.')',OC_Log::ERROR); OC_Helper::rmdirr($extractDir); if($data['source']=='http'){ unlink($path); @@ -300,4 +308,49 @@ class OC_Installer{ OC_Appconfig::setValue($app,'installed_version',OC_App::getAppVersion($app)); return $info; } + + + /** + * check the code of an app with some static code checks + * @param string $folder the folder of the app to check + * @returns true for app is o.k. and false for app is not o.k. + */ + public static function checkCode($appname,$folder){ + + $blacklist=array( + 'fopen(', + 'eval(' + // more evil pattern will go here later + // will will also check if an app is using private api once the public api is in place + + ); + + // is the code checker enabled? + if(OC_Config::getValue('appcodechecker', false)){ + + // check if grep is installed + $grep = exec('which grep'); + if($grep=='') { + OC_Log::write('core','grep not installed. So checking the code of the app "'.$appname.'" was not possible',OC_Log::ERROR); + return true; + } + + // iterate the bad patterns + foreach($blacklist as $bl) { + $cmd = 'grep -ri '.escapeshellarg($bl).' '.$folder.''; + $result = exec($cmd); + // bad pattern found + if($result<>'') { + OC_Log::write('core','App "'.$appname.'" is using a not allowed call "'.$bl.'". Installation refused.',OC_Log::ERROR); + return false; + } + } + return true; + + }else{ + return true; + } + } + + } -- GitLab From 1a494978997a455806db2c48e32fc8e0f724b0ad Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 22:55:18 +0200 Subject: [PATCH 211/430] structure the information a bit more so that is easier readable --- apps/contacts/templates/settings.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/contacts/templates/settings.php b/apps/contacts/templates/settings.php index 5627a15c50a..ff1cab0c8de 100644 --- a/apps/contacts/templates/settings.php +++ b/apps/contacts/templates/settings.php @@ -3,10 +3,10 @@ t('Contacts'); ?>
    t('CardDAV syncing addresses:'); ?>
    -
    t('Primary address (Kontact et al)'); ?>
    -
    /
    -
    t('iOS/OS X'); ?>
    -
    /principals//
    +
    t('Primary address (Kontact et al)'); ?>
    +
    /
    +
    t('iOS/OS X'); ?>
    +
    /principals//
    Powered by geonames.org webservice
    -- GitLab From ff3b199cc8712f46ef004e3666dd277ab583d0a2 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 23:08:52 +0200 Subject: [PATCH 212/430] use less space --- apps/admin_migrate/templates/settings.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/admin_migrate/templates/settings.php b/apps/admin_migrate/templates/settings.php index 91e305074e4..f81c9199ece 100644 --- a/apps/admin_migrate/templates/settings.php +++ b/apps/admin_migrate/templates/settings.php @@ -6,9 +6,9 @@

    What would you like to export?

    - ownCloud instance (suitable for import )
    - ownCloud system files
    - Just user files
    + ownCloud instance (suitable for import )
    + ownCloud system files
    + Just user files

    -- GitLab From 80950f2e1c6a1ca2814d33167f7db4d8e3b9c21b Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 23:10:35 +0200 Subject: [PATCH 213/430] make field completely visible --- apps/user_migrate/templates/admin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/user_migrate/templates/admin.php b/apps/user_migrate/templates/admin.php index b01e5c7579a..60fc74f6660 100644 --- a/apps/user_migrate/templates/admin.php +++ b/apps/user_migrate/templates/admin.php @@ -6,7 +6,7 @@ t('Import user account');?>

    -

    +

    -- GitLab From 260c48c29a9167446862bf38775274e07685f6e3 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 23:23:02 +0200 Subject: [PATCH 214/430] cleanup the admin page layout mess a bit. Still a lot to improve in the future :-) --- apps/user_migrate/templates/admin.php | 2 +- files/templates/admin.php | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/user_migrate/templates/admin.php b/apps/user_migrate/templates/admin.php index 60fc74f6660..ff51f43ffde 100644 --- a/apps/user_migrate/templates/admin.php +++ b/apps/user_migrate/templates/admin.php @@ -6,7 +6,7 @@ t('Import user account');?>

    -

    +

    diff --git a/files/templates/admin.php b/files/templates/admin.php index 9bcc40e9361..01fe1105260 100644 --- a/files/templates/admin.php +++ b/files/templates/admin.php @@ -7,9 +7,13 @@ '/>(t('max. possible: '); echo $_['maxPossibleUploadSize'] ?>)
    />
    -
    - ' title="t( '0 is unlimited' ); ?>" />
    -
    + + ' title="t( '0 is unlimited' ); ?>" /> +
    + + + + -- GitLab From a0a80e74c2b7ba32cd6e8a57dcfba6bcadab3053 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sat, 21 Apr 2012 23:23:46 +0200 Subject: [PATCH 215/430] remove old sabredav files --- 3rdparty/Sabre.includes.php | 127 -- 3rdparty/Sabre/CalDAV/Backend/Abstract.php | 163 -- 3rdparty/Sabre/CalDAV/Backend/PDO.php | 386 ---- 3rdparty/Sabre/CalDAV/Calendar.php | 318 --- 3rdparty/Sabre/CalDAV/CalendarObject.php | 260 --- 3rdparty/Sabre/CalDAV/CalendarRootNode.php | 75 - .../Exception/InvalidICalendarObject.php | 18 - 3rdparty/Sabre/CalDAV/ICSExportPlugin.php | 124 -- 3rdparty/Sabre/CalDAV/ICalendar.php | 18 - 3rdparty/Sabre/CalDAV/ICalendarObject.php | 20 - 3rdparty/Sabre/CalDAV/ICalendarUtil.php | 157 -- 3rdparty/Sabre/CalDAV/Plugin.php | 788 ------- .../Sabre/CalDAV/Principal/Collection.php | 31 - 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php | 178 -- .../Sabre/CalDAV/Principal/ProxyWrite.php | 178 -- 3rdparty/Sabre/CalDAV/Principal/User.php | 122 -- .../SupportedCalendarComponentSet.php | 85 - .../CalDAV/Property/SupportedCalendarData.php | 38 - .../CalDAV/Property/SupportedCollationSet.php | 44 - 3rdparty/Sabre/CalDAV/Server.php | 65 - 3rdparty/Sabre/CalDAV/UserCalendars.php | 280 --- 3rdparty/Sabre/CalDAV/Version.php | 24 - 3rdparty/Sabre/CalDAV/XMLUtil.php | 208 -- 3rdparty/Sabre/CardDAV/AddressBook.php | 293 --- .../Sabre/CardDAV/AddressBookQueryParser.php | 211 -- 3rdparty/Sabre/CardDAV/AddressBookRoot.php | 78 - 3rdparty/Sabre/CardDAV/Backend/Abstract.php | 121 - 3rdparty/Sabre/CardDAV/Backend/PDO.php | 277 --- 3rdparty/Sabre/CardDAV/Card.php | 220 -- 3rdparty/Sabre/CardDAV/IAddressBook.php | 18 - 3rdparty/Sabre/CardDAV/ICard.php | 18 - 3rdparty/Sabre/CardDAV/IDirectory.php | 21 - 3rdparty/Sabre/CardDAV/Plugin.php | 463 ---- .../CardDAV/Property/SupportedAddressData.php | 69 - 3rdparty/Sabre/CardDAV/UserAddressBooks.php | 240 -- 3rdparty/Sabre/CardDAV/Version.php | 26 - .../Sabre/DAV/Auth/Backend/AbstractBasic.php | 79 - .../Sabre/DAV/Auth/Backend/AbstractDigest.php | 96 - 3rdparty/Sabre/DAV/Auth/Backend/Apache.php | 60 - 3rdparty/Sabre/DAV/Auth/Backend/File.php | 76 - 3rdparty/Sabre/DAV/Auth/Backend/PDO.php | 66 - 3rdparty/Sabre/DAV/Auth/IBackend.php | 34 - 3rdparty/Sabre/DAV/Auth/Plugin.php | 111 - .../Sabre/DAV/Browser/GuessContentType.php | 97 - .../Sabre/DAV/Browser/MapGetToPropFind.php | 54 - 3rdparty/Sabre/DAV/Browser/Plugin.php | 285 --- 3rdparty/Sabre/DAV/Client.php | 431 ---- 3rdparty/Sabre/DAV/Collection.php | 90 - 3rdparty/Sabre/DAV/Directory.php | 17 - 3rdparty/Sabre/DAV/Exception.php | 63 - 3rdparty/Sabre/DAV/Exception/BadRequest.php | 28 - 3rdparty/Sabre/DAV/Exception/Conflict.php | 28 - .../Sabre/DAV/Exception/ConflictingLock.php | 35 - 3rdparty/Sabre/DAV/Exception/FileNotFound.php | 28 - 3rdparty/Sabre/DAV/Exception/Forbidden.php | 27 - .../DAV/Exception/InsufficientStorage.php | 27 - .../DAV/Exception/InvalidResourceType.php | 33 - .../Exception/LockTokenMatchesRequestUri.php | 39 - 3rdparty/Sabre/DAV/Exception/Locked.php | 67 - .../Sabre/DAV/Exception/MethodNotAllowed.php | 44 - .../Sabre/DAV/Exception/NotAuthenticated.php | 28 - .../Sabre/DAV/Exception/NotImplemented.php | 27 - .../DAV/Exception/PreconditionFailed.php | 69 - .../DAV/Exception/ReportNotImplemented.php | 30 - .../RequestedRangeNotSatisfiable.php | 29 - .../DAV/Exception/UnsupportedMediaType.php | 28 - 3rdparty/Sabre/DAV/FS/Directory.php | 121 - 3rdparty/Sabre/DAV/FS/File.php | 89 - 3rdparty/Sabre/DAV/FS/Node.php | 81 - 3rdparty/Sabre/DAV/FSExt/Directory.php | 135 -- 3rdparty/Sabre/DAV/FSExt/File.php | 88 - 3rdparty/Sabre/DAV/FSExt/Node.php | 276 --- 3rdparty/Sabre/DAV/File.php | 81 - 3rdparty/Sabre/DAV/ICollection.php | 58 - 3rdparty/Sabre/DAV/IExtendedCollection.php | 28 - 3rdparty/Sabre/DAV/IFile.php | 63 - 3rdparty/Sabre/DAV/ILockable.php | 38 - 3rdparty/Sabre/DAV/INode.php | 44 - 3rdparty/Sabre/DAV/IProperties.php | 67 - 3rdparty/Sabre/DAV/IQuota.php | 27 - 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php | 50 - 3rdparty/Sabre/DAV/Locks/Backend/FS.php | 189 -- 3rdparty/Sabre/DAV/Locks/Backend/File.php | 175 -- 3rdparty/Sabre/DAV/Locks/Backend/PDO.php | 165 -- 3rdparty/Sabre/DAV/Locks/LockInfo.php | 81 - 3rdparty/Sabre/DAV/Locks/Plugin.php | 680 ------ 3rdparty/Sabre/DAV/Mount/Plugin.php | 79 - 3rdparty/Sabre/DAV/Node.php | 55 - 3rdparty/Sabre/DAV/ObjectTree.php | 154 -- 3rdparty/Sabre/DAV/Property.php | 25 - .../Sabre/DAV/Property/GetLastModified.php | 75 - 3rdparty/Sabre/DAV/Property/Href.php | 91 - 3rdparty/Sabre/DAV/Property/HrefList.php | 96 - 3rdparty/Sabre/DAV/Property/IHref.php | 25 - 3rdparty/Sabre/DAV/Property/LockDiscovery.php | 102 - 3rdparty/Sabre/DAV/Property/ResourceType.php | 125 -- 3rdparty/Sabre/DAV/Property/Response.php | 156 -- 3rdparty/Sabre/DAV/Property/ResponseList.php | 58 - 3rdparty/Sabre/DAV/Property/SupportedLock.php | 76 - .../Sabre/DAV/Property/SupportedReportSet.php | 110 - 3rdparty/Sabre/DAV/Server.php | 1941 ----------------- 3rdparty/Sabre/DAV/ServerPlugin.php | 90 - 3rdparty/Sabre/DAV/SimpleCollection.php | 106 - 3rdparty/Sabre/DAV/SimpleDirectory.php | 21 - 3rdparty/Sabre/DAV/SimpleFile.php | 120 - 3rdparty/Sabre/DAV/StringUtil.php | 91 - .../Sabre/DAV/TemporaryFileFilterPlugin.php | 279 --- 3rdparty/Sabre/DAV/Tree.php | 192 -- 3rdparty/Sabre/DAV/Tree/Filesystem.php | 124 -- 3rdparty/Sabre/DAV/URLUtil.php | 125 -- 3rdparty/Sabre/DAV/UUIDUtil.php | 64 - 3rdparty/Sabre/DAV/Version.php | 24 - 3rdparty/Sabre/DAV/XMLUtil.php | 183 -- .../DAVACL/AbstractPrincipalCollection.php | 121 - .../Sabre/DAVACL/Exception/AceConflict.php | 34 - .../Sabre/DAVACL/Exception/NeedPrivileges.php | 80 - .../Sabre/DAVACL/Exception/NoAbstract.php | 34 - .../Exception/NotRecognizedPrincipal.php | 34 - .../Exception/NotSupportedPrivilege.php | 34 - 3rdparty/Sabre/DAVACL/IACL.php | 58 - 3rdparty/Sabre/DAVACL/IPrincipal.php | 75 - 3rdparty/Sabre/DAVACL/IPrincipalBackend.php | 73 - 3rdparty/Sabre/DAVACL/Plugin.php | 1238 ----------- 3rdparty/Sabre/DAVACL/Principal.php | 263 --- .../Sabre/DAVACL/PrincipalBackend/PDO.php | 206 -- 3rdparty/Sabre/DAVACL/PrincipalCollection.php | 35 - 3rdparty/Sabre/DAVACL/Property/Acl.php | 186 -- .../Property/CurrentUserPrivilegeSet.php | 75 - 3rdparty/Sabre/DAVACL/Property/Principal.php | 154 -- .../DAVACL/Property/SupportedPrivilegeSet.php | 92 - 3rdparty/Sabre/DAVACL/Version.php | 24 - 3rdparty/Sabre/HTTP/AWSAuth.php | 226 -- 3rdparty/Sabre/HTTP/AbstractAuth.php | 111 - 3rdparty/Sabre/HTTP/BasicAuth.php | 61 - 3rdparty/Sabre/HTTP/DigestAuth.php | 234 -- 3rdparty/Sabre/HTTP/Request.php | 243 --- 3rdparty/Sabre/HTTP/Response.php | 152 -- 3rdparty/Sabre/HTTP/Util.php | 65 - 3rdparty/Sabre/HTTP/Version.php | 24 - 3rdparty/Sabre/LICENCE | 27 - 3rdparty/Sabre/VObject/Component.php | 254 --- 3rdparty/Sabre/VObject/Element.php | 15 - 3rdparty/Sabre/VObject/Element/DateTime.php | 245 --- .../Sabre/VObject/Element/MultiDateTime.php | 168 -- 3rdparty/Sabre/VObject/ElementList.php | 172 -- 3rdparty/Sabre/VObject/Node.php | 149 -- 3rdparty/Sabre/VObject/Parameter.php | 81 - 3rdparty/Sabre/VObject/ParseException.php | 12 - 3rdparty/Sabre/VObject/Property.php | 289 --- 3rdparty/Sabre/VObject/Reader.php | 191 -- 3rdparty/Sabre/VObject/Version.php | 24 - 3rdparty/Sabre/VObject/includes.php | 29 - 3rdparty/Sabre/autoload.php | 27 - 153 files changed, 20626 deletions(-) delete mode 100644 3rdparty/Sabre.includes.php delete mode 100644 3rdparty/Sabre/CalDAV/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/CalDAV/Backend/PDO.php delete mode 100644 3rdparty/Sabre/CalDAV/Calendar.php delete mode 100644 3rdparty/Sabre/CalDAV/CalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/CalendarRootNode.php delete mode 100644 3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/ICSExportPlugin.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendar.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendarObject.php delete mode 100644 3rdparty/Sabre/CalDAV/ICalendarUtil.php delete mode 100644 3rdparty/Sabre/CalDAV/Plugin.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/Collection.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php delete mode 100644 3rdparty/Sabre/CalDAV/Principal/User.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php delete mode 100644 3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php delete mode 100644 3rdparty/Sabre/CalDAV/Server.php delete mode 100644 3rdparty/Sabre/CalDAV/UserCalendars.php delete mode 100644 3rdparty/Sabre/CalDAV/Version.php delete mode 100644 3rdparty/Sabre/CalDAV/XMLUtil.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBook.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBookQueryParser.php delete mode 100644 3rdparty/Sabre/CardDAV/AddressBookRoot.php delete mode 100644 3rdparty/Sabre/CardDAV/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/CardDAV/Backend/PDO.php delete mode 100644 3rdparty/Sabre/CardDAV/Card.php delete mode 100644 3rdparty/Sabre/CardDAV/IAddressBook.php delete mode 100644 3rdparty/Sabre/CardDAV/ICard.php delete mode 100644 3rdparty/Sabre/CardDAV/IDirectory.php delete mode 100644 3rdparty/Sabre/CardDAV/Plugin.php delete mode 100644 3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php delete mode 100644 3rdparty/Sabre/CardDAV/UserAddressBooks.php delete mode 100644 3rdparty/Sabre/CardDAV/Version.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/Apache.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/File.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Backend/PDO.php delete mode 100644 3rdparty/Sabre/DAV/Auth/IBackend.php delete mode 100644 3rdparty/Sabre/DAV/Auth/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Browser/GuessContentType.php delete mode 100644 3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php delete mode 100644 3rdparty/Sabre/DAV/Browser/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Client.php delete mode 100644 3rdparty/Sabre/DAV/Collection.php delete mode 100644 3rdparty/Sabre/DAV/Directory.php delete mode 100644 3rdparty/Sabre/DAV/Exception.php delete mode 100644 3rdparty/Sabre/DAV/Exception/BadRequest.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Conflict.php delete mode 100644 3rdparty/Sabre/DAV/Exception/ConflictingLock.php delete mode 100644 3rdparty/Sabre/DAV/Exception/FileNotFound.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Forbidden.php delete mode 100644 3rdparty/Sabre/DAV/Exception/InsufficientStorage.php delete mode 100644 3rdparty/Sabre/DAV/Exception/InvalidResourceType.php delete mode 100644 3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php delete mode 100644 3rdparty/Sabre/DAV/Exception/Locked.php delete mode 100644 3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php delete mode 100644 3rdparty/Sabre/DAV/Exception/NotAuthenticated.php delete mode 100644 3rdparty/Sabre/DAV/Exception/NotImplemented.php delete mode 100644 3rdparty/Sabre/DAV/Exception/PreconditionFailed.php delete mode 100644 3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php delete mode 100644 3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php delete mode 100644 3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php delete mode 100644 3rdparty/Sabre/DAV/FS/Directory.php delete mode 100644 3rdparty/Sabre/DAV/FS/File.php delete mode 100644 3rdparty/Sabre/DAV/FS/Node.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/Directory.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/File.php delete mode 100644 3rdparty/Sabre/DAV/FSExt/Node.php delete mode 100644 3rdparty/Sabre/DAV/File.php delete mode 100644 3rdparty/Sabre/DAV/ICollection.php delete mode 100644 3rdparty/Sabre/DAV/IExtendedCollection.php delete mode 100644 3rdparty/Sabre/DAV/IFile.php delete mode 100644 3rdparty/Sabre/DAV/ILockable.php delete mode 100644 3rdparty/Sabre/DAV/INode.php delete mode 100644 3rdparty/Sabre/DAV/IProperties.php delete mode 100644 3rdparty/Sabre/DAV/IQuota.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/FS.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/File.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Backend/PDO.php delete mode 100644 3rdparty/Sabre/DAV/Locks/LockInfo.php delete mode 100644 3rdparty/Sabre/DAV/Locks/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Mount/Plugin.php delete mode 100644 3rdparty/Sabre/DAV/Node.php delete mode 100644 3rdparty/Sabre/DAV/ObjectTree.php delete mode 100644 3rdparty/Sabre/DAV/Property.php delete mode 100644 3rdparty/Sabre/DAV/Property/GetLastModified.php delete mode 100644 3rdparty/Sabre/DAV/Property/Href.php delete mode 100644 3rdparty/Sabre/DAV/Property/HrefList.php delete mode 100644 3rdparty/Sabre/DAV/Property/IHref.php delete mode 100644 3rdparty/Sabre/DAV/Property/LockDiscovery.php delete mode 100644 3rdparty/Sabre/DAV/Property/ResourceType.php delete mode 100644 3rdparty/Sabre/DAV/Property/Response.php delete mode 100644 3rdparty/Sabre/DAV/Property/ResponseList.php delete mode 100644 3rdparty/Sabre/DAV/Property/SupportedLock.php delete mode 100644 3rdparty/Sabre/DAV/Property/SupportedReportSet.php delete mode 100644 3rdparty/Sabre/DAV/Server.php delete mode 100644 3rdparty/Sabre/DAV/ServerPlugin.php delete mode 100644 3rdparty/Sabre/DAV/SimpleCollection.php delete mode 100644 3rdparty/Sabre/DAV/SimpleDirectory.php delete mode 100644 3rdparty/Sabre/DAV/SimpleFile.php delete mode 100644 3rdparty/Sabre/DAV/StringUtil.php delete mode 100644 3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php delete mode 100644 3rdparty/Sabre/DAV/Tree.php delete mode 100644 3rdparty/Sabre/DAV/Tree/Filesystem.php delete mode 100644 3rdparty/Sabre/DAV/URLUtil.php delete mode 100644 3rdparty/Sabre/DAV/UUIDUtil.php delete mode 100644 3rdparty/Sabre/DAV/Version.php delete mode 100644 3rdparty/Sabre/DAV/XMLUtil.php delete mode 100644 3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/AceConflict.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NoAbstract.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php delete mode 100644 3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php delete mode 100644 3rdparty/Sabre/DAVACL/IACL.php delete mode 100644 3rdparty/Sabre/DAVACL/IPrincipal.php delete mode 100644 3rdparty/Sabre/DAVACL/IPrincipalBackend.php delete mode 100644 3rdparty/Sabre/DAVACL/Plugin.php delete mode 100644 3rdparty/Sabre/DAVACL/Principal.php delete mode 100644 3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php delete mode 100644 3rdparty/Sabre/DAVACL/PrincipalCollection.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/Acl.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/Principal.php delete mode 100644 3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php delete mode 100644 3rdparty/Sabre/DAVACL/Version.php delete mode 100644 3rdparty/Sabre/HTTP/AWSAuth.php delete mode 100644 3rdparty/Sabre/HTTP/AbstractAuth.php delete mode 100644 3rdparty/Sabre/HTTP/BasicAuth.php delete mode 100644 3rdparty/Sabre/HTTP/DigestAuth.php delete mode 100644 3rdparty/Sabre/HTTP/Request.php delete mode 100644 3rdparty/Sabre/HTTP/Response.php delete mode 100644 3rdparty/Sabre/HTTP/Util.php delete mode 100644 3rdparty/Sabre/HTTP/Version.php delete mode 100644 3rdparty/Sabre/LICENCE delete mode 100644 3rdparty/Sabre/VObject/Component.php delete mode 100644 3rdparty/Sabre/VObject/Element.php delete mode 100644 3rdparty/Sabre/VObject/Element/DateTime.php delete mode 100644 3rdparty/Sabre/VObject/Element/MultiDateTime.php delete mode 100644 3rdparty/Sabre/VObject/ElementList.php delete mode 100644 3rdparty/Sabre/VObject/Node.php delete mode 100644 3rdparty/Sabre/VObject/Parameter.php delete mode 100644 3rdparty/Sabre/VObject/ParseException.php delete mode 100644 3rdparty/Sabre/VObject/Property.php delete mode 100644 3rdparty/Sabre/VObject/Reader.php delete mode 100644 3rdparty/Sabre/VObject/Version.php delete mode 100644 3rdparty/Sabre/VObject/includes.php delete mode 100644 3rdparty/Sabre/autoload.php diff --git a/3rdparty/Sabre.includes.php b/3rdparty/Sabre.includes.php deleted file mode 100644 index d41b287b77d..00000000000 --- a/3rdparty/Sabre.includes.php +++ /dev/null @@ -1,127 +0,0 @@ - array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - return false; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - abstract function deleteCalendar($calendarId); - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - abstract function getCalendarObjects($calendarId); - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - abstract function getCalendarObject($calendarId,$objectUri); - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function createCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function updateCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - abstract function deleteCalendarObject($calendarId,$objectUri); - -} diff --git a/3rdparty/Sabre/CalDAV/Backend/PDO.php b/3rdparty/Sabre/CalDAV/Backend/PDO.php deleted file mode 100644 index 7b1b33b912e..00000000000 --- a/3rdparty/Sabre/CalDAV/Backend/PDO.php +++ /dev/null @@ -1,386 +0,0 @@ - 'displayname', - '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', - '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', - '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', - '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', - ); - - /** - * Creates the backend - * - * @param PDO $pdo - */ - public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') { - - $this->pdo = $pdo; - $this->calendarTableName = $calendarTableName; - $this->calendarObjectTableName = $calendarObjectTableName; - - } - - /** - * Returns a list of calendars for a principal. - * - * Every project is an array with the following keys: - * * id, a unique id that will be used by other functions to modify the - * calendar. This can be the same as the uri or a database key. - * * uri, which the basename of the uri with which the calendar is - * accessed. - * * principalUri. The owner of the calendar. Almost always the same as - * principalUri passed to this method. - * - * Furthermore it can contain webdav properties in clark notation. A very - * common one is '{DAV:}displayname'. - * - * @param string $principalUri - * @return array - */ - public function getCalendarsForUser($principalUri) { - - $fields = array_values($this->propertyMap); - $fields[] = 'id'; - $fields[] = 'uri'; - $fields[] = 'ctag'; - $fields[] = 'components'; - $fields[] = 'principaluri'; - - // Making fields a comma-delimited list - $fields = implode(', ', $fields); - $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM `".$this->calendarTableName."` WHERE principaluri = ?"); - $stmt->execute(array($principalUri)); - - $calendars = array(); - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $components = explode(',',$row['components']); - - $calendar = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), - ); - - - foreach($this->propertyMap as $xmlName=>$dbName) { - $calendar[$xmlName] = $row[$dbName]; - } - - $calendars[] = $calendar; - - } - - return $calendars; - - } - - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - */ - public function createCalendar($principalUri,$calendarUri, array $properties) { - - $fieldNames = array( - 'principaluri', - 'uri', - 'ctag', - ); - $values = array( - ':principaluri' => $principalUri, - ':uri' => $calendarUri, - ':ctag' => 1, - ); - - // Default value - $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; - $fieldNames[] = 'components'; - if (!isset($properties[$sccs])) { - $values[':components'] = 'VEVENT,VTODO'; - } else { - if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { - throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); - } - $values[':components'] = implode(',',$properties[$sccs]->getValue()); - } - - foreach($this->propertyMap as $xmlName=>$dbName) { - if (isset($properties[$xmlName])) { - - $myValue = $properties[$xmlName]; - $values[':' . $dbName] = $properties[$xmlName]; - $fieldNames[] = $dbName; - } - } - - $stmt = $this->pdo->prepare("INSERT INTO `".$this->calendarTableName."` (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")"); - $stmt->execute($values); - - return $this->pdo->lastInsertId(); - - } - - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - $newValues = array(); - $result = array( - 200 => array(), // Ok - 403 => array(), // Forbidden - 424 => array(), // Failed Dependency - ); - - $hasError = false; - - foreach($mutations as $propertyName=>$propertyValue) { - - // We don't know about this property. - if (!isset($this->propertyMap[$propertyName])) { - $hasError = true; - $result[403][$propertyName] = null; - unset($mutations[$propertyName]); - continue; - } - - $fieldName = $this->propertyMap[$propertyName]; - $newValues[$fieldName] = $propertyValue; - - } - - // If there were any errors we need to fail the request - if ($hasError) { - // Properties has the remaining properties - foreach($mutations as $propertyName=>$propertyValue) { - $result[424][$propertyName] = null; - } - - // Removing unused statuscodes for cleanliness - foreach($result as $status=>$properties) { - if (is_array($properties) && count($properties)===0) unset($result[$status]); - } - - return $result; - - } - - // Success - - // Now we're generating the sql query. - $valuesSql = array(); - foreach($newValues as $fieldName=>$value) { - $valuesSql[] = $fieldName . ' = ?'; - } - $valuesSql[] = 'ctag = ctag + 1'; - - $stmt = $this->pdo->prepare("UPDATE `" . $this->calendarTableName . "` SET " . implode(', ',$valuesSql) . " WHERE id = ?"); - $newValues['id'] = $calendarId; - $stmt->execute(array_values($newValues)); - - return true; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - public function deleteCalendar($calendarId) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarTableName.'` WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - public function getCalendarObjects($calendarId) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - return $stmt->fetchAll(); - - } - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - public function getCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId, $objectUri)); - return $stmt->fetch(); - - } - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function createCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->calendarObjectTableName.'` (calendarid, uri, calendardata, lastmodified) VALUES (?,?,?,?)'); - $stmt->execute(array($calendarId,$objectUri,$calendarData,time())); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function updateCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarObjectTableName.'` SET calendardata = ?, lastmodified = ? WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarData,time(),$calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - public function deleteCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'. $this->calendarTableName .'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - -} diff --git a/3rdparty/Sabre/CalDAV/Calendar.php b/3rdparty/Sabre/CalDAV/Calendar.php deleted file mode 100644 index 0d2b3875771..00000000000 --- a/3rdparty/Sabre/CalDAV/Calendar.php +++ /dev/null @@ -1,318 +0,0 @@ -caldavBackend = $caldavBackend; - $this->principalBackend = $principalBackend; - $this->calendarInfo = $calendarInfo; - - - } - - /** - * Returns the name of the calendar - * - * @return string - */ - public function getName() { - - return $this->calendarInfo['uri']; - - } - - /** - * Updates properties such as the display name and description - * - * @param array $mutations - * @return array - */ - public function updateProperties($mutations) { - - return $this->caldavBackend->updateCalendar($this->calendarInfo['id'],$mutations); - - } - - /** - * Returns the list of properties - * - * @param array $properties - * @return array - */ - public function getProperties($requestedProperties) { - - $response = array(); - - foreach($requestedProperties as $prop) switch($prop) { - - case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCalendarData(); - break; - case '{urn:ietf:params:xml:ns:caldav}supported-collation-set' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); - break; - case '{DAV:}owner' : - $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,$this->calendarInfo['principaluri']); - break; - default : - if (isset($this->calendarInfo[$prop])) $response[$prop] = $this->calendarInfo[$prop]; - break; - - } - return $response; - - } - - /** - * Returns a calendar object - * - * The contained calendar objects are for example Events or Todo's. - * - * @param string $name - * @return Sabre_DAV_ICalendarObject - */ - public function getChild($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Calendar object not found'); - return new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - - } - - /** - * Returns the full list of calendar objects - * - * @return array - */ - public function getChildren() { - - $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - } - return $children; - - } - - /** - * Checks if a child-node exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) - return false; - else - return true; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in calendars. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in calendar objects is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid ICalendar string. - * - * @param string $name - * @param resource $calendarData - * @return void - */ - public function createFile($name,$calendarData = null) { - - $calendarData = stream_get_contents($calendarData); - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->createCalendarObject($this->calendarInfo['id'],$name,$calendarData); - - } - - /** - * Deletes the calendar. - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendar($this->calendarInfo['id']); - - } - - /** - * Renames the calendar. Note that most calendars use the - * {DAV:}displayname to display a name to display a name. - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming calendars is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/CalendarObject.php b/3rdparty/Sabre/CalDAV/CalendarObject.php deleted file mode 100644 index 0c99f18deb7..00000000000 --- a/3rdparty/Sabre/CalDAV/CalendarObject.php +++ /dev/null @@ -1,260 +0,0 @@ -caldavBackend = $caldavBackend; - - if (!isset($objectData['calendarid'])) { - throw new InvalidArgumentException('The objectData argument must contain a \'calendarid\' property'); - } - if (!isset($objectData['uri'])) { - throw new InvalidArgumentException('The objectData argument must contain an \'uri\' property'); - } - - $this->calendarInfo = $calendarInfo; - $this->objectData = $objectData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->objectData['uri']; - - } - - /** - * Returns the ICalendar-formatted object - * - * @return string - */ - public function get() { - - // Pre-populating the 'calendardata' is optional, if we don't have it - // already we fetch it from the backend. - if (!isset($this->objectData['calendardata'])) { - $this->objectData = $this->caldavBackend->getCalendarObject($this->objectData['calendarid'], $this->objectData['uri']); - } - return $this->objectData['calendardata']; - - } - - /** - * Updates the ICalendar-formatted object - * - * @param string $calendarData - * @return void - */ - public function put($calendarData) { - - if (is_resource($calendarData)) - $calendarData = stream_get_contents($calendarData); - - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'],$this->objectData['uri'],$calendarData); - $this->objectData['calendardata'] = $calendarData; - - } - - /** - * Deletes the calendar object - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'],$this->objectData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/calendar'; - - } - - /** - * Returns an ETag for this object. - * - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * @return string - */ - public function getETag() { - - if (isset($this->objectData['etag'])) { - return $this->objectData['etag']; - } else { - return '"' . md5($this->get()). '"'; - } - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return $this->objectData['lastmodified']; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->objectData['calendardata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} - diff --git a/3rdparty/Sabre/CalDAV/CalendarRootNode.php b/3rdparty/Sabre/CalDAV/CalendarRootNode.php deleted file mode 100644 index 69669a9d7fd..00000000000 --- a/3rdparty/Sabre/CalDAV/CalendarRootNode.php +++ /dev/null @@ -1,75 +0,0 @@ -caldavBackend = $caldavBackend; - - } - - /** - * Returns the nodename - * - * We're overriding this, because the default will be the 'principalPrefix', - * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT - * - * @return void - */ - public function getName() { - - return Sabre_CalDAV_Plugin::CALENDAR_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->caldavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php b/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php deleted file mode 100644 index 656b7286a66..00000000000 --- a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php +++ /dev/null @@ -1,18 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?export - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='export') return; - - // splitting uri - list($uri) = explode('?',$uri,2); - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_CalDAV_Calendar)) return; - - $this->server->httpResponse->setHeader('Content-Type','text/calendar'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($this->generateICS($this->server->tree->getChildren($uri))); - - // Returning false to break the event chain - return false; - - } - - /** - * Merges all calendar objects, and builds one big ics export - * - * @param array $nodes - * @return void - */ - public function generateICS(array $nodes) { - - $calendar = new Sabre_VObject_Component('vcalendar'); - $calendar->version = '2.0'; - $calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN'; - $calendar->calscale = 'GREGORIAN'; - - $collectedTimezones = array(); - - $timezones = array(); - $objects = array(); - - foreach($nodes as $node) { - - $nodeData = $node->get(); - $nodeComp = Sabre_VObject_Reader::read($nodeData); - - foreach($nodeComp->children() as $child) { - - switch($child->name) { - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : - $objects[] = $child; - break; - - // VTIMEZONE is special, because we need to filter out the duplicates - case 'VTIMEZONE' : - // Naively just checking tzid. - if (in_array((string)$child->TZID, $collectedTimezones)) continue; - - $timezones[] = $child; - $collectedTimezones[] = $child->TZID; - break; - - - } - - - } - - - } - - foreach($timezones as $tz) $calendar->add($tz); - foreach($objects as $obj) $calendar->add($obj); - - return $calendar->serialize(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/ICalendar.php b/3rdparty/Sabre/CalDAV/ICalendar.php deleted file mode 100644 index 8193dff3a83..00000000000 --- a/3rdparty/Sabre/CalDAV/ICalendar.php +++ /dev/null @@ -1,18 +0,0 @@ -registerXPathNameSpace('cal','urn:ietf:params:xml:ns:xcal'); - - // Check if there's only 1 component - $components = array('vevent','vtodo','vjournal','vfreebusy'); - $componentsFound = array(); - - foreach($components as $component) { - $test = $xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:' . $component); - if (is_array($test)) $componentsFound = array_merge($componentsFound, $test); - } - if (count($componentsFound)<1) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('One VEVENT, VTODO, VJOURNAL or VFREEBUSY must be specified. 0 found.'); - } - $component = $componentsFound[0]; - - if (is_null($allowedComponents)) return true; - - // Check if the component is allowed - $name = $component->getName(); - if (!in_array(strtoupper($name),$allowedComponents)) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject(strtoupper($name) . ' is not allowed in this calendar.'); - } - - if (count($xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:method'))>0) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('The METHOD property is not allowed in calendar objects'); - } - - return true; - - } - - /** - * Converts ICalendar data to XML. - * - * Properties are converted to lowercase xml elements. Parameters are; - * converted to attributes. BEGIN:VEVENT is converted to and - * END:VEVENT as well as other components. - * - * It's a very loose parser. If any line does not conform to the spec, it - * will simply be ignored. It will try to detect if \r\n or \n line endings - * are used. - * - * @todo Currently quoted attributes are not parsed correctly. - * @see http://tools.ietf.org/html/draft-royer-calsch-xcal-03 - * @param string $icalData - * @return string. - */ - static function toXCAL($icalData) { - - // Detecting line endings - $lb="\r\n"; - if (strpos($icalData,"\r\n")!==false) $lb = "\r\n"; - elseif (strpos($icalData,"\n")!==false) $lb = "\n"; - - // Splitting up items per line - $lines = explode($lb,$icalData); - - // Properties can be folded over 2 lines. In this case the second - // line will be preceeded by a space or tab. - $lines2 = array(); - foreach($lines as $line) { - - if (!$line) continue; - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - continue; - } - - $lines2[]=$line; - - } - - $xml = '' . "\n"; - $xml.= "\n"; - - $spaces = 2; - foreach($lines2 as $line) { - - $matches = array(); - // This matches PROPERTYNAME;ATTRIBUTES:VALUE - if (!preg_match('/^([^:^;]*)(?:;([^:]*))?:(.*)$/',$line,$matches)) - continue; - - $propertyName = strtolower($matches[1]); - $attributes = $matches[2]; - $value = $matches[3]; - - // If the line was in the format BEGIN:COMPONENT or END:COMPONENT, we need to special case it. - if ($propertyName === 'begin') { - $xml.=str_repeat(" ",$spaces); - $xml.='<' . strtolower($value) . ">\n"; - $spaces+=2; - continue; - } elseif ($propertyName === 'end') { - $spaces-=2; - $xml.=str_repeat(" ",$spaces); - $xml.='\n"; - continue; - } - - $xml.=str_repeat(" ",$spaces); - $xml.='<' . $propertyName; - if ($attributes) { - // There can be multiple attributes - $attributes = explode(';',$attributes); - foreach($attributes as $att) { - - list($attName,$attValue) = explode('=',$att,2); - $attName = strtolower($attName); - if ($attName === 'language') $attName='xml:lang'; - $xml.=' ' . $attName . '="' . htmlspecialchars($attValue) . '"'; - - } - } - - $xml.='>'. htmlspecialchars(trim($value)) . '\n"; - - } - $xml.=""; - return $xml; - - } - -} - diff --git a/3rdparty/Sabre/CalDAV/Plugin.php b/3rdparty/Sabre/CalDAV/Plugin.php deleted file mode 100644 index 02747c8395e..00000000000 --- a/3rdparty/Sabre/CalDAV/Plugin.php +++ /dev/null @@ -1,788 +0,0 @@ -server->tree->getNodeForPath($parent); - - if ($node instanceof Sabre_DAV_IExtendedCollection) { - try { - $node->getChild($name); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - return array('MKCALENDAR'); - } - } - return array(); - - } - - /** - * Returns a list of features for the DAV: HTTP header. - * - * @return array - */ - public function getFeatures() { - - return array('calendar-access', 'calendar-proxy'); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'caldav'; - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CalDAV_ICalendar || $node instanceof Sabre_CalDAV_ICalendarObject) { - return array( - '{' . self::NS_CALDAV . '}calendar-multiget', - '{' . self::NS_CALDAV . '}calendar-query', - ); - } - return array(); - - } - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - //$server->subscribeEvent('unknownMethod',array($this,'unknownMethod2'),1000); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->xmlNamespaces[self::NS_CALDAV] = 'cal'; - $server->xmlNamespaces[self::NS_CALENDARSERVER] = 'cs'; - - $server->propertyMap['{' . self::NS_CALDAV . '}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; - - $server->resourceTypeMapping['Sabre_CalDAV_ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write'; - - array_push($server->protectedProperties, - - '{' . self::NS_CALDAV . '}supported-calendar-component-set', - '{' . self::NS_CALDAV . '}supported-calendar-data', - '{' . self::NS_CALDAV . '}max-resource-size', - '{' . self::NS_CALDAV . '}min-date-time', - '{' . self::NS_CALDAV . '}max-date-time', - '{' . self::NS_CALDAV . '}max-instances', - '{' . self::NS_CALDAV . '}max-attendees-per-instance', - '{' . self::NS_CALDAV . '}calendar-home-set', - '{' . self::NS_CALDAV . '}supported-collation-set', - '{' . self::NS_CALDAV . '}calendar-data', - - // scheduling extension - '{' . self::NS_CALDAV . '}calendar-user-address-set', - - // CalendarServer extensions - '{' . self::NS_CALENDARSERVER . '}getctag', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for' - - ); - } - - /** - * This function handles support for the MKCALENDAR method - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - if ($method!=='MKCALENDAR') return; - - $this->httpMkCalendar($uri); - // false is returned to stop the unknownMethod event - return false; - - } - - /** - * This functions handles REPORT requests specific to CalDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CALDAV.'}calendar-multiget' : - $this->calendarMultiGetReport($dom); - return false; - case '{'.self::NS_CALDAV.'}calendar-query' : - $this->calendarQueryReport($dom); - return false; - - } - - - } - - /** - * This function handles the MKCALENDAR HTTP method, which creates - * a new calendar. - * - * @param string $uri - * @return void - */ - public function httpMkCalendar($uri) { - - // Due to unforgivable bugs in iCal, we're completely disabling MKCALENDAR support - // for clients matching iCal in the user agent - //$ua = $this->server->httpRequest->getHeader('User-Agent'); - //if (strpos($ua,'iCal/')!==false) { - // throw new Sabre_DAV_Exception_Forbidden('iCal has major bugs in it\'s RFC3744 support. Therefore we are left with no other choice but disabling this feature.'); - //} - - $body = $this->server->httpRequest->getBody(true); - $properties = array(); - - if ($body) { - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - foreach($dom->firstChild->childNodes as $child) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($child)!=='{DAV:}set') continue; - foreach(Sabre_DAV_XMLUtil::parseProperties($child,$this->server->propertyMap) as $k=>$prop) { - $properties[$k] = $prop; - } - - } - } - - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); - - $this->server->createCollection($uri,$resourceType,$properties); - - $this->server->httpResponse->sendStatus(201); - $this->server->httpResponse->setHeader('Content-Length',0); - } - - /** - * beforeGetProperties - * - * This method handler is invoked before any after properties for a - * resource are fetched. This allows us to add in any CalDAV specific - * properties. - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $calHome = '{' . self::NS_CALDAV . '}calendar-home-set'; - if (in_array($calHome,$requestedProperties)) { - $principalId = $node->getName(); - $calendarHomePath = self::CALENDAR_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[$calHome]); - $returnedProperties[200][$calHome] = new Sabre_DAV_Property_Href($calendarHomePath); - } - - // calendar-user-address-set property - $calProp = '{' . self::NS_CALDAV . '}calendar-user-address-set'; - if (in_array($calProp,$requestedProperties)) { - - $addresses = $node->getAlternateUriSet(); - $addresses[] = $this->server->getBaseUri() . $node->getPrincipalUrl(); - unset($requestedProperties[$calProp]); - $returnedProperties[200][$calProp] = new Sabre_DAV_Property_HrefList($addresses, false); - - } - - // These two properties are shortcuts for ical to easily find - // other principals this principal has access to. - $propRead = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for'; - $propWrite = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for'; - if (in_array($propRead,$requestedProperties) || in_array($propWrite,$requestedProperties)) { - - $membership = $node->getGroupMembership(); - $readList = array(); - $writeList = array(); - - foreach($membership as $group) { - - $groupNode = $this->server->tree->getNodeForPath($group); - - // If the node is either ap proxy-read or proxy-write - // group, we grab the parent principal and add it to the - // list. - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyRead) { - list($readList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyWrite) { - list($writeList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - - } - if (in_array($propRead,$requestedProperties)) { - unset($requestedProperties[$propRead]); - $returnedProperties[200][$propRead] = new Sabre_DAV_Property_HrefList($readList); - } - if (in_array($propWrite,$requestedProperties)) { - unset($requestedProperties[$propWrite]); - $returnedProperties[200][$propWrite] = new Sabre_DAV_Property_HrefList($writeList); - } - - } - - } // instanceof IPrincipal - - - if ($node instanceof Sabre_CalDAV_ICalendarObject) { - // The calendar-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $calDataProp = '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'; - if (in_array($calDataProp, $requestedProperties)) { - unset($requestedProperties[$calDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$calDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This function handles the calendar-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function calendarMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - foreach($hrefElems as $elem) { - $uri = $this->server->calculateUri($elem->nodeValue); - list($objProps) = $this->server->getPropertiesForPath($uri,$properties); - $propertyList[]=$objProps; - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the calendar-query REPORT - * - * This report is used by clients to request calendar objects based on - * complex conditions. - * - * @param DOMNode $dom - * @return void - */ - public function calendarQueryReport($dom) { - - $requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $filterNode = $dom->getElementsByTagNameNS('urn:ietf:params:xml:ns:caldav','filter'); - if ($filterNode->length!==1) { - throw new Sabre_DAV_Exception_BadRequest('The calendar-query report must have a filter element'); - } - $filters = Sabre_CalDAV_XMLUtil::parseCalendarQueryFilters($filterNode->item(0)); - - $requestedCalendarData = true; - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar-data', $requestedProperties)) { - // We always retrieve calendar-data, as we need it for filtering. - $requestedProperties[] = '{urn:ietf:params:xml:ns:caldav}calendar-data'; - - // If calendar-data wasn't explicitly requested, we need to remove - // it after processing. - $requestedCalendarData = false; - } - - // These are the list of nodes that potentially match the requirement - $candidateNodes = $this->server->getPropertiesForPath($this->server->getRequestUri(),$requestedProperties,$this->server->getHTTPDepth(0)); - - $verifiedNodes = array(); - - foreach($candidateNodes as $node) { - - // If the node didn't have a calendar-data property, it must not be a calendar object - if (!isset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) continue; - - if ($this->validateFilters($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'],$filters)) { - - if (!$requestedCalendarData) { - unset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); - } - $verifiedNodes[] = $node; - } - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($verifiedNodes)); - - } - - - /** - * Verify if a list of filters applies to the calendar data object - * - * The calendarData object must be a valid iCalendar blob. The list of - * filters must be formatted as parsed by Sabre_CalDAV_Plugin::parseCalendarQueryFilters - * - * @param string $calendarData - * @param array $filters - * @return bool - */ - public function validateFilters($calendarData,$filters) { - - // We are converting the calendar object to an XML structure - // This makes it far easier to parse - $xCalendarData = Sabre_CalDAV_ICalendarUtil::toXCal($calendarData); - $xml = simplexml_load_string($xCalendarData); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:xcal'); - - foreach($filters as $xpath=>$filter) { - - // if-not-defined comes first - if (isset($filter['is-not-defined'])) { - if (!$xml->xpath($xpath)) - continue; - else - return false; - - } - - $elem = $xml->xpath($xpath); - - if (!$elem) return false; - $elem = $elem[0]; - - if (isset($filter['time-range'])) { - - switch($elem->getName()) { - case 'vevent' : - $result = $this->validateTimeRangeFilterForEvent($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vtodo' : - $result = $this->validateTimeRangeFilterForTodo($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vjournal' : - case 'vfreebusy' : - case 'valarm' : - // TODO: not implemented - break; - - /* - - case 'vjournal' : - $result = $this->validateTimeRangeFilterForJournal($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vfreebusy' : - $result = $this->validateTimeRangeFilterForFreeBusy($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'valarm' : - $result = $this->validateTimeRangeFilterForAlarm($xml,$xpath,$filter); - if ($result===false) return false; - break; - - */ - - } - - } - - if (isset($filter['text-match'])) { - $currentString = (string)$elem; - - $isMatching = Sabre_DAV_StringUtil::textMatch($currentString, $filter['text-match']['value'], $filter['text-match']['collation']); - if ($filter['text-match']['negate-condition'] && $isMatching) return false; - if (!$filter['text-match']['negate-condition'] && !$isMatching) return false; - - } - - } - return true; - - } - - /** - * Checks whether a time-range filter matches an event. - * - * @param SimpleXMLElement $xml Event as xml object - * @param string $currentXPath XPath to check - * @param array $currentFilter Filter information - * @return void - */ - private function validateTimeRangeFilterForEvent(SimpleXMLElement $xml,$currentXPath,array $currentFilter) { - - // Grabbing the DTSTART property - $xdtstart = $xml->xpath($currentXPath.'/c:dtstart'); - if (!count($xdtstart)) { - throw new Sabre_DAV_Exception_BadRequest('DTSTART property missing from calendar object'); - } - - // The dtstart can be both a date, or datetime property - if ((string)$xdtstart[0]['value']==='DATE' || strlen((string)$xdtstart[0])===8) { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdtstart[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtstart[0],$tz); - } else { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtstart[0]); - } - - - // Grabbing the DTEND property - $xdtend = $xml->xpath($currentXPath.'/c:dtend'); - $dtend = null; - - if (count($xdtend)) { - // Determining the timezone - if ($tzid = (string)$xdtend[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - - // Since the VALUE prameter of both DTSTART and DTEND must be the same - // we can assume we don't need to check the VALUE paramter of DTEND. - if ($isDateTime) { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtend[0],$tz); - } else { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtend[0],$tz); - } - - } - - if (is_null($dtend)) { - // The DTEND property was not found. We will first see if the event has a duration - // property - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - - // Making sure that the duration is bigger than 0 seconds. - $tempDT = clone $dtstart; - $tempDT->modify($duration); - if ($tempDT > $dtstart) { - - // use DTEND = DTSTART + DURATION - $dtend = $tempDT; - } else { - // use DTEND = DTSTART - $dtend = $dtstart; - } - - } - } - - if (is_null($dtend)) { - if ($isDateTime) { - // DTEND = DTSTART - $dtend = $dtstart; - } else { - // DTEND = DTSTART + 1 DAY - $dtend = clone $dtstart; - $dtend->modify('+1 day'); - } - } - // TODO: we need to properly parse RRULE's, but it's very difficult. - // For now, we're always returning events if they have an RRULE at all. - $rrule = $xml->xpath($currentXPath.'/c:rrule'); - $hasRrule = (count($rrule))>0; - - if (!is_null($currentFilter['time-range']['start']) && $currentFilter['time-range']['start'] >= $dtend) return false; - if (!is_null($currentFilter['time-range']['end']) && $currentFilter['time-range']['end'] <= $dtstart && !$hasRrule) return false; - return true; - - } - - private function validateTimeRangeFilterForTodo(SimpleXMLElement $xml,$currentXPath,array $filter) { - - // Gathering all relevant elements - - $dtStart = null; - $duration = null; - $due = null; - $completed = null; - $created = null; - - $xdt = $xml->xpath($currentXPath.'/c:dtstart'); - if (count($xdt)) { - // The dtstart can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - // Only need to grab duration if dtStart is set - if (!is_null($dtStart)) { - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - } - - } - - if (!is_null($dtStart) && !is_null($duration)) { - - // Comparision from RFC 4791: - // (start <= DTSTART+DURATION) AND ((end > DTSTART) OR (end >= DTSTART+DURATION)) - - $end = clone $dtStart; - $end->modify($duration); - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $end) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart || $filter['time-range']['end'] >= $end) ) { - return true; - } else { - return false; - } - - } - - // Need to grab the DUE property - $xdt = $xml->xpath($currentXPath.'/c:due'); - if (count($xdt)) { - // The due property can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - if (!is_null($dtStart) && !is_null($due)) { - - // Comparision from RFC 4791: - // ((start < DUE) OR (start <= DTSTART)) AND ((end > DTSTART) OR (end >= DUE)) - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due || $filter['time-range']['start'] < $dtstart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($dtStart)) { - - // Comparision from RFC 4791 - // (start <= DTSTART) AND (end > DTSTART) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $dtStart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($due)) { - - // Comparison from RFC 4791 - // (start < DUE) AND (end >= DUE) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - // Need to grab the COMPLETED property - $xdt = $xml->xpath($currentXPath.'/c:completed'); - if (count($xdt)) { - $completed = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - // Need to grab the CREATED property - $xdt = $xml->xpath($currentXPath.'/c:created'); - if (count($xdt)) { - $created = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - - if (!is_null($completed) && !is_null($created)) { - // Comparison from RFC 4791 - // ((start <= CREATED) OR (start <= COMPLETED)) AND ((end >= CREATED) OR (end >= COMPLETED)) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $created || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $created || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($completed)) { - // Comparison from RFC 4791 - // (start <= COMPLETED) AND (end >= COMPLETED) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($created)) { - // Comparison from RFC 4791 - // (end > CREATED) - if( (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $created) ) { - return true; - } else { - return false; - } - } - - // Everything else is TRUE - return true; - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/Collection.php b/3rdparty/Sabre/CalDAV/Principal/Collection.php deleted file mode 100644 index 13435b2448e..00000000000 --- a/3rdparty/Sabre/CalDAV/Principal/Collection.php +++ /dev/null @@ -1,31 +0,0 @@ -principalBackend, $principalInfo); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php b/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php deleted file mode 100644 index f531d85d1ff..00000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php +++ /dev/null @@ -1,178 +0,0 @@ -principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-read'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php b/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php deleted file mode 100644 index 4d8face2060..00000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php +++ /dev/null @@ -1,178 +0,0 @@ -principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-write'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/User.php b/3rdparty/Sabre/CalDAV/Principal/User.php deleted file mode 100644 index 034629b89b3..00000000000 --- a/3rdparty/Sabre/CalDAV/Principal/User.php +++ /dev/null @@ -1,122 +0,0 @@ -principalBackend, $this->principalProperties); - - if ($name === 'calendar-proxy-write') - return new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); - - throw new Sabre_DAV_Exception_FileNotFound('Node with name ' . $name . ' was not found'); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - return array( - new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties), - new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties), - ); - - } - - /** - * Checks if a child-node with the specified name exists - * - * @return bool - */ - public function childExists($name) { - - return $name === 'calendar-proxy-read' || $name === 'calendar-proxy-write'; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - ); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php deleted file mode 100644 index 1bbaca6b8a7..00000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php +++ /dev/null @@ -1,85 +0,0 @@ -components = $components; - - } - - /** - * Returns the list of supported components - * - * @return array - */ - public function getValue() { - - return $this->components; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->components as $component) { - - $xcomp = $doc->createElement('cal:comp'); - $xcomp->setAttribute('name',$component); - $node->appendChild($xcomp); - - } - - } - - /** - * Unserializes the DOMElement back into a Property class. - * - * @param DOMElement $node - * @return void - */ - static function unserialize(DOMElement $node) { - - $components = array(); - foreach($node->childNodes as $childNode) { - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)==='{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}comp') { - $components[] = $childNode->getAttribute('name'); - } - } - return new self($components); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php deleted file mode 100644 index 5010ee6d525..00000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php +++ /dev/null @@ -1,38 +0,0 @@ -ownerDocument; - - $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV])?$server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]:'cal'; - - $caldata = $doc->createElement($prefix . ':calendar-data'); - $caldata->setAttribute('content-type','text/calendar'); - $caldata->setAttribute('version','2.0'); - - $node->appendChild($caldata); - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php deleted file mode 100644 index e585e9db3d8..00000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php +++ /dev/null @@ -1,44 +0,0 @@ -ownerDocument; - - $prefix = $node->lookupPrefix('urn:ietf:params:xml:ns:caldav'); - if (!$prefix) $prefix = 'cal'; - - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;ascii-casemap') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;octet') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;unicode-casemap') - ); - - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Server.php b/3rdparty/Sabre/CalDAV/Server.php deleted file mode 100644 index 969d69c6279..00000000000 --- a/3rdparty/Sabre/CalDAV/Server.php +++ /dev/null @@ -1,65 +0,0 @@ -authRealm); - $this->addPlugin($authPlugin); - - $aclPlugin = new Sabre_DAVACL_Plugin(); - $this->addPlugin($aclPlugin); - - $caldavPlugin = new Sabre_CalDAV_Plugin(); - $this->addPlugin($caldavPlugin); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/UserCalendars.php b/3rdparty/Sabre/CalDAV/UserCalendars.php deleted file mode 100644 index f52d65e9a73..00000000000 --- a/3rdparty/Sabre/CalDAV/UserCalendars.php +++ /dev/null @@ -1,280 +0,0 @@ -principalBackend = $principalBackend; - $this->caldavBackend = $caldavBackend; - $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CalDAV_Calendar - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Calendar with name \'' . $name . '\' could not be found'); - - } - - /** - * Checks if a calendar exists. - * - * @param string $name - * @todo needs optimizing - * @return bool - */ - public function childExists($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return true; - - } - return false; - - } - - /** - * Returns a list of calendars - * - * @return array - */ - public function getChildren() { - - $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']); - $objs = array(); - foreach($calendars as $calendar) { - $objs[] = new Sabre_CalDAV_Calendar($this->principalBackend, $this->caldavBackend, $calendar); - } - return $objs; - - } - - /** - * Creates a new calendar - * - * @param string $name - * @param string $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->caldavBackend->createCalendar($this->principalInfo['uri'], $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalInfo['uri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/Version.php b/3rdparty/Sabre/CalDAV/Version.php deleted file mode 100644 index df8fe1f6bd6..00000000000 --- a/3rdparty/Sabre/CalDAV/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -childNodes as $child) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($child)) { - - case '{urn:ietf:params:xml:ns:caldav}comp-filter' : - case '{urn:ietf:params:xml:ns:caldav}prop-filter' : - - $filterName = $basePath . '/' . 'c:' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - - self::parseCalendarQueryFilters($child, $filterName,$filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}time-range' : - - if ($start = $child->getAttribute('start')) { - $start = self::parseICalendarDateTime($start); - } else { - $start = null; - } - if ($end = $child->getAttribute('end')) { - $end = self::parseICalendarDateTime($end); - } else { - $end = null; - } - - if (!is_null($start) && !is_null($end) && $end <= $start) { - throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the time-range filter'); - } - - $filters[$basePath]['time-range'] = array( - 'start' => $start, - 'end' => $end - ); - break; - - case '{urn:ietf:params:xml:ns:caldav}is-not-defined' : - $filters[$basePath]['is-not-defined'] = true; - break; - - case '{urn:ietf:params:xml:ns:caldav}param-filter' : - - $filterName = $basePath . '/@' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - self::parseCalendarQueryFilters($child, $filterName, $filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}text-match' : - - $collation = $child->getAttribute('collation'); - if (!$collation) $collation = 'i;ascii-casemap'; - - $filters[$basePath]['text-match'] = array( - 'collation' => ($collation == 'default'?'i;ascii-casemap':$collation), - 'negate-condition' => $child->getAttribute('negate-condition')==='yes', - 'value' => $child->nodeValue, - ); - break; - - } - - } - - return $filters; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * Specifying a reference timezone is optional. It will only be used - * if the non-UTC format is used. The argument is used as a reference, the - * returned DateTime object will still be in the UTC timezone. - * - * @param string $dt - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDateTime($dt,DateTimeZone $tz = null) { - - // Format is YYYYMMDD + "T" + hhmmss - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/',$dt,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar datetime value is incorrect: ' . $dt); - } - - if ($matches[7]==='Z' || is_null($tz)) { - $tz = new DateTimeZone('UTC'); - } - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz); - - // Still resetting the timezone, to normalize everything to UTC - $date->setTimeZone(new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * @param string $date - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDate($date) { - - // Format is YYYYMMDD - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar date value is incorrect: ' . $date); - } - - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (RFC5545) formatted duration and returns a string suitable - * for strtotime or DateTime::modify. - * - * NOTE: When we require PHP 5.3 this can be replaced by the DateTimeInterval object, which - * supports ISO 8601 Intervals, which is a superset of ICalendar durations. - * - * For now though, we're just gonna live with this messy system - * - * @param string $duration - * @return string - */ - static public function parseICalendarDuration($duration) { - - $result = preg_match('/^(?P\+|-)?P((?P\d+)W)?((?P\d+)D)?(T((?P\d+)H)?((?P\d+)M)?((?P\d+)S)?)?$/', $duration, $matches); - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar duration value is incorrect: ' . $duration); - } - - $parts = array( - 'week', - 'day', - 'hour', - 'minute', - 'second', - ); - - $newDur = ''; - foreach($parts as $part) { - if (isset($matches[$part]) && $matches[$part]) { - $newDur.=' '.$matches[$part] . ' ' . $part . 's'; - } - } - - $newDur = ($matches['plusminus']==='-'?'-':'+') . trim($newDur); - return $newDur; - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBook.php b/3rdparty/Sabre/CardDAV/AddressBook.php deleted file mode 100644 index 471ca7b338a..00000000000 --- a/3rdparty/Sabre/CardDAV/AddressBook.php +++ /dev/null @@ -1,293 +0,0 @@ -carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - - } - - /** - * Returns the name of the addressbook - * - * @return string - */ - public function getName() { - - return $this->addressBookInfo['uri']; - - } - - /** - * Returns a card - * - * @param string $name - * @return Sabre_DAV_Card - */ - public function getChild($name) { - - $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Card not found'); - return new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - - } - - /** - * Returns the full list of cards - * - * @return array - */ - public function getChildren() { - - $objs = $this->carddavBackend->getCards($this->addressBookInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - } - return $children; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in addressbooks. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in addressbooks is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid VCARD - * - * @param string $name - * @param resource $vcardData - * @return void - */ - public function createFile($name,$vcardData = null) { - - $vcardData = stream_get_contents($vcardData); - // Converting to UTF-8, if needed - $vcardData = Sabre_DAV_StringUtil::ensureUTF8($vcardData); - - $this->carddavBackend->createCard($this->addressBookInfo['id'],$name,$vcardData); - - } - - /** - * Deletes the entire addressbook. - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteAddressBook($this->addressBookInfo['id']); - - } - - /** - * Renames the addressbook - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming addressbooks is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Updates properties on this node, - * - * The properties array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - public function updateProperties($mutations) { - - return $this->carddavBackend->updateAddressBook($this->addressBookInfo['id'], $mutations); - - } - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - public function getProperties($properties) { - - $response = array(); - foreach($properties as $propertyName) { - - if (isset($this->addressBookInfo[$propertyName])) { - - $response[$propertyName] = $this->addressBookInfo[$propertyName]; - - } - - } - - return $response; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php b/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php deleted file mode 100644 index 08adc3b8157..00000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php +++ /dev/null @@ -1,211 +0,0 @@ -dom = $dom; - - $this->xpath = new DOMXPath($dom); - $this->xpath->registerNameSpace('card',Sabre_CardDAV_Plugin::NS_CARDDAV); - - } - - /** - * Parses the request. - * - * @param DOMNode $dom - * @return void - */ - public function parse() { - - $filterNode = null; - - $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); - if (is_nan($limit)) $limit = null; - - $filter = $this->xpath->query('/card:addressbook-query/card:filter'); - if ($filter->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); - } - - $filter = $filter->item(0); - $test = $this->xpath->evaluate('string(@test)', $filter); - if (!$test) $test = self::TEST_ANYOF; - if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { - throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"'); - } - - $propFilters = array(); - - $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); - for($ii=0; $ii < $propFilterNodes->length; $ii++) { - - $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); - - - } - - $this->filters = $propFilters; - $this->limit = $limit; - $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); - $this->test = $test; - - } - - /** - * Parses the prop-filter xml element - * - * @param DOMElement $propFilterNode - * @return array - */ - protected function parsePropFilterNode(DOMElement $propFilterNode) { - - $propFilter = array(); - $propFilter['name'] = $propFilterNode->getAttribute('name'); - $propFilter['test'] = $propFilterNode->getAttribute('test'); - if (!$propFilter['test']) $propFilter['test'] = 'anyof'; - - $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; - - $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); - - $propFilter['param-filters'] = array(); - - - for($ii=0;$ii<$paramFilterNodes->length;$ii++) { - - $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); - - } - $propFilter['text-matches'] = array(); - $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); - - for($ii=0;$ii<$textMatchNodes->length;$ii++) { - - $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); - - } - - return $propFilter; - - } - - /** - * Parses the param-filter element - * - * @param DOMElement $paramFilterNode - * @return array - */ - public function parseParamFilterNode(DOMElement $paramFilterNode) { - - $paramFilter = array(); - $paramFilter['name'] = $paramFilterNode->getAttribute('name'); - $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; - $paramFilter['text-match'] = null; - - $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); - if ($textMatch->length>0) { - $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); - } - - return $paramFilter; - - } - - /** - * Text match - * - * @param DOMElement $textMatchNode - * @return void - */ - public function parseTextMatchNode(DOMElement $textMatchNode) { - - $matchType = $textMatchNode->getAttribute('match-type'); - if (!$matchType) $matchType = 'contains'; - - if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { - throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: ' . $matchType); - } - - $negateCondition = $textMatchNode->getAttribute('negate-condition'); - $negateCondition = $negateCondition==='yes'; - $collation = $textMatchNode->getAttribute('collation'); - if (!$collation) $collation = 'i;unicode-casemap'; - - return array( - 'negate-condition' => $negateCondition, - 'collation' => $collation, - 'match-type' => $matchType, - 'value' => $textMatchNode->nodeValue - ); - - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookRoot.php b/3rdparty/Sabre/CardDAV/AddressBookRoot.php deleted file mode 100644 index 1a80efba35e..00000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookRoot.php +++ /dev/null @@ -1,78 +0,0 @@ -carddavBackend = $carddavBackend; - parent::__construct($principalBackend, $principalPrefix); - - } - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CardDAV_UserAddressBooks($this->carddavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CardDAV/Backend/Abstract.php b/3rdparty/Sabre/CardDAV/Backend/Abstract.php deleted file mode 100644 index 1f0253ddab8..00000000000 --- a/3rdparty/Sabre/CardDAV/Backend/Abstract.php +++ /dev/null @@ -1,121 +0,0 @@ -pdo = $pdo; - $this->addressBooksTableName = $addressBooksTableName; - $this->cardsTableName = $cardsTableName; - - } - - /** - * Returns the list of addressbooks for a specific user. - * - * @param string $principalUri - * @return array - */ - public function getAddressBooksForUser($principalUri) { - - $stmt = $this->pdo->prepare('SELECT id, uri, displayname, principaluri, description, ctag FROM `'.$this->addressBooksTableName.'` WHERE principaluri = ?'); - $result = $stmt->execute(array($principalUri)); - - $addressBooks = array(); - - foreach($stmt->fetchAll() as $row) { - - $addressBooks[] = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{DAV:}displayname' => $row['displayname'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['ctag'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => - new Sabre_CardDAV_Property_SupportedAddressData(), - ); - - } - - return $addressBooks; - - } - - - /** - * Updates an addressbook's properties - * - * See Sabre_DAV_IProperties for a description of the mutations array, as - * well as the return value. - * - * @param mixed $addressBookId - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateAddressBook($addressBookId, array $mutations) { - - $updates = array(); - - foreach($mutations as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $updates['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $updates['description'] = $newValue; - break; - default : - // If any unsupported values were being updated, we must - // let the entire request fail. - return false; - } - - } - - // No values are being updated? - if (!$updates) { - return false; - } - - $query = 'UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 '; - foreach($updates as $key=>$value) { - $query.=', `' . $key . '` = :' . $key . ' '; - } - $query.=' WHERE id = :addressbookid'; - - $stmt = $this->pdo->prepare($query); - $updates['addressbookid'] = $addressBookId; - - $stmt->execute($updates); - - return true; - - } - - /** - * Creates a new address book - * - * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @return void - */ - public function createAddressBook($principalUri, $url, array $properties) { - - $values = array( - 'displayname' => null, - 'description' => null, - 'principaluri' => $principalUri, - 'uri' => $url, - ); - - foreach($properties as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $values['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $values['description'] = $newValue; - break; - default : - throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); - } - - } - - $query = 'INSERT INTO `' . $this->addressBooksTableName . '` (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; - $stmt = $this->pdo->prepare($query); - $stmt->execute($values); - - } - - /** - * Deletes an entire addressbook and all its contents - * - * @param int $addressBookId - * @return void - */ - public function deleteAddressBook($addressBookId) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressBookId)); - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->addressBooksTableName . '` WHERE id = ?'); - $stmt->execute(array($addressBookId)); - - } - - /** - * Returns all cards for a specific addressbook id. - * - * @param mixed $addressbookId - * @return array - */ - public function getCards($addressbookId) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressbookId)); - - return $stmt->fetchAll(PDO::FETCH_ASSOC); - - - } - /** - * Returns a specfic card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return array - */ - public function getCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ? LIMIT 1'); - $stmt->execute(array($addressBookId, $cardUri)); - - $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - - return (count($result)>0?$result[0]:false); - - } - - /** - * Creates a new card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function createCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('INSERT INTO `' . $this->cardsTableName . '` (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); - - $result = $stmt->execute(array($cardData, $cardUri, time(), $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $result; - - } - - /** - * Updates a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function updateCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('UPDATE `' . $this->cardsTableName . '` SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); - $result = $stmt->execute(array($cardData, time(), $cardUri, $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } - - /** - * Deletes a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return bool - */ - public function deleteCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ?'); - $stmt->execute(array($addressBookId, $cardUri)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } -} diff --git a/3rdparty/Sabre/CardDAV/Card.php b/3rdparty/Sabre/CardDAV/Card.php deleted file mode 100644 index 2844eaf7ed6..00000000000 --- a/3rdparty/Sabre/CardDAV/Card.php +++ /dev/null @@ -1,220 +0,0 @@ -carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - $this->cardData = $cardData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->cardData['uri']; - - } - - /** - * Returns the VCard-formatted object - * - * @return string - */ - public function get() { - - $cardData = $this->cardData['carddata']; - $s = fopen('php://temp','r+'); - fwrite($s, $cardData); - rewind($s); - return $s; - - } - - /** - * Updates the VCard-formatted object - * - * @param string $cardData - * @return void - */ - public function put($cardData) { - - if (is_resource($cardData)) - $cardData = stream_get_contents($cardData); - - // Converting to UTF-8, if needed - $cardData = Sabre_DAV_StringUtil::ensureUTF8($cardData); - - $this->carddavBackend->updateCard($this->addressBookInfo['id'],$this->cardData['uri'],$cardData); - $this->cardData['carddata'] = $cardData; - - } - - /** - * Deletes the card - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteCard($this->addressBookInfo['id'],$this->cardData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/x-vcard'; - - } - - /** - * Returns an ETag for this object - * - * @return string - */ - public function getETag() { - - return '"' . md5($this->cardData['carddata']) . '"'; - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return isset($this->cardData['lastmodified'])?$this->cardData['lastmodified']:null; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->cardData['carddata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - -} - diff --git a/3rdparty/Sabre/CardDAV/IAddressBook.php b/3rdparty/Sabre/CardDAV/IAddressBook.php deleted file mode 100644 index a0dffb30aea..00000000000 --- a/3rdparty/Sabre/CardDAV/IAddressBook.php +++ /dev/null @@ -1,18 +0,0 @@ -subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); - $server->subscribeEvent('report', array($this,'report')); - - /* Namespaces */ - $server->xmlNamespaces[self::NS_CARDDAV] = 'card'; - - /* Mapping Interfaces to {DAV:}resourcetype values */ - $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook'; - $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory'; - - /* Adding properties that may never be changed */ - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size'; - - - $this->server = $server; - - } - - /** - * Returns a list of supported features. - * - * This is used in the DAV: header in the OPTIONS and PROPFIND requests. - * - * @return array - */ - public function getFeatures() { - - return array('addressbook'); - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) { - return array( - '{' . self::NS_CARDDAV . '}addressbook-multiget', - '{' . self::NS_CARDDAV . '}addressbook-query', - ); - } - return array(); - - } - - - /** - * Adds all CardDAV-specific properties - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set'; - if (in_array($addHome,$requestedProperties)) { - $principalId = $node->getName(); - $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[array_search($addHome, $requestedProperties)]); - $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath); - } - - $directories = '{' . self::NS_CARDDAV . '}directory-gateway'; - if ($this->directories && in_array($directories, $requestedProperties)) { - unset($requestedProperties[array_search($directories, $requestedProperties)]); - $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories); - } - - } - - if ($node instanceof Sabre_CardDAV_ICard) { - - // The address-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $addressDataProp = '{' . self::NS_CARDDAV . '}address-data'; - if (in_array($addressDataProp, $requestedProperties)) { - unset($requestedProperties[$addressDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$addressDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This functions handles REPORT requests specific to CardDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CARDDAV.'}addressbook-multiget' : - $this->addressbookMultiGetReport($dom); - return false; - case '{'.self::NS_CARDDAV.'}addressbook-query' : - $this->addressBookQueryReport($dom); - return false; - default : - return; - - } - - - } - - /** - * This function handles the addressbook-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function addressbookMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - $propertyList = array(); - - foreach($hrefElems as $elem) { - - $uri = $this->server->calculateUri($elem->nodeValue); - list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the addressbook-query REPORT - * - * This report is used by the client to filter an addressbook based on a - * complex query. - * - * @param DOMNode $dom - * @return void - */ - protected function addressbookQueryReport($dom) { - - $query = new Sabre_CardDAV_AddressBookQueryParser($dom); - $query->parse(); - - $depth = $this->server->getHTTPDepth(0); - - if ($depth==0) { - $candidateNodes = array( - $this->server->tree->getNodeForPath($this->server->getRequestUri()) - ); - } else { - $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); - } - - $validNodes = array(); - foreach($candidateNodes as $node) { - - if (!$node instanceof Sabre_CardDAV_ICard) - continue; - - $blob = $node->get(); - if (is_resource($blob)) { - $blob = stream_get_contents($blob); - } - - if (!$this->validateFilters($blob, $query->filters, $query->test)) { - continue; - } - - $validNodes[] = $node; - - if ($query->limit && $query->limit <= count($validNodes)) { - // We hit the maximum number of items, we can stop now. - break; - } - - } - - $result = array(); - foreach($validNodes as $validNode) { - if ($depth==0) { - $href = $this->server->getRequestUri(); - } else { - $href = $this->server->getRequestUri() . '/' . $validNode->getName(); - } - - list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); - - } - - /** - * Validates if a vcard makes it throught a list of filters. - * - * @param string $vcardData - * @param array $filters - * @param string $test anyof or allof (which means OR or AND) - * @return bool - */ - public function validateFilters($vcardData, array $filters, $test) { - - $vcard = Sabre_VObject_Reader::read($vcardData); - - $success = true; - - foreach($filters as $filter) { - - $isDefined = isset($vcard->{$filter['name']}); - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { - - // We only need to check for existence - $success = $isDefined; - - } else { - - $vProperties = $vcard->select($filter['name']); - - $results = array(); - if ($filter['param-filters']) { - $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); - } - if ($filter['text-matches']) { - $texts = array(); - foreach($vProperties as $vProperty) - $texts[] = $vProperty->value; - - $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); - } - - if (count($results)===1) { - $success = $results[0]; - } else { - if ($filter['test'] === 'anyof') { - $success = $results[0] || $results[1]; - } else { - $success = $results[0] && $results[1]; - } - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } // foreach - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a param-filter can be applied to a specific property. - * - * @todo currently we're only validating the first parameter of the passed - * property. Any subsequence parameters with the same name are - * ignored. - * @param Sabre_VObject_Property $vProperty - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateParamFilters(array $vProperties, array $filters, $test) { - - $success = false; - foreach($filters as $filter) { - - $isDefined = false; - foreach($vProperties as $vProperty) { - $isDefined = isset($vProperty[$filter['name']]); - if ($isDefined) break; - } - - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - - // If there's no text-match, we can just check for existence - } elseif (!$filter['text-match'] || !$isDefined) { - - $success = $isDefined; - - } else { - - $texts = array(); - $success = false; - foreach($vProperties as $vProperty) { - // If we got all the way here, we'll need to validate the - // text-match filter. - $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); - if ($success) break; - } - if ($filter['text-match']['negate-condition']) { - $success = !$success; - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a text-filter can be applied to a specific property. - * - * @param array $texts - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateTextMatches(array $texts, array $filters, $test) { - - foreach($filters as $filter) { - - $success = false; - foreach($texts as $haystack) { - $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); - - // Breaking on the first match - if ($success) break; - } - if ($filter['negate-condition']) { - $success = !$success; - } - - if ($success && $test==='anyof') - return true; - - if (!$success && $test=='allof') - return false; - - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php b/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php deleted file mode 100644 index d57d3a6e7bd..00000000000 --- a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php +++ /dev/null @@ -1,69 +0,0 @@ - 'text/vcard', 'version' => '3.0'), - array('contentType' => 'text/vcard', 'version' => '4.0'), - ); - } - - $this->supportedData = $supportedData; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - - $prefix = - isset($server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV]) ? - $server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV] : - 'card'; - - foreach($this->supportedData as $supported) { - - $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix . ':address-data-type'); - $caldata->setAttribute('content-type',$supported['contentType']); - $caldata->setAttribute('version',$supported['version']); - $node->appendChild($caldata); - - } - - } - -} diff --git a/3rdparty/Sabre/CardDAV/UserAddressBooks.php b/3rdparty/Sabre/CardDAV/UserAddressBooks.php deleted file mode 100644 index e9f2de7f741..00000000000 --- a/3rdparty/Sabre/CardDAV/UserAddressBooks.php +++ /dev/null @@ -1,240 +0,0 @@ -carddavBackend = $carddavBackend; - $this->principalUri = $principalUri; - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CardDAV_AddressBook - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Addressbook with name \'' . $name . '\' could not be found'); - - } - - /** - * Returns a list of addressbooks - * - * @return array - */ - public function getChildren() { - - $addressbooks = $this->carddavBackend->getAddressbooksForUser($this->principalUri); - $objs = array(); - foreach($addressbooks as $addressbook) { - $objs[] = new Sabre_CardDAV_AddressBook($this->carddavBackend, $addressbook); - } - return $objs; - - } - - /** - * Creates a new addressbook - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->carddavBackend->createAddressBook($this->principalUri, $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalUri; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalUri, - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalUri, - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Version.php b/3rdparty/Sabre/CardDAV/Version.php deleted file mode 100644 index 900fbf5e75c..00000000000 --- a/3rdparty/Sabre/CardDAV/Version.php +++ /dev/null @@ -1,26 +0,0 @@ -currentUser; - } - - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function authenticate(Sabre_DAV_Server $server,$realm) { - - $auth = new Sabre_HTTP_BasicAuth(); - $auth->setHTTPRequest($server->httpRequest); - $auth->setHTTPResponse($server->httpResponse); - $auth->setRealm($realm); - $userpass = $auth->getUserPass(); - if (!$userpass) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No basic authentication headers were found'); - } - - // Authenticates the user - if (!$this->validateUserPass($userpass[0],$userpass[1])) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); - } - $this->currentUser = $userpass[0]; - return true; - } - - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php b/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php deleted file mode 100644 index 5bdc72753ec..00000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php +++ /dev/null @@ -1,96 +0,0 @@ -setHTTPRequest($server->httpRequest); - $digest->setHTTPResponse($server->httpResponse); - - $digest->setRealm($realm); - $digest->init(); - - $username = $digest->getUsername(); - - // No username was given - if (!$username) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No digest authentication headers were found'); - } - - $hash = $this->getDigestHash($realm, $username); - // If this was false, the user account didn't exist - if ($hash===false || is_null($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('The supplied username was not on file'); - } - if (!is_string($hash)) { - throw new Sabre_DAV_Exception('The returned value from getDigestHash must be a string or null'); - } - - // If this was false, the password or part of the hash was incorrect. - if (!$digest->validateA1($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Incorrect username'); - } - - $this->currentUser = $username; - return true; - - } - - /** - * Returns the currently logged in username. - * - * @return string|null - */ - public function getCurrentUser() { - - return $this->currentUser; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php b/3rdparty/Sabre/DAV/Auth/Backend/Apache.php deleted file mode 100644 index 6bcd76bdcb0..00000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php +++ /dev/null @@ -1,60 +0,0 @@ -httpRequest->getRawServerValue('REMOTE_USER'); - if (is_null($remoteUser)) { - throw new Sabre_DAV_Exception('We did not receive the $_SERVER[REMOTE_USER] property. This means that apache might have been misconfigured'); - } - - $this->remoteUser = $remoteUser; - return true; - - } - - /** - * Returns information about the currently logged in user. - * - * If nobody is currently logged in, this method should return null. - * - * @return array|null - */ - public function getCurrentUser() { - - return $this->remoteUser; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/File.php b/3rdparty/Sabre/DAV/Auth/Backend/File.php deleted file mode 100644 index db1f04c4772..00000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/File.php +++ /dev/null @@ -1,76 +0,0 @@ -loadFile($filename); - - } - - /** - * Loads an htdigest-formatted file. This method can be called multiple times if - * more than 1 file is used. - * - * @param string $filename - * @return void - */ - public function loadFile($filename) { - - foreach(file($filename,FILE_IGNORE_NEW_LINES) as $line) { - - if (substr_count($line, ":") !== 2) - throw new Sabre_DAV_Exception('Malformed htdigest file. Every line should contain 2 colons'); - - list($username,$realm,$A1) = explode(':',$line); - - if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) - throw new Sabre_DAV_Exception('Malformed htdigest file. Invalid md5 hash'); - - $this->users[$realm . ':' . $username] = $A1; - - } - - } - - /** - * Returns a users' information - * - * @param string $realm - * @param string $username - * @return string - */ - public function getDigestHash($realm, $username) { - - return isset($this->users[$realm . ':' . $username])?$this->users[$realm . ':' . $username]:false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php b/3rdparty/Sabre/DAV/Auth/Backend/PDO.php deleted file mode 100644 index 0301503601e..00000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php +++ /dev/null @@ -1,66 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns the digest hash for a user. - * - * @param string $realm - * @param string $username - * @return string|null - */ - public function getDigestHash($realm,$username) { - - $stmt = $this->pdo->prepare('SELECT username, digesta1 FROM `'.$this->tableName.'` WHERE username = ?'); - $stmt->execute(array($username)); - $result = $stmt->fetchAll(); - - if (!count($result)) return; - - return $result[0]['digesta1']; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/IBackend.php b/3rdparty/Sabre/DAV/Auth/IBackend.php deleted file mode 100644 index 1f67af4c2d9..00000000000 --- a/3rdparty/Sabre/DAV/Auth/IBackend.php +++ /dev/null @@ -1,34 +0,0 @@ -authBackend = $authBackend; - $this->realm = $realm; - - } - - /** - * Initializes the plugin. This function is automatically called by the server - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),10); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'auth'; - - } - - /** - * Returns the current users' principal uri. - * - * If nobody is logged in, this will return null. - * - * @return string|null - */ - public function getCurrentUser() { - - $userInfo = $this->authBackend->getCurrentUser(); - if (!$userInfo) return null; - - return $userInfo; - - } - - /** - * This method is called before any HTTP method and forces users to be authenticated - * - * @param string $method - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function beforeMethod($method, $uri) { - - $this->authBackend->authenticate($this->server,$this->realm); - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/GuessContentType.php b/3rdparty/Sabre/DAV/Browser/GuessContentType.php deleted file mode 100644 index ee8c698d782..00000000000 --- a/3rdparty/Sabre/DAV/Browser/GuessContentType.php +++ /dev/null @@ -1,97 +0,0 @@ - 'image/jpeg', - 'gif' => 'image/gif', - 'png' => 'image/png', - - // groupware - 'ics' => 'text/calendar', - 'vcf' => 'text/x-vcard', - - // text - 'txt' => 'text/plain', - - ); - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - // Using a relatively low priority (200) to allow other extensions - // to set the content-type first. - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties'),200); - - } - - /** - * Handler for teh afterGetProperties event - * - * @param string $path - * @param array $properties - * @return void - */ - public function afterGetProperties($path, &$properties) { - - if (array_key_exists('{DAV:}getcontenttype', $properties[404])) { - - list(, $fileName) = Sabre_DAV_URLUtil::splitPath($path); - $contentType = $this->getContentType($fileName); - - if ($contentType) { - $properties[200]['{DAV:}getcontenttype'] = $contentType; - unset($properties[404]['{DAV:}getcontenttype']); - } - - } - - } - - /** - * Simple method to return the contenttype - * - * @param string $fileName - * @return string - */ - protected function getContentType($fileName) { - - // Just grabbing the extension - $extension = strtolower(substr($fileName,strrpos($fileName,'.')+1)); - if (isset($this->extensionMap[$extension])) - return $this->extensionMap[$extension]; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php b/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php deleted file mode 100644 index a66b57a3a90..00000000000 --- a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php +++ /dev/null @@ -1,54 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - } - - /** - * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_IFile) return; - - $this->server->invokeMethod('PROPFIND',$uri); - return false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/Plugin.php b/3rdparty/Sabre/DAV/Browser/Plugin.php deleted file mode 100644 index cd5617babb1..00000000000 --- a/3rdparty/Sabre/DAV/Browser/Plugin.php +++ /dev/null @@ -1,285 +0,0 @@ -enablePost = $enablePost; - - } - - /** - * Initializes the plugin and subscribes to events - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler')); - } - - /** - * This method intercepts GET requests to collections and returns the html - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - try { - $node = $this->server->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // We're simply stopping when the file isn't found to not interfere - // with other plugins. - return; - } - if ($node instanceof Sabre_DAV_IFile) - return; - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8'); - - $this->server->httpResponse->sendBody( - $this->generateDirectoryIndex($uri) - ); - - return false; - - } - - /** - * Handles POST requests for tree operations - * - * This method is not yet used. - * - * @param string $method - * @return bool - */ - public function httpPOSTHandler($method, $uri) { - - if ($method!='POST') return true; - if (isset($_POST['sabreAction'])) switch($_POST['sabreAction']) { - - case 'mkcol' : - if (isset($_POST['name']) && trim($_POST['name'])) { - // Using basename() because we won't allow slashes - list(, $folderName) = Sabre_DAV_URLUtil::splitPath(trim($_POST['name'])); - $this->server->createDirectory($uri . '/' . $folderName); - } - break; - case 'put' : - if ($_FILES) $file = current($_FILES); - else break; - $newName = trim($file['name']); - list(, $newName) = Sabre_DAV_URLUtil::splitPath(trim($file['name'])); - if (isset($_POST['name']) && trim($_POST['name'])) - $newName = trim($_POST['name']); - - // Making sure we only have a 'basename' component - list(, $newName) = Sabre_DAV_URLUtil::splitPath($newName); - - - if (is_uploaded_file($file['tmp_name'])) { - $parent = $this->server->tree->getNodeForPath(trim($uri,'/')); - $parent->createFile($newName,fopen($file['tmp_name'],'r')); - } - - } - $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri()); - return false; - - } - - /** - * Escapes a string for html. - * - * @param string $value - * @return void - */ - public function escapeHTML($value) { - - return htmlspecialchars($value,ENT_QUOTES,'UTF-8'); - - } - - /** - * Generates the html directory index for a given url - * - * @param string $path - * @return string - */ - public function generateDirectoryIndex($path) { - - $html = " - - Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . Sabre_DAV_Version::VERSION . " - - - -

    Index for " . $this->escapeHTML($path) . "/

    - - - "; - - $files = $this->server->getPropertiesForPath($path,array( - '{DAV:}displayname', - '{DAV:}resourcetype', - '{DAV:}getcontenttype', - '{DAV:}getcontentlength', - '{DAV:}getlastmodified', - ),1); - - $parent = $this->server->tree->getNodeForPath($path); - - - if ($path) { - - list($parentUri) = Sabre_DAV_URLUtil::splitPath($path); - $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri() . $parentUri); - - $html.= " - - - - -"; - - } - - foreach($files as $k=>$file) { - - // This is the current directory, we can skip it - if (rtrim($file['href'],'/')==$path) continue; - - list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']); - - $type = null; - - - if (isset($file[200]['{DAV:}resourcetype'])) { - $type = $file[200]['{DAV:}resourcetype']->getValue(); - - // resourcetype can have multiple values - if (!is_array($type)) $type = array($type); - - foreach($type as $k=>$v) { - - // Some name mapping is preferred - switch($v) { - case '{DAV:}collection' : - $type[$k] = 'Collection'; - break; - case '{DAV:}principal' : - $type[$k] = 'Principal'; - break; - case '{urn:ietf:params:xml:ns:carddav}addressbook' : - $type[$k] = 'Addressbook'; - break; - case '{urn:ietf:params:xml:ns:caldav}calendar' : - $type[$k] = 'Calendar'; - break; - } - - } - $type = implode(', ', $type); - } - - // If no resourcetype was found, we attempt to use - // the contenttype property - if (!$type && isset($file[200]['{DAV:}getcontenttype'])) { - $type = $file[200]['{DAV:}getcontenttype']; - } - if (!$type) $type = 'Unknown'; - - $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:''; - $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):''; - - $fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/')); - - $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name; - - $name = $this->escapeHTML($name); - $displayName = $this->escapeHTML($displayName); - $type = $this->escapeHTML($type); - - $html.= " - - - - -"; - - } - - $html.= ""; - - if ($this->enablePost && $parent instanceof Sabre_DAV_ICollection) { - $html.= ''; - } - - $html.= "
    NameTypeSizeLast modified

    ..[parent]
    {$displayName}{$type}{$size}{$lastmodified}

    -

    Create new folder

    - - Name:
    - -
    -
    -

    Upload file

    - - Name (optional):
    - File:
    - -
    -
    -
    Generated by SabreDAV " . Sabre_DAV_Version::VERSION ."-". Sabre_DAV_Version::STABILITY . " (c)2007-2011 http://code.google.com/p/sabredav/
    - -"; - - return $html; - - } - -} diff --git a/3rdparty/Sabre/DAV/Client.php b/3rdparty/Sabre/DAV/Client.php deleted file mode 100644 index fc6a6fff083..00000000000 --- a/3rdparty/Sabre/DAV/Client.php +++ /dev/null @@ -1,431 +0,0 @@ -$validSetting = $settings[$validSetting]; - } - } - - $this->propertyMap['{DAV:}resourcetype'] = 'Sabre_DAV_Property_ResourceType'; - - } - - /** - * Does a PROPFIND request - * - * The list of requested properties must be specified as an array, in clark - * notation. - * - * The returned array will contain a list of filenames as keys, and - * properties as values. - * - * The properties array will contain the list of properties. Only properties - * that are actually returned from the server (without error) will be - * returned, anything else is discarded. - * - * 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. - * - * @param string $url - * @param array $properties - * @param int $depth - * @return array - */ - public function propFind($url, array $properties, $depth = 0) { - - $body = '' . "\n"; - $body.= '' . "\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"; - $body.= ''; - - $response = $this->request('PROPFIND', $url, $body, array( - 'Depth' => $depth, - 'Content-Type' => 'application/xml' - )); - - $result = $this->parseMultiStatus($response['body']); - - // If depth was 0, we only return the top item - if ($depth===0) { - reset($result); - $result = current($result); - return $result[200]; - } - - $newResult = array(); - foreach($result as $href => $statusList) { - - $newResult[$href] = $statusList[200]; - - } - - return $newResult; - - } - - /** - * Updates a list of properties on the server - * - * The list of properties must have clark-notation properties for the keys, - * and the actual (string) value for the value. If the value is null, an - * attempt is made to delete the property. - * - * @todo Must be building the request using the DOM, and does not yet - * support complex properties. - * @param string $url - * @param array $properties - * @return void - */ - public function propPatch($url, array $properties) { - - $body = '' . "\n"; - $body.= '' . "\n"; - - foreach($properties as $propName => $propValue) { - - list( - $namespace, - $elementName - ) = Sabre_DAV_XMLUtil::parseClarkNotation($propName); - - if ($propValue === null) { - - $body.="\n"; - - if ($namespace === 'DAV:') { - $body.=' ' . "\n"; - } else { - $body.=" \n"; - } - - $body.="\n"; - - } else { - - $body.="\n"; - if ($namespace === 'DAV:') { - $body.=' '; - } else { - $body.=" "; - } - // Shitty.. i know - $body.=htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); - if ($namespace === 'DAV:') { - $body.='' . "\n"; - } else { - $body.="\n"; - } - $body.="\n"; - - } - - } - - $body.= ''; - - $response = $this->request('PROPPATCH', $url, $body, array( - 'Content-Type' => 'application/xml' - )); - - } - - /** - * Performs an HTTP options request - * - * This method returns all the features from the 'DAV:' header as an array. - * If there was no DAV header, or no contents this method will return an - * empty array. - * - * @return array - */ - public function options() { - - $result = $this->request('OPTIONS'); - if (!isset($result['headers']['dav'])) { - return array(); - } - - $features = explode(',', $result['headers']['dav']); - foreach($features as &$v) { - $v = trim($v); - } - return $features; - - } - - /** - * Performs an actual HTTP request, and returns the result. - * - * If the specified url is relative, it will be expanded based on the base - * url. - * - * The returned array contains 3 keys: - * * body - the response body - * * httpCode - a HTTP code (200, 404, etc) - * * headers - a list of response http headers. The header names have - * been lowercased. - * - * @param string $method - * @param string $url - * @param string $body - * @param array $headers - * @return array - */ - public function request($method, $url = '', $body = null, $headers = array()) { - - $url = $this->getAbsoluteUrl($url); - - $curlSettings = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_CUSTOMREQUEST => $method, - CURLOPT_POSTFIELDS => $body, - // Return headers as part of the response - CURLOPT_HEADER => true - ); - - // Adding HTTP headers - $nHeaders = array(); - foreach($headers as $key=>$value) { - - $nHeaders[] = $key . ': ' . $value; - - } - $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; - - if ($this->proxy) { - $curlSettings[CURLOPT_PROXY] = $this->proxy; - } - - if ($this->userName) { - $curlSettings[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC | CURLAUTH_DIGEST; - $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; - } - - list( - $response, - $curlInfo, - $curlErrNo, - $curlError - ) = $this->curlRequest($url, $curlSettings); - - $headerBlob = substr($response, 0, $curlInfo['header_size']); - $response = substr($response, $curlInfo['header_size']); - - // In the case of 100 Continue, or redirects we'll have multiple lists - // of headers for each separate HTTP response. We can easily split this - // because they are separated by \r\n\r\n - $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); - - // We only care about the last set of headers - $headerBlob = $headerBlob[count($headerBlob)-1]; - - // Splitting headers - $headerBlob = explode("\r\n", $headerBlob); - - $headers = array(); - foreach($headerBlob as $header) { - $parts = explode(':', $header, 2); - if (count($parts)==2) { - $headers[strtolower(trim($parts[0]))] = trim($parts[1]); - } - } - - $response = array( - 'body' => $response, - 'statusCode' => $curlInfo['http_code'], - 'headers' => $headers - ); - - if ($curlErrNo) { - throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); - } - - if ($response['statusCode']>=400) { - throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); - } - - return $response; - - } - - /** - * Wrapper for all curl functions. - * - * The only reason this was split out in a separate method, is so it - * becomes easier to unittest. - * - * @param string $url - * @param array $settings - * @return - */ - protected function curlRequest($url, $settings) { - - $curl = curl_init($url); - curl_setopt_array($curl, $settings); - - return array( - curl_exec($curl), - curl_getinfo($curl), - curl_errno($curl), - curl_error($curl) - ); - - } - - /** - * Returns the full url based on the given url (which may be relative). All - * urls are expanded based on the base url as given by the server. - * - * @param string $url - * @return string - */ - protected function getAbsoluteUrl($url) { - - // If the url starts with http:// or https://, the url is already absolute. - if (preg_match('/^http(s?):\/\//', $url)) { - return $url; - } - - // If the url starts with a slash, we must calculate the url based off - // the root of the base url. - if (strpos($url,'/') === 0) { - $parts = parse_url($this->baseUri); - return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port'])?':' . $parts['port']:'') . $url; - } - - // Otherwise... - return $this->baseUri . $url; - - } - - /** - * Parses a WebDAV multistatus response body - * - * This method returns an array with the following structure - * - * array( - * 'url/to/resource' => array( - * '200' => array( - * '{DAV:}property1' => 'value1', - * '{DAV:}property2' => 'value2', - * ), - * '404' => array( - * '{DAV:}property1' => null, - * '{DAV:}property2' => null, - * ), - * ) - * 'url/to/resource2' => array( - * .. etc .. - * ) - * ) - * - * - * @param string $body xml body - * @return array - */ - public function parseMultiStatus($body) { - - $body = Sabre_DAV_XMLUtil::convertDAVNamespace($body); - - $responseXML = simplexml_load_string($body, null, LIBXML_NOBLANKS | LIBXML_NOCDATA); - if ($responseXML===false) { - throw new InvalidArgumentException('The passed data is not valid XML'); - } - - $responseXML->registerXPathNamespace('d','DAV:'); - - $propResult = array(); - - foreach($responseXML->xpath('d:response') as $response) { - - $response->registerXPathNamespace('d','DAV:'); - $href = $response->xpath('d:href'); - $href = (string)$href[0]; - - $properties = array(); - - foreach($response->xpath('d:propstat') as $propStat) { - - $propStat->registerXPathNamespace('d','DAV:'); - $status = $propStat->xpath('d:status'); - list($httpVersion, $statusCode, $message) = explode(' ', (string)$status[0],3); - - $properties[$statusCode] = Sabre_DAV_XMLUtil::parseProperties(dom_import_simplexml($propStat), $this->propertyMap); - - } - - $propResult[$href] = $properties; - - } - - return $propResult; - - } - -} diff --git a/3rdparty/Sabre/DAV/Collection.php b/3rdparty/Sabre/DAV/Collection.php deleted file mode 100644 index 9da04c12792..00000000000 --- a/3rdparty/Sabre/DAV/Collection.php +++ /dev/null @@ -1,90 +0,0 @@ -getChildren() as $child) { - - if ($child->getName()==$name) return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name); - - } - - /** - * Checks is a child-node exists. - * - * It is generally a good idea to try and override this. Usually it can be optimized. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - try { - - $this->getChild($name); - return true; - - } catch(Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Creates a new file in the directory - * - * @param string $name Name of the file - * @param resource $data Initial payload, passed as a readable stream resource. - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createFile($name, $data = null) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/Directory.php b/3rdparty/Sabre/DAV/Directory.php deleted file mode 100644 index 86af4827b3e..00000000000 --- a/3rdparty/Sabre/DAV/Directory.php +++ /dev/null @@ -1,17 +0,0 @@ -lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/FileNotFound.php b/3rdparty/Sabre/DAV/Exception/FileNotFound.php deleted file mode 100644 index b20e4a2fb3f..00000000000 --- a/3rdparty/Sabre/DAV/Exception/FileNotFound.php +++ /dev/null @@ -1,28 +0,0 @@ -ownerDocument->createElementNS('DAV:','d:valid-resourcetype'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php b/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php deleted file mode 100644 index 47032cffc75..00000000000 --- a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php +++ /dev/null @@ -1,39 +0,0 @@ -message = 'The locktoken supplied does not match any locks on this entity'; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-matches-request-uri'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/Locked.php b/3rdparty/Sabre/DAV/Exception/Locked.php deleted file mode 100644 index b4bb2e0378c..00000000000 --- a/3rdparty/Sabre/DAV/Exception/Locked.php +++ /dev/null @@ -1,67 +0,0 @@ -lock = $lock; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 423; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-submitted'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php b/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php deleted file mode 100644 index 02c145ffeb6..00000000000 --- a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php +++ /dev/null @@ -1,44 +0,0 @@ -getAllowedMethods($server->getRequestUri()); - - return array( - 'Allow' => strtoupper(implode(', ',$methods)), - ); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php b/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php deleted file mode 100644 index 1faffddfa00..00000000000 --- a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php +++ /dev/null @@ -1,28 +0,0 @@ -header = $header; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 412; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->header) { - $prop = $errorNode->ownerDocument->createElement('s:header'); - $prop->nodeValue = $this->header; - $errorNode->appendChild($prop); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php b/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php deleted file mode 100644 index e4ed601b16c..00000000000 --- a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php +++ /dev/null @@ -1,30 +0,0 @@ -ownerDocument->createElementNS('DAV:','d:supported-report'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php b/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php deleted file mode 100644 index 37abbd729d1..00000000000 --- a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php +++ /dev/null @@ -1,29 +0,0 @@ -path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); - - if (is_dir($path)) { - - return new Sabre_DAV_FS_Directory($path); - - } else { - - return new Sabre_DAV_FS_File($path); - - } - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - foreach($this->getChildren() as $child) $child->delete(); - rmdir($this->path); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/File.php b/3rdparty/Sabre/DAV/FS/File.php deleted file mode 100644 index 262187d7e8a..00000000000 --- a/3rdparty/Sabre/DAV/FS/File.php +++ /dev/null @@ -1,89 +0,0 @@ -path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - - } - - /** - * Returns the size of the node, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - * - * @return mixed - */ - public function getETag() { - - return null; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - * - * @return mixed - */ - public function getContentType() { - - return null; - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/Node.php b/3rdparty/Sabre/DAV/FS/Node.php deleted file mode 100644 index b8d7bcfe846..00000000000 --- a/3rdparty/Sabre/DAV/FS/Node.php +++ /dev/null @@ -1,81 +0,0 @@ -path = $path; - - } - - - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); - return $name; - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - - $newPath = $parentPath . '/' . $newName; - rename($this->path,$newPath); - - $this->path = $newPath; - - } - - - - /** - * Returns the last modification time, as a unix timestamp - * - * @return int - */ - public function getLastModified() { - - return filemtime($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Directory.php b/3rdparty/Sabre/DAV/FSExt/Directory.php deleted file mode 100644 index c43d4385ac7..00000000000 --- a/3rdparty/Sabre/DAV/FSExt/Directory.php +++ /dev/null @@ -1,135 +0,0 @@ -path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - // We're not allowing dots - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File could not be located'); - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - if (is_dir($path)) { - - return new Sabre_DAV_FSExt_Directory($path); - - } else { - - return new Sabre_DAV_FSExt_File($path); - - } - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - if ($name=='.' || $name=='..') - throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..' && $node!='.sabredav') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - // Deleting all children - foreach($this->getChildren() as $child) $child->delete(); - - // Removing resource info, if its still around - if (file_exists($this->path . '/.sabredav')) unlink($this->path . '/.sabredav'); - - // Removing the directory itself - rmdir($this->path); - - return parent::delete(); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/File.php b/3rdparty/Sabre/DAV/FSExt/File.php deleted file mode 100644 index 7a8e7a11f21..00000000000 --- a/3rdparty/Sabre/DAV/FSExt/File.php +++ /dev/null @@ -1,88 +0,0 @@ -path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - return parent::delete(); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5_file($this->path). '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return null; - - } - - /** - * Returns the size of the file, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Node.php b/3rdparty/Sabre/DAV/FSExt/Node.php deleted file mode 100644 index 9e36222bfd3..00000000000 --- a/3rdparty/Sabre/DAV/FSExt/Node.php +++ /dev/null @@ -1,276 +0,0 @@ -getResourceData(); - $locks = $resourceData['locks']; - foreach($locks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($locks[$k]); - } - return $locks; - - } - - /** - * Locks this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - function lock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $resourceData = $this->getResourceData(); - if (!isset($resourceData['locks'])) $resourceData['locks'] = array(); - $current = null; - foreach($resourceData['locks'] as $k=>$lock) { - if ($lock->token === $lockInfo->token) $current = $k; - } - if (!is_null($current)) $resourceData['locks'][$current] = $lockInfo; - else $resourceData['locks'][] = $lockInfo; - - $this->putResourceData($resourceData); - - } - - /** - * Removes a lock from this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - function unlock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - //throw new Sabre_DAV_Exception('bla'); - $resourceData = $this->getResourceData(); - foreach($resourceData['locks'] as $k=>$lock) { - - if ($lock->token === $lockInfo->token) { - - unset($resourceData['locks'][$k]); - $this->putResourceData($resourceData); - return true; - - } - } - return false; - - } - - /** - * Updates properties on this node, - * - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - $resourceData = $this->getResourceData(); - - $result = array(); - - foreach($properties as $propertyName=>$propertyValue) { - - // If it was null, we need to delete the property - if (is_null($propertyValue)) { - if (isset($resourceData['properties'][$propertyName])) { - unset($resourceData['properties'][$propertyName]); - } - } else { - $resourceData['properties'][$propertyName] = $propertyValue; - } - - } - - $this->putResourceData($resourceData); - return true; - } - - /** - * Returns a list of properties for this nodes.; - * - * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author - * If the array is empty, all properties should be returned - * - * @param array $properties - * @return void - */ - function getProperties($properties) { - - $resourceData = $this->getResourceData(); - - // if the array was empty, we need to return everything - if (!$properties) return $resourceData['properties']; - - $props = array(); - foreach($properties as $property) { - if (isset($resourceData['properties'][$property])) $props[$property] = $resourceData['properties'][$property]; - } - - return $props; - - } - - /** - * Returns the path to the resource file - * - * @return string - */ - protected function getResourceInfoPath() { - - list($parentDir) = Sabre_DAV_URLUtil::splitPath($this->path); - return $parentDir . '/.sabredav'; - - } - - /** - * Returns all the stored resource information - * - * @return array - */ - protected function getResourceData() { - - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return array('locks'=>array(), 'properties' => array()); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!isset($data[$this->getName()])) { - return array('locks'=>array(), 'properties' => array()); - } - - $data = $data[$this->getName()]; - if (!isset($data['locks'])) $data['locks'] = array(); - if (!isset($data['properties'])) $data['properties'] = array(); - return $data; - - } - - /** - * Updates the resource information - * - * @param array $newData - * @return void - */ - protected function putResourceData(array $newData) { - - $path = $this->getResourceInfoPath(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - $data[$this->getName()] = $newData; - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($data)); - fclose($handle); - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - $newPath = $parentPath . '/' . $newName; - - // We're deleting the existing resourcedata, and recreating it - // for the new path. - $resourceData = $this->getResourceData(); - $this->deleteResourceData(); - - rename($this->path,$newPath); - $this->path = $newPath; - $this->putResourceData($resourceData); - - - } - - public function deleteResourceData() { - - // When we're deleting this node, we also need to delete any resource information - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return true; - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (isset($data[$this->getName()])) unset($data[$this->getName()]); - ftruncate($handle,0); - rewind($handle); - fwrite($handle,serialize($data)); - fclose($handle); - - } - - public function delete() { - - return $this->deleteResourceData(); - - } - -} - diff --git a/3rdparty/Sabre/DAV/File.php b/3rdparty/Sabre/DAV/File.php deleted file mode 100644 index b74bd9525b3..00000000000 --- a/3rdparty/Sabre/DAV/File.php +++ /dev/null @@ -1,81 +0,0 @@ - array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - function updateProperties($mutations); - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - function getProperties($properties); - -} - diff --git a/3rdparty/Sabre/DAV/IQuota.php b/3rdparty/Sabre/DAV/IQuota.php deleted file mode 100644 index 8ff1a4597f8..00000000000 --- a/3rdparty/Sabre/DAV/IQuota.php +++ /dev/null @@ -1,27 +0,0 @@ -dataDir = $dataDir; - - } - - protected function getFileNameForUri($uri) { - - return $this->dataDir . '/sabredav_' . md5($uri) . '.locks'; - - } - - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $lockList = array(); - $currentPath = ''; - - foreach(explode('/',$uri) as $uriPart) { - - // weird algorithm that can probably be improved, but we're traversing the path top down - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - $uriLocks = $this->getData($currentPath); - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ingore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - - // Checking if we can remove any of these locks - foreach($lockList as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($lockList[$k]); - } - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($uri,$locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($uri,$locks); - return true; - - } - } - return false; - - } - - /** - * Returns the stored data for a uri - * - * @param string $uri - * @return array - */ - protected function getData($uri) { - - $path = $this->getFilenameForUri($uri); - if (!file_exists($path)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Updates the lock information - * - * @param string $uri - * @param array $newData - * @return void - */ - protected function putData($uri,array $newData) { - - $path = $this->getFileNameForUri($uri); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/File.php b/3rdparty/Sabre/DAV/Locks/Backend/File.php deleted file mode 100644 index f65b20c4306..00000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/File.php +++ /dev/null @@ -1,175 +0,0 @@ -locksFile = $locksFile; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $newLocks = array(); - $currentPath = ''; - - $locks = $this->getData(); - foreach($locks as $lock) { - - if ($lock->uri === $uri || - //deep locks on parents - ($lock->depth!=0 && strpos($uri, $lock->uri . '/')===0) || - - // locks on children - ($returnChildLocks && (strpos($lock->uri, $uri . '/')===0)) ) { - - $newLocks[] = $lock; - - } - - } - - // Checking if we can remove any of these locks - foreach($newLocks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($newLocks[$k]); - } - return $newLocks; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($locks); - return true; - - } - } - return false; - - } - - /** - * Loads the lockdata from the filesystem. - * - * @return array - */ - protected function getData() { - - if (!file_exists($this->locksFile)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($this->locksFile,'r'); - flock($handle,LOCK_SH); - - // Reading data until the eof - $data = stream_get_contents($handle); - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Saves the lockdata - * - * @param array $newData - * @return void - */ - protected function putData(array $newData) { - - // opening up the file, and creating an exclusive lock - $handle = fopen($this->locksFile,'a+'); - flock($handle,LOCK_EX); - - // We can only truncate and rewind once the lock is acquired. - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php b/3rdparty/Sabre/DAV/Locks/Backend/PDO.php deleted file mode 100644 index c3923af19d3..00000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php +++ /dev/null @@ -1,165 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - // NOTE: the following 10 lines or so could be easily replaced by - // pure sql. MySQL's non-standard string concatination prevents us - // from doing this though. - $query = 'SELECT owner, token, timeout, created, scope, depth, uri FROM `'.$this->tableName.'` WHERE ((created + timeout) > CAST(? AS UNSIGNED INTEGER)) AND ((uri = ?)'; - $params = array(time(),$uri); - - // We need to check locks for every part in the uri. - $uriParts = explode('/',$uri); - - // We already covered the last part of the uri - array_pop($uriParts); - - $currentPath=''; - - foreach($uriParts as $part) { - - if ($currentPath) $currentPath.='/'; - $currentPath.=$part; - - $query.=' OR (depth!=0 AND uri = ?)'; - $params[] = $currentPath; - - } - - if ($returnChildLocks) { - - $query.=' OR (uri LIKE ?)'; - $params[] = $uri . '/%'; - - } - $query.=')'; - - $stmt = $this->pdo->prepare($query); - $stmt->execute($params); - $result = $stmt->fetchAll(); - - $lockList = array(); - foreach($result as $row) { - - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - $lockInfo->owner = $row['owner']; - $lockInfo->token = $row['token']; - $lockInfo->timeout = $row['timeout']; - $lockInfo->created = $row['created']; - $lockInfo->scope = $row['scope']; - $lockInfo->depth = $row['depth']; - $lockInfo->uri = $row['uri']; - $lockList[] = $lockInfo; - - } - - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 30*60; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - $exists = false; - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) $exists = true; - } - - if ($exists) { - $stmt = $this->pdo->prepare('UPDATE `'.$this->tableName.'` SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE token = ?'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } else { - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->tableName.'` (owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?)'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } - - return true; - - } - - - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->tableName.'` WHERE uri = ? AND token = ?'); - $stmt->execute(array($uri,$lockInfo->token)); - - return $stmt->rowCount()===1; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/LockInfo.php b/3rdparty/Sabre/DAV/Locks/LockInfo.php deleted file mode 100644 index 6a064466f40..00000000000 --- a/3rdparty/Sabre/DAV/Locks/LockInfo.php +++ /dev/null @@ -1,81 +0,0 @@ -addPlugin($lockPlugin); - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * locksBackend - * - * @var Sabre_DAV_Locks_Backend_Abstract - */ - private $locksBackend; - - /** - * server - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * __construct - * - * @param Sabre_DAV_Locks_Backend_Abstract $locksBackend - * @return void - */ - public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) { - - $this->locksBackend = $locksBackend; - - } - - /** - * Initializes the plugin - * - * This method is automatically called by the Server class after addPlugin. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),50); - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties')); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'locks'; - - } - - /** - * This method is called by the Server if the user used an HTTP method - * the server didn't recognize. - * - * This plugin intercepts the LOCK and UNLOCK methods. - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - switch($method) { - - case 'LOCK' : $this->httpLock($uri); return false; - case 'UNLOCK' : $this->httpUnlock($uri); return false; - - } - - } - - /** - * This method is called after most properties have been found - * it allows us to add in any Lock-related properties - * - * @param string $path - * @param array $properties - * @return bool - */ - public function afterGetProperties($path,&$newProperties) { - - foreach($newProperties[404] as $propName=>$discard) { - - $node = null; - - switch($propName) { - - case '{DAV:}supportedlock' : - $val = false; - if ($this->locksBackend) $val = true; - else { - if (!$node) $node = $this->server->tree->getNodeForPath($path); - if ($node instanceof Sabre_DAV_ILockable) $val = true; - } - $newProperties[200][$propName] = new Sabre_DAV_Property_SupportedLock($val); - unset($newProperties[404][$propName]); - break; - - case '{DAV:}lockdiscovery' : - $newProperties[200][$propName] = new Sabre_DAV_Property_LockDiscovery($this->getLocks($path)); - unset($newProperties[404][$propName]); - break; - - } - - - } - return true; - - } - - - /** - * This method is called before the logic for any HTTP method is - * handled. - * - * This plugin uses that feature to intercept access to locked resources. - * - * @param string $method - * @param string $uri - * @return bool - */ - public function beforeMethod($method, $uri) { - - switch($method) { - - case 'DELETE' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MKCOL' : - case 'PROPPATCH' : - case 'PUT' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MOVE' : - $lastLock = null; - if (!$this->validateLock(array( - $uri, - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - ),$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'COPY' : - $lastLock = null; - if (!$this->validateLock( - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - $lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - } - - return true; - - } - - /** - * Use this method to tell the server this plugin defines additional - * HTTP methods. - * - * This method is passed a uri. It should only return HTTP methods that are - * available for the specified uri. - * - * @param string $uri - * @return array - */ - public function getHTTPMethods($uri) { - - if ($this->locksBackend || - $this->server->tree->getNodeForPath($uri) instanceof Sabre_DAV_ILocks) { - return array('LOCK','UNLOCK'); - } - return array(); - - } - - /** - * Returns a list of features for the HTTP OPTIONS Dav: header. - * - * In this case this is only the number 2. The 2 in the Dav: header - * indicates the server supports locks. - * - * @return array - */ - public function getFeatures() { - - return array(2); - - } - - /** - * Returns all lock information on a particular uri - * - * This function should return an array with Sabre_DAV_Locks_LockInfo objects. If there are no locks on a file, return an empty array. - * - * Additionally there is also the possibility of locks on parent nodes, so we'll need to traverse every part of the tree - * If the $returnChildLocks argument is set to true, we'll also traverse all the children of the object - * for any possible locks and return those as well. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks = false) { - - $lockList = array(); - $currentPath = ''; - foreach(explode('/',$uri) as $uriPart) { - - $uriLocks = array(); - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - try { - - $node = $this->server->tree->getNodeForPath($currentPath); - if ($node instanceof Sabre_DAV_ILockable) $uriLocks = $node->getLocks(); - - } catch (Sabre_DAV_Exception_FileNotFound $e){ - // In case the node didn't exist, this could be a lock-null request - } - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ignore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - if ($this->locksBackend) - $lockList = array_merge($lockList,$this->locksBackend->getLocks($uri, $returnChildLocks)); - - return $lockList; - - } - - /** - * Locks an uri - * - * The WebDAV lock request can be operated to either create a new lock on a file, or to refresh an existing lock - * If a new lock is created, a full XML body should be supplied, containing information about the lock such as the type - * of lock (shared or exclusive) and the owner of the lock - * - * If a lock is to be refreshed, no body should be supplied and there should be a valid If header containing the lock - * - * Additionally, a lock can be requested for a non-existant file. In these case we're obligated to create an empty file as per RFC4918:S7.3 - * - * @param string $uri - * @return void - */ - protected function httpLock($uri) { - - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) { - - // If the existing lock was an exclusive lock, we need to fail - if (!$lastLock || $lastLock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE) { - //var_dump($lastLock); - throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - } - - } - - if ($body = $this->server->httpRequest->getBody(true)) { - // This is a new lock request - $lockInfo = $this->parseLockRequest($body); - $lockInfo->depth = $this->server->getHTTPDepth(); - $lockInfo->uri = $uri; - if($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - - } elseif ($lastLock) { - - // This must have been a lock refresh - $lockInfo = $lastLock; - - // The resource could have been locked through another uri. - if ($uri!=$lockInfo->uri) $uri = $lockInfo->uri; - - } else { - - // There was neither a lock refresh nor a new lock request - throw new Sabre_DAV_Exception_BadRequest('An xml body is required for lock requests'); - - } - - if ($timeout = $this->getTimeoutHeader()) $lockInfo->timeout = $timeout; - - $newFile = false; - - // If we got this far.. we should go check if this node actually exists. If this is not the case, we need to create it first - try { - $node = $this->server->tree->getNodeForPath($uri); - - // We need to call the beforeWriteContent event for RFC3744 - $this->server->broadcastEvent('beforeWriteContent',array($uri)); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // It didn't, lets create it - $this->server->createFile($uri,fopen('php://memory','r')); - $newFile = true; - - } - - $this->lockNode($uri,$lockInfo); - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->setHeader('Lock-Token','token . '>'); - $this->server->httpResponse->sendStatus($newFile?201:200); - $this->server->httpResponse->sendBody($this->generateLockResponse($lockInfo)); - - } - - /** - * Unlocks a uri - * - * This WebDAV method allows you to remove a lock from a node. The client should provide a valid locktoken through the Lock-token http header - * The server should return 204 (No content) on success - * - * @param string $uri - * @return void - */ - protected function httpUnlock($uri) { - - $lockToken = $this->server->httpRequest->getHeader('Lock-Token'); - - // If the locktoken header is not supplied, we need to throw a bad request exception - if (!$lockToken) throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); - - $locks = $this->getLocks($uri); - - // Windows sometimes forgets to include < and > in the Lock-Token - // header - if ($lockToken[0]!=='<') $lockToken = '<' . $lockToken . '>'; - - foreach($locks as $lock) { - - if ('token . '>' == $lockToken) { - - $this->server->broadcastEvent('beforeUnlock',array($uri, $lock)); - $this->unlockNode($uri,$lock); - $this->server->httpResponse->setHeader('Content-Length','0'); - $this->server->httpResponse->sendStatus(204); - return; - - } - - } - - // If we got here, it means the locktoken was invalid - throw new Sabre_DAV_Exception_LockTokenMatchesRequestUri(); - - } - - /** - * Locks a uri - * - * All the locking information is supplied in the lockInfo object. The object has a suggested timeout, but this can be safely ignored - * It is important that if the existing timeout is ignored, the property is overwritten, as this needs to be sent back to the client - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function lockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeLock',array($uri,$lockInfo))) return; - - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->lock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - if ($this->locksBackend) return $this->locksBackend->lock($uri,$lockInfo); - throw new Sabre_DAV_Exception_MethodNotAllowed('Locking support is not enabled for this resource. No Locking backend was found so if you didn\'t expect this error, please check your configuration.'); - - } - - /** - * Unlocks a uri - * - * This method removes a lock from a uri. It is assumed all the supplied information is correct and verified - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function unlockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeUnlock',array($uri,$lockInfo))) return; - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->unlock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - - if ($this->locksBackend) return $this->locksBackend->unlock($uri,$lockInfo); - - } - - - /** - * Returns the contents of the HTTP Timeout header. - * - * The method formats the header into an integer. - * - * @return int - */ - public function getTimeoutHeader() { - - $header = $this->server->httpRequest->getHeader('Timeout'); - - if ($header) { - - if (stripos($header,'second-')===0) $header = (int)(substr($header,7)); - else if (strtolower($header)=='infinite') $header=Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; - else throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); - - } else { - - $header = 0; - - } - - return $header; - - } - - /** - * Generates the response for successfull LOCK requests - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return string - */ - protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) { - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - - $prop = $dom->createElementNS('DAV:','d:prop'); - $dom->appendChild($prop); - - $lockDiscovery = $dom->createElementNS('DAV:','d:lockdiscovery'); - $prop->appendChild($lockDiscovery); - - $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo),true); - $lockObj->serialize($this->server,$lockDiscovery); - - return $dom->saveXML(); - - } - - /** - * validateLock should be called when a write operation is about to happen - * It will check if the requested url is locked, and see if the correct lock tokens are passed - * - * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri - * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) - * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees. - * @return bool - */ - protected function validateLock($urls = null,&$lastLock = null, $checkChildLocks = false) { - - if (is_null($urls)) { - $urls = array($this->server->getRequestUri()); - } elseif (is_string($urls)) { - $urls = array($urls); - } elseif (!is_array($urls)) { - throw new Sabre_DAV_Exception('The urls parameter should either be null, a string or an array'); - } - - $conditions = $this->getIfConditions(); - - // We're going to loop through the urls and make sure all lock conditions are satisfied - foreach($urls as $url) { - - $locks = $this->getLocks($url, $checkChildLocks); - - // If there were no conditions, but there were locks, we fail - if (!$conditions && $locks) { - reset($locks); - $lastLock = current($locks); - return false; - } - - // If there were no locks or conditions, we go to the next url - if (!$locks && !$conditions) continue; - - foreach($conditions as $condition) { - - if (!$condition['uri']) { - $conditionUri = $this->server->getRequestUri(); - } else { - $conditionUri = $this->server->calculateUri($condition['uri']); - } - - // If the condition has a url, and it isn't part of the affected url at all, check the next condition - if ($conditionUri && strpos($url,$conditionUri)!==0) continue; - - // The tokens array contians arrays with 2 elements. 0=true/false for normal/not condition, 1=locktoken - // At least 1 condition has to be satisfied - foreach($condition['tokens'] as $conditionToken) { - - $etagValid = true; - $lockValid = true; - - // key 2 can contain an etag - if ($conditionToken[2]) { - - $uri = $conditionUri?$conditionUri:$this->server->getRequestUri(); - $node = $this->server->tree->getNodeForPath($uri); - $etagValid = $node->getETag()==$conditionToken[2]; - - } - - // key 1 can contain a lock token - if ($conditionToken[1]) { - - $lockValid = false; - // Match all the locks - foreach($locks as $lockIndex=>$lock) { - - $lockToken = 'opaquelocktoken:' . $lock->token; - - // Checking NOT - if (!$conditionToken[0] && $lockToken != $conditionToken[1]) { - - // Condition valid, onto the next - $lockValid = true; - break; - } - if ($conditionToken[0] && $lockToken == $conditionToken[1]) { - - $lastLock = $lock; - // Condition valid and lock matched - unset($locks[$lockIndex]); - $lockValid = true; - break; - - } - - } - - } - - // If, after checking both etags and locks they are stil valid, - // we can continue with the next condition. - if ($etagValid && $lockValid) continue 2; - } - // No conditions matched, so we fail - throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match','If'); - } - - // Conditions were met, we'll also need to check if all the locks are gone - if (count($locks)) { - - reset($locks); - - // There's still locks, we fail - $lastLock = current($locks); - return false; - - } - - - } - - // We got here, this means every condition was satisfied - return true; - - } - - /** - * This method is created to extract information from the WebDAV HTTP 'If:' header - * - * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information - * The function will return an array, containg structs with the following keys - * - * * uri - the uri the condition applies to. If this is returned as an - * empty string, this implies it's referring to the request url. - * * tokens - The lock token. another 2 dimensional array containg 2 elements (0 = true/false.. If this is a negative condition its set to false, 1 = the actual token) - * * etag - an etag, if supplied - * - * @return void - */ - public function getIfConditions() { - - $header = $this->server->httpRequest->getHeader('If'); - if (!$header) return array(); - - $matches = array(); - - $regex = '/(?:\<(?P.*?)\>\s)?\((?PNot\s)?(?:\<(?P[^\>]*)\>)?(?:\s?)(?:\[(?P[^\]]*)\])?\)/im'; - preg_match_all($regex,$header,$matches,PREG_SET_ORDER); - - $conditions = array(); - - foreach($matches as $match) { - - $condition = array( - 'uri' => $match['uri'], - 'tokens' => array( - array($match['not']?0:1,$match['token'],isset($match['etag'])?$match['etag']:'') - ), - ); - - if (!$condition['uri'] && count($conditions)) $conditions[count($conditions)-1]['tokens'][] = array( - $match['not']?0:1, - $match['token'], - isset($match['etag'])?$match['etag']:'' - ); - else { - $conditions[] = $condition; - } - - } - - return $conditions; - - } - - /** - * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object - * - * @param string $body - * @return Sabre_DAV_Locks_LockInfo - */ - protected function parseLockRequest($body) { - - $xml = simplexml_load_string($body,null,LIBXML_NOWARNING); - $xml->registerXPathNamespace('d','DAV:'); - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - - $children = $xml->children("DAV:"); - $lockInfo->owner = (string)$children->owner; - - $lockInfo->token = Sabre_DAV_UUIDUtil::getUUID(); - $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive'))>0?Sabre_DAV_Locks_LockInfo::EXCLUSIVE:Sabre_DAV_Locks_LockInfo::SHARED; - - return $lockInfo; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Mount/Plugin.php b/3rdparty/Sabre/DAV/Mount/Plugin.php deleted file mode 100644 index f93a1aa25a1..00000000000 --- a/3rdparty/Sabre/DAV/Mount/Plugin.php +++ /dev/null @@ -1,79 +0,0 @@ -server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?mount - * - * @param string $method - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='mount') return; - - $currentUri = $this->server->httpRequest->getAbsoluteUri(); - - // Stripping off everything after the ? - list($currentUri) = explode('?',$currentUri); - - $this->davMount($currentUri); - - // Returning false to break the event chain - return false; - - } - - /** - * Generates the davmount response - * - * @param string $uri absolute uri - * @return void - */ - public function davMount($uri) { - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','application/davmount+xml'); - ob_start(); - echo '', "\n"; - echo "\n"; - echo " ", htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "\n"; - echo ""; - $this->server->httpResponse->sendBody(ob_get_clean()); - - } - - -} diff --git a/3rdparty/Sabre/DAV/Node.php b/3rdparty/Sabre/DAV/Node.php deleted file mode 100644 index 0510df5fdf2..00000000000 --- a/3rdparty/Sabre/DAV/Node.php +++ /dev/null @@ -1,55 +0,0 @@ -rootNode = $rootNode; - - } - - /** - * Returns the INode object for the requested path - * - * @param string $path - * @return Sabre_DAV_INode - */ - public function getNodeForPath($path) { - - $path = trim($path,'/'); - if (isset($this->cache[$path])) return $this->cache[$path]; - - //if (!$path || $path=='.') return $this->rootNode; - $currentNode = $this->rootNode; - $i=0; - // We're splitting up the path variable into folder/subfolder components and traverse to the correct node.. - foreach(explode('/',$path) as $pathPart) { - - // If this part of the path is just a dot, it actually means we can skip it - if ($pathPart=='.' || $pathPart=='') continue; - - if (!($currentNode instanceof Sabre_DAV_ICollection)) - throw new Sabre_DAV_Exception_FileNotFound('Could not find node at path: ' . $path); - - $currentNode = $currentNode->getChild($pathPart); - - } - - $this->cache[$path] = $currentNode; - return $currentNode; - - } - - /** - * This function allows you to check if a node exists. - * - * @param string $path - * @return bool - */ - public function nodeExists($path) { - - try { - - // The root always exists - if ($path==='') return true; - - list($parent, $base) = Sabre_DAV_URLUtil::splitPath($path); - - $parentNode = $this->getNodeForPath($parent); - if (!$parentNode instanceof Sabre_DAV_ICollection) return false; - return $parentNode->childExists($base); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - $children = $node->getChildren(); - foreach($children as $child) { - - $this->cache[trim($path,'/') . '/' . $child->getName()] = $child; - - } - return $children; - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - // We don't care enough about sub-paths - // flushing the entire cache - $path = trim($path,'/'); - foreach($this->cache as $nodePath=>$node) { - if ($nodePath == $path || strpos($nodePath,$path.'/')===0) - unset($this->cache[$nodePath]); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property.php b/3rdparty/Sabre/DAV/Property.php deleted file mode 100644 index 577535b0127..00000000000 --- a/3rdparty/Sabre/DAV/Property.php +++ /dev/null @@ -1,25 +0,0 @@ -time = $time; - } elseif (is_int($time) || ctype_digit($time)) { - $this->time = new DateTime('@' . $time); - } else { - $this->time = new DateTime($time); - } - - // Setting timezone to UTC - $this->time->setTimezone(new DateTimeZone('UTC')); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - - $doc = $prop->ownerDocument; - $prop->setAttribute('xmlns:b','urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); - $prop->setAttribute('b:dt','dateTime.rfc1123'); - $prop->nodeValue = $this->time->format(DateTime::RFC1123); - - } - - /** - * getTime - * - * @return DateTime - */ - public function getTime() { - - return $this->time; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/Href.php b/3rdparty/Sabre/DAV/Property/Href.php deleted file mode 100644 index 3294ff2ac68..00000000000 --- a/3rdparty/Sabre/DAV/Property/Href.php +++ /dev/null @@ -1,91 +0,0 @@ -href = $href; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uri - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $this->href; - $dom->appendChild($elem); - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. For non-compatible elements null will be returned. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)==='{DAV:}href') { - return new self($dom->firstChild->textContent,false); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/HrefList.php b/3rdparty/Sabre/DAV/Property/HrefList.php deleted file mode 100644 index 76a5512901c..00000000000 --- a/3rdparty/Sabre/DAV/Property/HrefList.php +++ /dev/null @@ -1,96 +0,0 @@ -hrefs = $hrefs; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uris - * - * @return array - */ - public function getHrefs() { - - return $this->hrefs; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - foreach($this->hrefs as $href) { - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $href; - $dom->appendChild($elem); - } - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - $hrefs = array(); - foreach($dom->childNodes as $child) { - if (Sabre_DAV_XMLUtil::toClarkNotation($child)==='{DAV:}href') { - $hrefs[] = $child->textContent; - } - } - return new self($hrefs, false); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/IHref.php b/3rdparty/Sabre/DAV/Property/IHref.php deleted file mode 100644 index 29d76a44fcd..00000000000 --- a/3rdparty/Sabre/DAV/Property/IHref.php +++ /dev/null @@ -1,25 +0,0 @@ -locks = $locks; - $this->revealLockToken = $revealLockToken; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - foreach($this->locks as $lock) { - - $activeLock = $doc->createElementNS('DAV:','d:activelock'); - $prop->appendChild($activeLock); - - $lockScope = $doc->createElementNS('DAV:','d:lockscope'); - $activeLock->appendChild($lockScope); - - $lockScope->appendChild($doc->createElementNS('DAV:','d:' . ($lock->scope==Sabre_DAV_Locks_LockInfo::EXCLUSIVE?'exclusive':'shared'))); - - $lockType = $doc->createElementNS('DAV:','d:locktype'); - $activeLock->appendChild($lockType); - - $lockType->appendChild($doc->createElementNS('DAV:','d:write')); - - /* {DAV:}lockroot */ - if (!self::$hideLockRoot) { - $lockRoot = $doc->createElementNS('DAV:','d:lockroot'); - $activeLock->appendChild($lockRoot); - $href = $doc->createElementNS('DAV:','d:href'); - $href->appendChild($doc->createTextNode($server->getBaseUri() . $lock->uri)); - $lockRoot->appendChild($href); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:depth',($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY?'infinity':$lock->depth))); - $activeLock->appendChild($doc->createElementNS('DAV:','d:timeout','Second-' . $lock->timeout)); - - if ($this->revealLockToken) { - $lockToken = $doc->createElementNS('DAV:','d:locktoken'); - $activeLock->appendChild($lockToken); - $lockToken->appendChild($doc->createElementNS('DAV:','d:href','opaquelocktoken:' . $lock->token)); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:owner',$lock->owner)); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/ResourceType.php b/3rdparty/Sabre/DAV/Property/ResourceType.php deleted file mode 100644 index 2c606c22d60..00000000000 --- a/3rdparty/Sabre/DAV/Property/ResourceType.php +++ /dev/null @@ -1,125 +0,0 @@ -resourceType = array(); - elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) - $this->resourceType = array('{DAV:}collection'); - elseif (is_array($resourceType)) - $this->resourceType = $resourceType; - else - $this->resourceType = array($resourceType); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $propName = null; - $rt = $this->resourceType; - - foreach($rt as $resourceType) { - if (preg_match('/^{([^}]*)}(.*)$/',$resourceType,$propName)) { - - if (isset($server->xmlNamespaces[$propName[1]])) { - $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]] . ':' . $propName[2])); - } else { - $prop->appendChild($prop->ownerDocument->createElementNS($propName[1],'custom:' . $propName[2])); - } - - } - } - - } - - /** - * Returns the values in clark-notation - * - * For example array('{DAV:}collection') - * - * @return array - */ - public function getValue() { - - return $this->resourceType; - - } - - /** - * Checks if the principal contains a certain value - * - * @param string $type - * @return bool - */ - public function is($type) { - - return in_array($type, $this->resourceType); - - } - - /** - * Adds a resourcetype value to this property - * - * @param string $type - * @return void - */ - public function add($type) { - - $this->resourceType[] = $type; - $this->resourceType = array_unique($this->resourceType); - - } - - /** - * Unserializes a DOM element into a ResourceType property. - * - * @param DOMElement $dom - * @return void - */ - static public function unserialize(DOMElement $dom) { - - $value = array(); - foreach($dom->childNodes as $child) { - - $value[] = Sabre_DAV_XMLUtil::toClarkNotation($child); - - } - - return new self($value); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/Response.php b/3rdparty/Sabre/DAV/Property/Response.php deleted file mode 100644 index 7d3a2db0387..00000000000 --- a/3rdparty/Sabre/DAV/Property/Response.php +++ /dev/null @@ -1,156 +0,0 @@ -href = $href; - $this->responseProperties = $responseProperties; - - } - - /** - * Returns the url - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Returns the property list - * - * @return array - */ - public function getResponseProperties() { - - return $this->responseProperties; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $document = $dom->ownerDocument; - $properties = $this->responseProperties; - - $xresponse = $document->createElement('d:response'); - $dom->appendChild($xresponse); - - $uri = Sabre_DAV_URLUtil::encodePath($this->href); - - // Adding the baseurl to the beginning of the url - $uri = $server->getBaseUri() . $uri; - - $xresponse->appendChild($document->createElement('d:href',$uri)); - - // The properties variable is an array containing properties, grouped by - // HTTP status - foreach($properties as $httpStatus=>$propertyGroup) { - - // The 'href' is also in this array, and it's special cased. - // We will ignore it - if ($httpStatus=='href') continue; - - // If there are no properties in this group, we can also just carry on - if (!count($propertyGroup)) continue; - - $xpropstat = $document->createElement('d:propstat'); - $xresponse->appendChild($xpropstat); - - $xprop = $document->createElement('d:prop'); - $xpropstat->appendChild($xprop); - - $nsList = $server->xmlNamespaces; - - foreach($propertyGroup as $propertyName=>$propertyValue) { - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - // special case for empty namespaces - if ($propName[1]=='') { - - $currentProperty = $document->createElement($propName[2]); - $xprop->appendChild($currentProperty); - $currentProperty->setAttribute('xmlns',''); - - } else { - - if (!isset($nsList[$propName[1]])) { - $nsList[$propName[1]] = 'x' . count($nsList); - } - - // If the namespace was defined in the top-level xml namespaces, it means - // there was already a namespace declaration, and we don't have to worry about it. - if (isset($server->xmlNamespaces[$propName[1]])) { - $currentProperty = $document->createElement($nsList[$propName[1]] . ':' . $propName[2]); - } else { - $currentProperty = $document->createElementNS($propName[1],$nsList[$propName[1]].':' . $propName[2]); - } - $xprop->appendChild($currentProperty); - - } - - if (is_scalar($propertyValue)) { - $text = $document->createTextNode($propertyValue); - $currentProperty->appendChild($text); - } elseif ($propertyValue instanceof Sabre_DAV_Property) { - $propertyValue->serialize($server,$currentProperty); - } elseif (!is_null($propertyValue)) { - throw new Sabre_DAV_Exception('Unknown property value type: ' . gettype($propertyValue) . ' for property: ' . $propertyName); - } - - } - - $xpropstat->appendChild($document->createElement('d:status',$server->httpResponse->getStatusMessage($httpStatus))); - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/ResponseList.php b/3rdparty/Sabre/DAV/Property/ResponseList.php deleted file mode 100644 index cd70b12861d..00000000000 --- a/3rdparty/Sabre/DAV/Property/ResponseList.php +++ /dev/null @@ -1,58 +0,0 @@ -responses = $responses; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - foreach($this->responses as $response) { - $response->serialize($server, $dom); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/SupportedLock.php b/3rdparty/Sabre/DAV/Property/SupportedLock.php deleted file mode 100644 index 01e63f58d9d..00000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedLock.php +++ /dev/null @@ -1,76 +0,0 @@ -supportsLocks = $supportsLocks; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - if (!$this->supportsLocks) return null; - - $lockEntry1 = $doc->createElementNS('DAV:','d:lockentry'); - $lockEntry2 = $doc->createElementNS('DAV:','d:lockentry'); - - $prop->appendChild($lockEntry1); - $prop->appendChild($lockEntry2); - - $lockScope1 = $doc->createElementNS('DAV:','d:lockscope'); - $lockScope2 = $doc->createElementNS('DAV:','d:lockscope'); - $lockType1 = $doc->createElementNS('DAV:','d:locktype'); - $lockType2 = $doc->createElementNS('DAV:','d:locktype'); - - $lockEntry1->appendChild($lockScope1); - $lockEntry1->appendChild($lockType1); - $lockEntry2->appendChild($lockScope2); - $lockEntry2->appendChild($lockType2); - - $lockScope1->appendChild($doc->createElementNS('DAV:','d:exclusive')); - $lockScope2->appendChild($doc->createElementNS('DAV:','d:shared')); - - $lockType1->appendChild($doc->createElementNS('DAV:','d:write')); - $lockType2->appendChild($doc->createElementNS('DAV:','d:write')); - - //$frag->appendXML(''); - //$frag->appendXML(''); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php b/3rdparty/Sabre/DAV/Property/SupportedReportSet.php deleted file mode 100644 index acd9219c0f7..00000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php +++ /dev/null @@ -1,110 +0,0 @@ -addReport($reports); - - } - - /** - * Adds a report to this property - * - * The report must be a string in clark-notation. - * Multiple reports can be specified as an array. - * - * @param mixed $report - * @return void - */ - public function addReport($report) { - - if (!is_array($report)) $report = array($report); - - foreach($report as $r) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$r)) - throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); - - $this->reports[] = $r; - - } - - } - - /** - * Returns the list of supported reports - * - * @return array - */ - public function getValue() { - - return $this->reports; - - } - - /** - * Serializes the node - * - * @param Sabre_DAV_Server $server - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - foreach($this->reports as $reportName) { - - $supportedReport = $prop->ownerDocument->createElement('d:supported-report'); - $prop->appendChild($supportedReport); - - $report = $prop->ownerDocument->createElement('d:report'); - $supportedReport->appendChild($report); - - preg_match('/^{([^}]*)}(.*)$/',$reportName,$matches); - - list(, $namespace, $element) = $matches; - - $prefix = isset($server->xmlNamespaces[$namespace])?$server->xmlNamespaces[$namespace]:null; - - if ($prefix) { - $report->appendChild($prop->ownerDocument->createElement($prefix . ':' . $element)); - } else { - $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:' . $element)); - } - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Server.php b/3rdparty/Sabre/DAV/Server.php deleted file mode 100644 index 3d76d4f1918..00000000000 --- a/3rdparty/Sabre/DAV/Server.php +++ /dev/null @@ -1,1941 +0,0 @@ - 'd', - 'http://sabredav.org/ns' => 's', - ); - - /** - * The propertymap can be used to map properties from - * requests to property classes. - * - * @var array - */ - public $propertyMap = array( - '{DAV:}resourcetype' => 'Sabre_DAV_Property_ResourceType', - ); - - public $protectedProperties = array( - // RFC4918 - '{DAV:}getcontentlength', - '{DAV:}getetag', - '{DAV:}getlastmodified', - '{DAV:}lockdiscovery', - '{DAV:}resourcetype', - '{DAV:}supportedlock', - - // RFC4331 - '{DAV:}quota-available-bytes', - '{DAV:}quota-used-bytes', - - // RFC3744 - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - - ); - - /** - * This is a flag that allow or not showing file, line and code - * of the exception in the returned XML - * - * @var bool - */ - public $debugExceptions = false; - - /** - * This property allows you to automatically add the 'resourcetype' value - * based on a node's classname or interface. - * - * The preset ensures that {DAV:}collection is automaticlly added for nodes - * implementing Sabre_DAV_ICollection. - * - * @var array - */ - public $resourceTypeMapping = array( - 'Sabre_DAV_ICollection' => '{DAV:}collection', - ); - - - /** - * Sets up the server - * - * If a Sabre_DAV_Tree object is passed as an argument, it will - * use it as the directory tree. If a Sabre_DAV_INode is passed, it - * will create a Sabre_DAV_ObjectTree and use the node as the root. - * - * If nothing is passed, a Sabre_DAV_SimpleCollection is created in - * a Sabre_DAV_ObjectTree. - * - * If an array is passed, we automatically create a root node, and use - * the nodes in the array as top-level children. - * - * @param Sabre_DAV_Tree $tree The tree object - * @return void - */ - public function __construct($treeOrNode = null) { - - if ($treeOrNode instanceof Sabre_DAV_Tree) { - $this->tree = $treeOrNode; - } elseif ($treeOrNode instanceof Sabre_DAV_INode) { - $this->tree = new Sabre_DAV_ObjectTree($treeOrNode); - } elseif (is_array($treeOrNode)) { - - // If it's an array, a list of nodes was passed, and we need to - // create the root node. - foreach($treeOrNode as $node) { - if (!($node instanceof Sabre_DAV_INode)) { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode'); - } - } - - $root = new Sabre_DAV_SimpleCollection('root', $treeOrNode); - $this->tree = new Sabre_DAV_ObjectTree($root); - - } elseif (is_null($treeOrNode)) { - $root = new Sabre_DAV_SimpleCollection('root'); - $this->tree = new Sabre_DAV_ObjectTree($root); - } else { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre_DAV_Tree, Sabre_DAV_INode, an array or null'); - } - $this->httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Starts the DAV Server - * - * @return void - */ - public function exec() { - - try { - - $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri()); - - } catch (Exception $e) { - - $DOM = new DOMDocument('1.0','utf-8'); - $DOM->formatOutput = true; - - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s',self::NS_SABREDAV); - $DOM->appendChild($error); - - $error->appendChild($DOM->createElement('s:exception',get_class($e))); - $error->appendChild($DOM->createElement('s:message',$e->getMessage())); - if ($this->debugExceptions) { - $error->appendChild($DOM->createElement('s:file',$e->getFile())); - $error->appendChild($DOM->createElement('s:line',$e->getLine())); - $error->appendChild($DOM->createElement('s:code',$e->getCode())); - $error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString())); - - } - $error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION)); - - if($e instanceof Sabre_DAV_Exception) { - - $httpCode = $e->getHTTPCode(); - $e->serialize($this,$error); - $headers = $e->getHTTPHeaders($this); - - } else { - - $httpCode = 500; - $headers = array(); - - } - $headers['Content-Type'] = 'application/xml; charset=utf-8'; - - $this->httpResponse->sendStatus($httpCode); - $this->httpResponse->setHeaders($headers); - $this->httpResponse->sendBody($DOM->saveXML()); - - } - - } - - /** - * Sets the base server uri - * - * @param string $uri - * @return void - */ - public function setBaseUri($uri) { - - // If the baseUri does not end with a slash, we must add it - if ($uri[strlen($uri)-1]!=='/') - $uri.='/'; - - $this->baseUri = $uri; - - } - - /** - * Returns the base responding uri - * - * @return string - */ - public function getBaseUri() { - - if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri(); - return $this->baseUri; - - } - - /** - * This method attempts to detect the base uri. - * Only the PATH_INFO variable is considered. - * - * If this variable is not set, the root (/) is assumed. - * - * @return void - */ - public function guessBaseUri() { - - $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO'); - $uri = $this->httpRequest->getRawServerValue('REQUEST_URI'); - - // If PATH_INFO is found, we can assume it's accurate. - if (!empty($pathInfo)) { - - // We need to make sure we ignore the QUERY_STRING part - if ($pos = strpos($uri,'?')) - $uri = substr($uri,0,$pos); - - // PATH_INFO is only set for urls, such as: /example.php/path - // in that case PATH_INFO contains '/path'. - // Note that REQUEST_URI is percent encoded, while PATH_INFO is - // not, Therefore they are only comparable if we first decode - // REQUEST_INFO as well. - $decodedUri = Sabre_DAV_URLUtil::decodePath($uri); - - // A simple sanity check: - if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) { - $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo)); - return rtrim($baseUri,'/') . '/'; - } - - throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.'); - - } - - // The last fallback is that we're just going to assume the server root. - return '/'; - - } - - /** - * Adds a plugin to the server - * - * For more information, console the documentation of Sabre_DAV_ServerPlugin - * - * @param Sabre_DAV_ServerPlugin $plugin - * @return void - */ - public function addPlugin(Sabre_DAV_ServerPlugin $plugin) { - - $this->plugins[$plugin->getPluginName()] = $plugin; - $plugin->initialize($this); - - } - - /** - * Returns an initialized plugin by it's name. - * - * This function returns null if the plugin was not found. - * - * @param string $name - * @return Sabre_DAV_ServerPlugin - */ - public function getPlugin($name) { - - if (isset($this->plugins[$name])) - return $this->plugins[$name]; - - // This is a fallback and deprecated. - foreach($this->plugins as $plugin) { - if (get_class($plugin)===$name) return $plugin; - } - - return null; - - } - - /** - * Returns all plugins - * - * @return array - */ - public function getPlugins() { - - return $this->plugins; - - } - - - - /** - * Subscribe to an event. - * - * When the event is triggered, we'll call all the specified callbacks. - * It is possible to control the order of the callbacks through the - * priority argument. - * - * This is for example used to make sure that the authentication plugin - * is triggered before anything else. If it's not needed to change this - * number, it is recommended to ommit. - * - * @param string $event - * @param callback $callback - * @param int $priority - * @return void - */ - public function subscribeEvent($event, $callback, $priority = 100) { - - if (!isset($this->eventSubscriptions[$event])) { - $this->eventSubscriptions[$event] = array(); - } - while(isset($this->eventSubscriptions[$event][$priority])) $priority++; - $this->eventSubscriptions[$event][$priority] = $callback; - ksort($this->eventSubscriptions[$event]); - - } - - /** - * Broadcasts an event - * - * This method will call all subscribers. If one of the subscribers returns false, the process stops. - * - * The arguments parameter will be sent to all subscribers - * - * @param string $eventName - * @param array $arguments - * @return bool - */ - public function broadcastEvent($eventName,$arguments = array()) { - - if (isset($this->eventSubscriptions[$eventName])) { - - foreach($this->eventSubscriptions[$eventName] as $subscriber) { - - $result = call_user_func_array($subscriber,$arguments); - if ($result===false) return false; - - } - - } - - return true; - - } - - /** - * Handles a http request, and execute a method based on its name - * - * @param string $method - * @param string $uri - * @return void - */ - public function invokeMethod($method, $uri) { - - $method = strtoupper($method); - - if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return; - - // Make sure this is a HTTP method we support - $internalMethods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'MKCOL', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - if (in_array($method,$internalMethods)) { - - call_user_func(array($this,'http' . $method), $uri); - - } else { - - if ($this->broadcastEvent('unknownMethod',array($method, $uri))) { - // Unsupported method - throw new Sabre_DAV_Exception_NotImplemented(); - } - - } - - } - - // {{{ HTTP Method implementations - - /** - * HTTP OPTIONS - * - * @param string $uri - * @return void - */ - protected function httpOptions($uri) { - - $methods = $this->getAllowedMethods($uri); - - $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods))); - $features = array('1','3', 'extended-mkcol'); - - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - $this->httpResponse->setHeader('MS-Author-Via','DAV'); - $this->httpResponse->setHeader('Accept-Ranges','bytes'); - $this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION); - $this->httpResponse->setHeader('Content-Length',0); - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP GET - * - * This method simply fetches the contents of a uri, like normal - * - * @param string $uri - * @return void - */ - protected function httpGet($uri) { - - $node = $this->tree->getNodeForPath($uri,0); - - if (!$this->checkPreconditions(true)) return false; - - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); - $body = $node->get(); - - // Converting string into stream, if needed. - if (is_string($body)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$body); - rewind($stream); - $body = $stream; - } - - /* - * TODO: getetag, getlastmodified, getsize should also be used using - * this method - */ - $httpHeaders = $this->getHTTPHeaders($uri); - - /* ContentType needs to get a default, because many webservers will otherwise - * default to text/html, and we don't want this for security reasons. - */ - if (!isset($httpHeaders['Content-Type'])) { - $httpHeaders['Content-Type'] = 'application/octet-stream'; - } - - - if (isset($httpHeaders['Content-Length'])) { - - $nodeSize = $httpHeaders['Content-Length']; - - // Need to unset Content-Length, because we'll handle that during figuring out the range - unset($httpHeaders['Content-Length']); - - } else { - $nodeSize = null; - } - - $this->httpResponse->setHeaders($httpHeaders); - - $range = $this->getHTTPRange(); - $ifRange = $this->httpRequest->getHeader('If-Range'); - $ignoreRangeHeader = false; - - // If ifRange is set, and range is specified, we first need to check - // the precondition. - if ($nodeSize && $range && $ifRange) { - - // if IfRange is parsable as a date we'll treat it as a DateTime - // otherwise, we must treat it as an etag. - try { - $ifRangeDate = new DateTime($ifRange); - - // It's a date. We must check if the entity is modified since - // the specified date. - if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true; - else { - $modified = new DateTime($httpHeaders['Last-Modified']); - if($modified > $ifRangeDate) $ignoreRangeHeader = true; - } - - } catch (Exception $e) { - - // It's an entity. We can do a simple comparison. - if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true; - elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true; - } - } - - // We're only going to support HTTP ranges if the backend provided a filesize - if (!$ignoreRangeHeader && $nodeSize && $range) { - - // Determining the exact byte offsets - if (!is_null($range[0])) { - - $start = $range[0]; - $end = $range[1]?$range[1]:$nodeSize-1; - if($start >= $nodeSize) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')'); - - if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); - if($end >= $nodeSize) $end = $nodeSize-1; - - } else { - - $start = $nodeSize-$range[1]; - $end = $nodeSize-1; - - if ($start<0) $start = 0; - - } - - // New read/write stream - $newStream = fopen('php://temp','r+'); - - stream_copy_to_stream($body, $newStream, $end-$start+1, $start); - rewind($newStream); - - $this->httpResponse->setHeader('Content-Length', $end-$start+1); - $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize); - $this->httpResponse->sendStatus(206); - $this->httpResponse->sendBody($newStream); - - - } else { - - if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize); - $this->httpResponse->sendStatus(200); - $this->httpResponse->sendBody($body); - - } - - } - - /** - * HTTP HEAD - * - * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body - * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again - * - * @param string $uri - * @return void - */ - protected function httpHead($uri) { - - $node = $this->tree->getNodeForPath($uri); - /* This information is only collection for File objects. - * Ideally we want to throw 405 Method Not Allowed for every - * non-file, but MS Office does not like this - */ - if ($node instanceof Sabre_DAV_IFile) { - $headers = $this->getHTTPHeaders($this->getRequestUri()); - if (!isset($headers['Content-Type'])) { - $headers['Content-Type'] = 'application/octet-stream'; - } - $this->httpResponse->setHeaders($headers); - } - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP Delete - * - * The HTTP delete method, deletes a given uri - * - * @param string $uri - * @return void - */ - protected function httpDelete($uri) { - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - $this->httpResponse->sendStatus(204); - $this->httpResponse->setHeader('Content-Length','0'); - - } - - - /** - * WebDAV PROPFIND - * - * This WebDAV method requests information about an uri resource, or a list of resources - * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value - * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory) - * - * The request body contains an XML data structure that has a list of properties the client understands - * The response body is also an xml document, containing information about every uri resource and the requested properties - * - * It has to return a HTTP 207 Multi-status status code - * - * @param string $uri - * @return void - */ - protected function httpPropfind($uri) { - - // $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input')); - $requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true)); - - $depth = $this->getHTTPDepth(1); - // The only two options for the depth of a propfind is 0 or 1 - if ($depth!=0) $depth = 1; - - $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth); - - // This is a multi-status response - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - // Normally this header is only needed for OPTIONS responses, however.. - // iCal seems to also depend on these being set for PROPFIND. Since - // this is not harmful, we'll add it. - $features = array('1','3', 'extended-mkcol'); - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - - $data = $this->generateMultiStatus($newProperties); - $this->httpResponse->sendBody($data); - - } - - /** - * WebDAV PROPPATCH - * - * This method is called to update properties on a Node. The request is an XML body with all the mutations. - * In this XML body it is specified which properties should be set/updated and/or deleted - * - * @param string $uri - * @return void - */ - protected function httpPropPatch($uri) { - - $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true)); - - $result = $this->updateProperties($uri, $newProperties); - - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } - - /** - * HTTP PUT method - * - * This HTTP method updates a file, or creates a new one. - * - * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 200 Ok - * - * @param string $uri - * @return void - */ - protected function httpPut($uri) { - - $body = $this->httpRequest->getBody(); - - // Intercepting Content-Range - if ($this->httpRequest->getHeader('Content-Range')) { - /** - Content-Range is dangerous for PUT requests: PUT per definition - stores a full resource. draft-ietf-httpbis-p2-semantics-15 says - in section 7.6: - An origin server SHOULD reject any PUT request that contains a - Content-Range header field, since it might be misinterpreted as - partial content (or might be partial content that is being mistakenly - PUT as a full representation). Partial content updates are possible - by targeting a separately identified resource with state that - overlaps a portion of the larger resource, or by using a different - method that has been specifically defined for partial updates (for - example, the PATCH method defined in [RFC5789]). - This clarifies RFC2616 section 9.6: - The recipient of the entity MUST NOT ignore any Content-* - (e.g. Content-Range) headers that it does not understand or implement - and MUST return a 501 (Not Implemented) response in such cases. - OTOH is a PUT request with a Content-Range currently the only way to - continue an aborted upload request and is supported by curl, mod_dav, - Tomcat and others. Since some clients do use this feature which results - in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject - all PUT requests with a Content-Range for now. - */ - - throw new Sabre_DAV_Exception_NotImplemented('PUT with Content-Range is not allowed.'); - } - - // Intercepting the Finder problem - if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { - - /** - Many webservers will not cooperate well with Finder PUT requests, - because it uses 'Chunked' transfer encoding for the request body. - - The symptom of this problem is that Finder sends files to the - server, but they arrive as 0-lenght files in PHP. - - If we don't do anything, the user might think they are uploading - files successfully, but they end up empty on the server. Instead, - we throw back an error if we detect this. - - The reason Finder uses Chunked, is because it thinks the files - might change as it's being uploaded, and therefore the - Content-Length can vary. - - Instead it sends the X-Expected-Entity-Length header with the size - of the file at the very start of the request. If this header is set, - but we don't get a request body we will fail the request to - protect the end-user. - */ - - // Only reading first byte - $firstByte = fread($body,1); - if (strlen($firstByte)!==1) { - throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); - } - - // The body needs to stay intact, so we copy everything to a - // temporary stream. - - $newBody = fopen('php://temp','r+'); - fwrite($newBody,$firstByte); - stream_copy_to_stream($body, $newBody); - rewind($newBody); - - $body = $newBody; - - } - - if ($this->tree->nodeExists($uri)) { - - $node = $this->tree->getNodeForPath($uri); - - // Checking If-None-Match and related headers. - if (!$this->checkPreconditions()) return; - - // If the node is a collection, we'll deny it - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); - if (!$this->broadcastEvent('beforeWriteContent',array($this->getRequestUri()))) return false; - - $node->put($body); - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(204); - - } else { - - // If we got here, the resource didn't exist yet. - if (!$this->createFile($this->getRequestUri(),$body)) { - // For one reason or another the file was not created. - return; - } - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - - } - - } - - - /** - * WebDAV MKCOL - * - * The MKCOL method is used to create a new collection (directory) on the server - * - * @param string $uri - * @return void - */ - protected function httpMkcol($uri) { - - $requestBody = $this->httpRequest->getBody(true); - - if ($requestBody) { - - $contentType = $this->httpRequest->getHeader('Content-Type'); - if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type'); - - } - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody); - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.'); - - } - - $properties = array(); - foreach($dom->firstChild->childNodes as $childNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue; - $properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap)); - - } - if (!isset($properties['{DAV:}resourcetype'])) - throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property'); - - $resourceType = $properties['{DAV:}resourcetype']->getValue(); - unset($properties['{DAV:}resourcetype']); - - } else { - - $properties = array(); - $resourceType = array('{DAV:}collection'); - - } - - $result = $this->createCollection($uri, $resourceType, $properties); - - if (is_array($result)) { - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } else { - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - } - - } - - /** - * WebDAV HTTP MOVE method - * - * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpMove($uri) { - - $moveInfo = $this->getCopyAndMoveInfo(); - - // If the destination is part of the source tree, we must fail - if ($moveInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($moveInfo['destinationExists']) { - - if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false; - $this->tree->delete($moveInfo['destination']); - - } - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false; - if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false; - $this->tree->move($uri,$moveInfo['destination']); - $this->broadcastEvent('afterBind',array($moveInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201); - - } - - /** - * WebDAV HTTP COPY method - * - * This method copies one uri to a different uri, and works much like the MOVE request - * A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpCopy($uri) { - - $copyInfo = $this->getCopyAndMoveInfo(); - // If the destination is part of the source tree, we must fail - if ($copyInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($copyInfo['destinationExists']) { - if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false; - $this->tree->delete($copyInfo['destination']); - - } - if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false; - $this->tree->copy($uri,$copyInfo['destination']); - $this->broadcastEvent('afterBind',array($copyInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201); - - } - - - - /** - * HTTP REPORT method implementation - * - * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253) - * It's used in a lot of extensions, so it made sense to implement it into the core. - * - * @param string $uri - * @return void - */ - protected function httpReport($uri) { - - $body = $this->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild); - - if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) { - - // If broadcastEvent returned true, it means the report was not supported - throw new Sabre_DAV_Exception_ReportNotImplemented(); - - } - - } - - // }}} - // {{{ HTTP/WebDAV protocol helpers - - /** - * Returns an array with all the supported HTTP methods for a specific uri. - * - * @param string $uri - * @return array - */ - public function getAllowedMethods($uri) { - - $methods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - // The MKCOL is only allowed on an unmapped uri - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $methods[] = 'MKCOL'; - } - - // We're also checking if any of the plugins register any new methods - foreach($this->plugins as $plugin) $methods = array_merge($methods,$plugin->getHTTPMethods($uri)); - array_unique($methods); - - return $methods; - - } - - /** - * Gets the uri for the request, keeping the base uri into consideration - * - * @return string - */ - public function getRequestUri() { - - return $this->calculateUri($this->httpRequest->getUri()); - - } - - /** - * Calculates the uri for a request, making sure that the base uri is stripped out - * - * @param string $uri - * @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri - * @return string - */ - public function calculateUri($uri) { - - if ($uri[0]!='/' && strpos($uri,'://')) { - - $uri = parse_url($uri,PHP_URL_PATH); - - } - - $uri = str_replace('//','/',$uri); - - if (strpos($uri,$this->getBaseUri())===0) { - - return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/'); - - // A special case, if the baseUri was accessed without a trailing - // slash, we'll accept it as well. - } elseif ($uri.'/' === $this->getBaseUri()) { - - return ''; - - } else { - - throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')'); - - } - - } - - /** - * Returns the HTTP depth header - * - * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object - * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existant - * - * @param mixed $default - * @return int - */ - public function getHTTPDepth($default = self::DEPTH_INFINITY) { - - // If its not set, we'll grab the default - $depth = $this->httpRequest->getHeader('Depth'); - - if (is_null($depth)) return $default; - - if ($depth == 'infinity') return self::DEPTH_INFINITY; - - - // If its an unknown value. we'll grab the default - if (!ctype_digit($depth)) return $default; - - return (int)$depth; - - } - - /** - * Returns the HTTP range header - * - * This method returns null if there is no well-formed HTTP range request - * header or array($start, $end). - * - * The first number is the offset of the first byte in the range. - * The second number is the offset of the last byte in the range. - * - * If the second offset is null, it should be treated as the offset of the last byte of the entity - * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity - * - * return $mixed - */ - public function getHTTPRange() { - - $range = $this->httpRequest->getHeader('range'); - if (is_null($range)) return null; - - // Matching "Range: bytes=1234-5678: both numbers are optional - - if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; - - if ($matches[1]==='' && $matches[2]==='') return null; - - return array( - $matches[1]!==''?$matches[1]:null, - $matches[2]!==''?$matches[2]:null, - ); - - } - - - /** - * Returns information about Copy and Move requests - * - * This function is created to help getting information about the source and the destination for the - * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions - * - * The returned value is an array with the following keys: - * * destination - Destination path - * * destinationExists - Wether or not the destination is an existing url (and should therefore be overwritten) - * - * @return array - */ - public function getCopyAndMoveInfo() { - - // Collecting the relevant HTTP headers - if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); - $destination = $this->calculateUri($this->httpRequest->getHeader('Destination')); - $overwrite = $this->httpRequest->getHeader('Overwrite'); - if (!$overwrite) $overwrite = 'T'; - if (strtoupper($overwrite)=='T') $overwrite = true; - elseif (strtoupper($overwrite)=='F') $overwrite = false; - // We need to throw a bad request exception, if the header was invalid - else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); - - list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination); - - try { - $destinationParent = $this->tree->getNodeForPath($destinationDir); - if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // If the destination parent node is not found, we throw a 409 - throw new Sabre_DAV_Exception_Conflict('The destination node is not found'); - } - - try { - - $destinationNode = $this->tree->getNodeForPath($destination); - - // If this succeeded, it means the destination already exists - // we'll need to throw precondition failed in case overwrite is false - if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // Destination didn't exist, we're all good - $destinationNode = false; - - - - } - - // These are the three relevant properties we need to return - return array( - 'destination' => $destination, - 'destinationExists' => $destinationNode==true, - 'destinationNode' => $destinationNode, - ); - - } - - /** - * Returns a list of properties for a path - * - * This is a simplified version getPropertiesForPath. - * if you aren't interested in status codes, but you just - * want to have a flat list of properties. Use this method. - * - * @param string $path - * @param array $propertyNames - */ - public function getProperties($path, $propertyNames) { - - $result = $this->getPropertiesForPath($path,$propertyNames,0); - return $result[0][200]; - - } - - /** - * Returns a list of HTTP headers for a particular resource - * - * The generated http headers are based on properties provided by the - * resource. The method basically provides a simple mapping between - * DAV property and HTTP header. - * - * The headers are intended to be used for HEAD and GET requests. - * - * @param string $path - */ - public function getHTTPHeaders($path) { - - $propertyMap = array( - '{DAV:}getcontenttype' => 'Content-Type', - '{DAV:}getcontentlength' => 'Content-Length', - '{DAV:}getlastmodified' => 'Last-Modified', - '{DAV:}getetag' => 'ETag', - ); - - $properties = $this->getProperties($path,array_keys($propertyMap)); - - $headers = array(); - foreach($propertyMap as $property=>$header) { - if (!isset($properties[$property])) continue; - - if (is_scalar($properties[$property])) { - $headers[$header] = $properties[$property]; - - // GetLastModified gets special cased - } elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) { - $headers[$header] = $properties[$property]->getTime()->format(DateTime::RFC1123); - } - - } - - return $headers; - - } - - /** - * Returns a list of properties for a given path - * - * The path that should be supplied should have the baseUrl stripped out - * The list of properties should be supplied in Clark notation. If the list is empty - * 'allprops' is assumed. - * - * If a depth of 1 is requested child elements will also be returned. - * - * @param string $path - * @param array $propertyNames - * @param int $depth - * @return array - */ - public function getPropertiesForPath($path,$propertyNames = array(),$depth = 0) { - - if ($depth!=0) $depth = 1; - - $returnPropertyList = array(); - - $parentNode = $this->tree->getNodeForPath($path); - $nodes = array( - $path => $parentNode - ); - if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) { - foreach($this->tree->getChildren($path) as $childNode) - $nodes[$path . '/' . $childNode->getName()] = $childNode; - } - - // If the propertyNames array is empty, it means all properties are requested. - // We shouldn't actually return everything we know though, and only return a - // sensible list. - $allProperties = count($propertyNames)==0; - - foreach($nodes as $myPath=>$node) { - - $currentPropertyNames = $propertyNames; - - $newProperties = array( - '200' => array(), - '404' => array(), - ); - - if ($allProperties) { - // Default list of propertyNames, when all properties were requested. - $currentPropertyNames = array( - '{DAV:}getlastmodified', - '{DAV:}getcontentlength', - '{DAV:}resourcetype', - '{DAV:}quota-used-bytes', - '{DAV:}quota-available-bytes', - '{DAV:}getetag', - '{DAV:}getcontenttype', - ); - } - - // If the resourceType was not part of the list, we manually add it - // and mark it for removal. We need to know the resourcetype in order - // to make certain decisions about the entry. - // WebDAV dictates we should add a / and the end of href's for collections - $removeRT = false; - if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) { - $currentPropertyNames[] = '{DAV:}resourcetype'; - $removeRT = true; - } - - $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties)); - // If this method explicitly returned false, we must ignore this - // node as it is inacessible. - if ($result===false) continue; - - if (count($currentPropertyNames) > 0) { - - if ($node instanceof Sabre_DAV_IProperties) - $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); - - } - - - foreach($currentPropertyNames as $prop) { - - if (isset($newProperties[200][$prop])) continue; - - switch($prop) { - case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break; - case '{DAV:}getcontentlength' : if ($node instanceof Sabre_DAV_IFile) $newProperties[200][$prop] = (int)$node->getSize(); break; - case '{DAV:}quota-used-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[0]; - } - break; - case '{DAV:}quota-available-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[1]; - } - break; - case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break; - case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break; - case '{DAV:}supported-report-set' : - $reports = array(); - foreach($this->plugins as $plugin) { - $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath)); - } - $newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports); - break; - case '{DAV:}resourcetype' : - $newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType(); - foreach($this->resourceTypeMapping as $className => $resourceType) { - if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType); - } - break; - - } - - // If we were unable to find the property, we will list it as 404. - if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null; - - } - - $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties)); - - $newProperties['href'] = trim($myPath,'/'); - - // Its is a WebDAV recommendation to add a trailing slash to collectionnames. - // Apple's iCal also requires a trailing slash for principals (rfc 3744). - // Therefore we add a trailing / for any non-file. This might need adjustments - // if we find there are other edge cases. - if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/'; - - // If the resourcetype property was manually added to the requested property list, - // we will remove it again. - if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']); - - $returnPropertyList[] = $newProperties; - - } - - return $returnPropertyList; - - } - - /** - * This method is invoked by sub-systems creating a new file. - * - * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin). - * It was important to get this done through a centralized function, - * allowing plugins to intercept this using the beforeCreateFile event. - * - * This method will return true if the file was actually created - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function createFile($uri,$data) { - - list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri); - - if (!$this->broadcastEvent('beforeBind',array($uri))) return false; - if (!$this->broadcastEvent('beforeCreateFile',array($uri,$data))) return false; - - $parent = $this->tree->getNodeForPath($dir); - $parent->createFile($name,$data); - $this->tree->markDirty($dir); - - $this->broadcastEvent('afterBind',array($uri)); - - return true; - } - - /** - * This method is invoked by sub-systems creating a new directory. - * - * @param string $uri - * @return void - */ - public function createDirectory($uri) { - - $this->createCollection($uri,array('{DAV:}collection'),array()); - - } - - /** - * Use this method to create a new collection - * - * The {DAV:}resourcetype is specified using the resourceType array. - * At the very least it must contain {DAV:}collection. - * - * The properties array can contain a list of additional properties. - * - * @param string $uri The new uri - * @param array $resourceType The resourceType(s) - * @param array $properties A list of properties - * @return void - */ - public function createCollection($uri, array $resourceType, array $properties) { - - list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri); - - // Making sure {DAV:}collection was specified as resourceType - if (!in_array('{DAV:}collection', $resourceType)) { - throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection'); - } - - - // Making sure the parent exists - try { - - $parent = $this->tree->getNodeForPath($parentUri); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - throw new Sabre_DAV_Exception_Conflict('Parent node does not exist'); - - } - - // Making sure the parent is a collection - if (!$parent instanceof Sabre_DAV_ICollection) { - throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection'); - } - - - - // Making sure the child does not already exist - try { - $parent->getChild($newName); - - // If we got here.. it means there's already a node on that url, and we need to throw a 405 - throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // This is correct - } - - - if (!$this->broadcastEvent('beforeBind',array($uri))) return; - - // There are 2 modes of operation. The standard collection - // creates the directory, and then updates properties - // the extended collection can create it directly. - if ($parent instanceof Sabre_DAV_IExtendedCollection) { - - $parent->createExtendedCollection($newName, $resourceType, $properties); - - } else { - - // No special resourcetypes are supported - if (count($resourceType)>1) { - throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.'); - } - - $parent->createDirectory($newName); - $rollBack = false; - $exception = null; - $errorResult = null; - - if (count($properties)>0) { - - try { - - $errorResult = $this->updateProperties($uri, $properties); - if (!isset($errorResult[200])) { - $rollBack = true; - } - - } catch (Sabre_DAV_Exception $e) { - - $rollBack = true; - $exception = $e; - - } - - } - - if ($rollBack) { - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - // Re-throwing exception - if ($exception) throw $exception; - - return $errorResult; - } - - } - $this->tree->markDirty($parentUri); - $this->broadcastEvent('afterBind',array($uri)); - - } - - /** - * This method updates a resource's properties - * - * The properties array must be a list of properties. Array-keys are - * property names in clarknotation, array-values are it's values. - * If a property must be deleted, the value should be null. - * - * Note that this request should either completely succeed, or - * completely fail. - * - * The response is an array with statuscodes for keys, which in turn - * contain arrays with propertynames. This response can be used - * to generate a multistatus body. - * - * @param string $uri - * @param array $properties - * @return array - */ - public function updateProperties($uri, array $properties) { - - // we'll start by grabbing the node, this will throw the appropriate - // exceptions if it doesn't. - $node = $this->tree->getNodeForPath($uri); - - $result = array( - 200 => array(), - 403 => array(), - 424 => array(), - ); - $remainingProperties = $properties; - $hasError = false; - - // Running through all properties to make sure none of them are protected - if (!$hasError) foreach($properties as $propertyName => $value) { - if(in_array($propertyName, $this->protectedProperties)) { - $result[403][$propertyName] = null; - unset($remainingProperties[$propertyName]); - $hasError = true; - } - } - - if (!$hasError) { - // Allowing plugins to take care of property updating - $hasError = !$this->broadcastEvent('updateProperties',array( - &$remainingProperties, - &$result, - $node - )); - } - - // If the node is not an instance of Sabre_DAV_IProperties, every - // property is 403 Forbidden - if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) { - $hasError = true; - foreach($properties as $propertyName=> $value) { - $result[403][$propertyName] = null; - } - $remainingProperties = array(); - } - - // Only if there were no errors we may attempt to update the resource - if (!$hasError) { - - if (count($remainingProperties)>0) { - - $updateResult = $node->updateProperties($remainingProperties); - - if ($updateResult===true) { - // success - foreach($remainingProperties as $propertyName=>$value) { - $result[200][$propertyName] = null; - } - - } elseif ($updateResult===false) { - // The node failed to update the properties for an - // unknown reason - foreach($remainingProperties as $propertyName=>$value) { - $result[403][$propertyName] = null; - } - - } elseif (is_array($updateResult)) { - - // The node has detailed update information - // We need to merge the results with the earlier results. - foreach($updateResult as $status => $props) { - if (is_array($props)) { - if (!isset($result[$status])) - $result[$status] = array(); - - $result[$status] = array_merge($result[$status], $updateResult[$status]); - } - } - - } else { - throw new Sabre_DAV_Exception('Invalid result from updateProperties'); - } - $remainingProperties = array(); - } - - } - - foreach($remainingProperties as $propertyName=>$value) { - // if there are remaining properties, it must mean - // there's a dependency failure - $result[424][$propertyName] = null; - } - - // Removing empty array values - foreach($result as $status=>$props) { - - if (count($props)===0) unset($result[$status]); - - } - $result['href'] = $uri; - return $result; - - } - - /** - * This method checks the main HTTP preconditions. - * - * Currently these are: - * * If-Match - * * If-None-Match - * * If-Modified-Since - * * If-Unmodified-Since - * - * The method will return true if all preconditions are met - * The method will return false, or throw an exception if preconditions - * failed. If false is returned the operation should be aborted, and - * the appropriate HTTP response headers are already set. - * - * Normally this method will throw 412 Precondition Failed for failures - * related to If-None-Match, If-Match and If-Unmodified Since. It will - * set the status to 304 Not Modified for If-Modified_since. - * - * If the $handleAsGET argument is set to true, it will also return 304 - * Not Modified for failure of the If-None-Match precondition. This is the - * desired behaviour for HTTP GET and HTTP HEAD requests. - * - * @return bool - */ - public function checkPreconditions($handleAsGET = false) { - - $uri = $this->getRequestUri(); - $node = null; - $lastMod = null; - $etag = null; - - if ($ifMatch = $this->httpRequest->getHeader('If-Match')) { - - // If-Match contains an entity tag. Only if the entity-tag - // matches we are allowed to make the request succeed. - // If the entity-tag is '*' we are only allowed to make the - // request succeed if a resource exists at that url. - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match'); - } - - // Only need to check entity tags if they are not * - if ($ifMatch!=='*') { - - // There can be multiple etags - $ifMatch = explode(',',$ifMatch); - $haveMatch = false; - foreach($ifMatch as $ifMatchItem) { - - // Stripping any extra spaces - $ifMatchItem = trim($ifMatchItem,' '); - - $etag = $node->getETag(); - if ($etag===$ifMatchItem) { - $haveMatch = true; - } - } - if (!$haveMatch) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match'); - } - } - } - - if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) { - - // The If-None-Match header contains an etag. - // Only if the ETag does not match the current ETag, the request will succeed - // The header can also contain *, in which case the request - // will only succeed if the entity does not exist at all. - $nodeExists = true; - if (!$node) { - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $nodeExists = false; - } - } - if ($nodeExists) { - $haveMatch = false; - if ($ifNoneMatch==='*') $haveMatch = true; - else { - - // There might be multiple etags - $ifNoneMatch = explode(',', $ifNoneMatch); - $etag = $node->getETag(); - - foreach($ifNoneMatch as $ifNoneMatchItem) { - - // Stripping any extra spaces - $ifNoneMatchItem = trim($ifNoneMatchItem,' '); - - if ($etag===$ifNoneMatchItem) $haveMatch = true; - - } - - } - - if ($haveMatch) { - if ($handleAsGET) { - $this->httpResponse->sendStatus(304); - return false; - } else { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match'); - } - } - } - - } - - if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) { - - // The If-Modified-Since header contains a date. We - // will only return the entity if it has been changed since - // that date. If it hasn't been changed, we return a 304 - // header - // Note that this header only has to be checked if there was no If-None-Match header - // as per the HTTP spec. - $date = Sabre_HTTP_Util::parseHTTPDate($ifModifiedSince); - - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod <= $date) { - $this->httpResponse->sendStatus(304); - return false; - } - } - } - } - - if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) { - - // The If-Unmodified-Since will allow allow the request if the - // entity has not changed since the specified date. - $date = Sabre_HTTP_Util::parseHTTPDate($ifUnmodifiedSince); - - // We must only check the date if it's valid - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod > $date) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since'); - } - } - } - - } - return true; - - } - - // }}} - // {{{ XML Readers & Writers - - - /** - * Generates a WebDAV propfind response body based on a list of nodes - * - * @param array $fileProperties The list with nodes - * @param array $requestedProperties The properties that should be returned - * @return string - */ - public function generateMultiStatus(array $fileProperties) { - - $dom = new DOMDocument('1.0','utf-8'); - //$dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($fileProperties as $entry) { - - $href = $entry['href']; - unset($entry['href']); - - $response = new Sabre_DAV_Property_Response($href,$entry); - $response->serialize($this,$multiStatus); - - } - - return $dom->saveXML(); - - } - - /** - * This method parses a PropPatch request - * - * PropPatch changes the properties for a resource. This method - * returns a list of properties. - * - * The keys in the returned array contain the property name (e.g.: {DAV:}displayname, - * and the value contains the property value. If a property is to be removed the value - * will be null. - * - * @param string $body xml body - * @return array list of properties in need of updating or deletion - */ - public function parsePropPatchRequest($body) { - - //We'll need to change the DAV namespace declaration to something else in order to make it parsable - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newProperties = array(); - - foreach($dom->firstChild->childNodes as $child) { - - if ($child->nodeType !== XML_ELEMENT_NODE) continue; - - $operation = Sabre_DAV_XMLUtil::toClarkNotation($child); - - if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue; - - $innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap); - - foreach($innerProperties as $propertyName=>$propertyValue) { - - if ($operation==='{DAV:}remove') { - $propertyValue = null; - } - - $newProperties[$propertyName] = $propertyValue; - - } - - } - - return $newProperties; - - } - - /** - * This method parses the PROPFIND request and returns its information - * - * This will either be a list of properties, or an empty array; in which case - * an {DAV:}allprop was requested. - * - * @param string $body - * @return array - */ - public function parsePropFindRequest($body) { - - // If the propfind body was empty, it means IE is requesting 'all' properties - if (!$body) return array(); - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0); - return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); - - } - - // }}} - -} - diff --git a/3rdparty/Sabre/DAV/ServerPlugin.php b/3rdparty/Sabre/DAV/ServerPlugin.php deleted file mode 100644 index 6909f600c21..00000000000 --- a/3rdparty/Sabre/DAV/ServerPlugin.php +++ /dev/null @@ -1,90 +0,0 @@ -name = $name; - foreach($children as $child) { - - if (!($child instanceof Sabre_DAV_INode)) throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); - $this->addChild($child); - - } - - } - - /** - * Adds a new childnode to this collection - * - * @param Sabre_DAV_INode $child - * @return void - */ - public function addChild(Sabre_DAV_INode $child) { - - $this->children[$child->getName()] = $child; - - } - - /** - * Returns the name of the collection - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns a child object, by its name. - * - * This method makes use of the getChildren method to grab all the child nodes, and compares the name. - * Generally its wise to override this, as this can usually be optimized - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - if (isset($this->children[$name])) return $this->children[$name]; - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name . ' in \'' . $this->getName() . '\''); - - } - - /** - * Returns a list of children for this collection - * - * @return array - */ - public function getChildren() { - - return array_values($this->children); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/SimpleDirectory.php b/3rdparty/Sabre/DAV/SimpleDirectory.php deleted file mode 100644 index 516a3aa907c..00000000000 --- a/3rdparty/Sabre/DAV/SimpleDirectory.php +++ /dev/null @@ -1,21 +0,0 @@ -name = $name; - $this->contents = $contents; - $this->mimeType = $mimeType; - - } - - /** - * Returns the node name for this file. - * - * This name is used to construct the url. - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns the data - * - * This method may either return a string or a readable stream resource - * - * @return mixed - */ - public function get() { - - return $this->contents; - - } - - /** - * Returns the size of the file, in bytes. - * - * @return int - */ - public function getSize() { - - return strlen($this->contents); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5($this->contents) . '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return $this->mimeType; - - } - -} - -?> diff --git a/3rdparty/Sabre/DAV/StringUtil.php b/3rdparty/Sabre/DAV/StringUtil.php deleted file mode 100644 index 440cf6866ca..00000000000 --- a/3rdparty/Sabre/DAV/StringUtil.php +++ /dev/null @@ -1,91 +0,0 @@ -dataDir = $dataDir; - - } - - /** - * Initialize the plugin - * - * This is called automatically be the Server class after this plugin is - * added with Sabre_DAV_Server::addPlugin() - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod')); - $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile')); - - } - - /** - * This method is called before any HTTP method handler - * - * This method intercepts any GET, DELETE, PUT and PROPFIND calls to - * filenames that are known to match the 'temporary file' regex. - * - * @param string $method - * @return bool - */ - public function beforeMethod($method, $uri) { - - if (!$tempLocation = $this->isTempFile($uri)) - return true; - - switch($method) { - case 'GET' : - return $this->httpGet($tempLocation); - case 'PUT' : - return $this->httpPut($tempLocation); - case 'PROPFIND' : - return $this->httpPropfind($tempLocation, $uri); - case 'DELETE' : - return $this->httpDelete($tempLocation); - } - return true; - - } - - /** - * This method is invoked if some subsystem creates a new file. - * - * This is used to deal with HTTP LOCK requests which create a new - * file. - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function beforeCreateFile($uri,$data) { - - if ($tempPath = $this->isTempFile($uri)) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - file_put_contents($tempPath,$data); - return false; - } - return true; - - } - - /** - * This method will check if the url matches the temporary file pattern - * if it does, it will return an path based on $this->dataDir for the - * temporary file storage. - * - * @param string $path - * @return boolean|string - */ - protected function isTempFile($path) { - - // We're only interested in the basename. - list(, $tempPath) = Sabre_DAV_URLUtil::splitPath($path); - - foreach($this->temporaryFilePatterns as $tempFile) { - - if (preg_match($tempFile,$tempPath)) { - return $this->dataDir . '/sabredav_' . md5($path) . '.tempfile'; - } - - } - - return false; - - } - - - /** - * This method handles the GET method for temporary files. - * If the file doesn't exist, it will return false which will kick in - * the regular system for the GET method. - * - * @param string $tempLocation - * @return bool - */ - public function httpGet($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('Content-Type','application/octet-stream'); - $hR->setHeader('Content-Length',filesize($tempLocation)); - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(200); - $hR->sendBody(fopen($tempLocation,'r')); - return false; - - } - - /** - * This method handles the PUT method. - * - * @param string $tempLocation - * @return bool - */ - public function httpPut($tempLocation) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - - $newFile = !file_exists($tempLocation); - - if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) { - throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); - } - - file_put_contents($tempLocation,$this->server->httpRequest->getBody()); - $hR->sendStatus($newFile?201:200); - return false; - - } - - /** - * This method handles the DELETE method. - * - * If the file didn't exist, it will return false, which will make the - * standard HTTP DELETE handler kick in. - * - * @param string $tempLocation - * @return bool - */ - public function httpDelete($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - unlink($tempLocation); - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(204); - return false; - - } - - /** - * This method handles the PROPFIND method. - * - * It's a very lazy method, it won't bother checking the request body - * for which properties were requested, and just sends back a default - * set of properties. - * - * @param string $tempLocation - * @return void - */ - public function httpPropfind($tempLocation, $uri) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(207); - $hR->setHeader('Content-Type','application/xml; charset=utf-8'); - - $requestedProps = $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true)); - - $properties = array( - 'href' => $uri, - 200 => array( - '{DAV:}getlastmodified' => new Sabre_DAV_Property_GetLastModified(filemtime($tempLocation)), - '{DAV:}getcontentlength' => filesize($tempLocation), - '{DAV:}resourcetype' => new Sabre_DAV_Property_ResourceType(null), - '{'.Sabre_DAV_Server::NS_SABREDAV.'}tempFile' => true, - - ), - ); - - $data = $this->server->generateMultiStatus(array($properties)); - $hR->sendBody($data); - return false; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Tree.php b/3rdparty/Sabre/DAV/Tree.php deleted file mode 100644 index 98e6f62c9e5..00000000000 --- a/3rdparty/Sabre/DAV/Tree.php +++ /dev/null @@ -1,192 +0,0 @@ -getNodeForPath($path); - return true; - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Copies a file from path to another - * - * @param string $sourcePath The source location - * @param string $destinationPath The full destination path - * @return void - */ - public function copy($sourcePath, $destinationPath) { - - $sourceNode = $this->getNodeForPath($sourcePath); - - // grab the dirname and basename components - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - $destinationParent = $this->getNodeForPath($destinationDir); - $this->copyNode($sourceNode,$destinationParent,$destinationName); - - $this->markDirty($destinationDir); - - } - - /** - * Moves a file from one location to another - * - * @param string $sourcePath The path to the file which should be moved - * @param string $destinationPath The full destination path, so not just the destination parent node - * @return int - */ - public function move($sourcePath, $destinationPath) { - - list($sourceDir, $sourceName) = Sabre_DAV_URLUtil::splitPath($sourcePath); - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - if ($sourceDir===$destinationDir) { - $renameable = $this->getNodeForPath($sourcePath); - $renameable->setName($destinationName); - } else { - $this->copy($sourcePath,$destinationPath); - $this->getNodeForPath($sourcePath)->delete(); - } - $this->markDirty($sourceDir); - $this->markDirty($destinationDir); - - } - - /** - * Deletes a node from the tree - * - * @param string $path - * @return void - */ - public function delete($path) { - - $node = $this->getNodeForPath($path); - $node->delete(); - - list($parent) = Sabre_DAV_URLUtil::splitPath($path); - $this->markDirty($parent); - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - return $node->getChildren(); - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - - } - - /** - * copyNode - * - * @param Sabre_DAV_INode $source - * @param Sabre_DAV_ICollection $destination - * @return void - */ - protected function copyNode(Sabre_DAV_INode $source,Sabre_DAV_ICollection $destinationParent,$destinationName = null) { - - if (!$destinationName) $destinationName = $source->getName(); - - if ($source instanceof Sabre_DAV_IFile) { - - $data = $source->get(); - - // If the body was a string, we need to convert it to a stream - if (is_string($data)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$data); - rewind($stream); - $data = $stream; - } - $destinationParent->createFile($destinationName,$data); - $destination = $destinationParent->getChild($destinationName); - - } elseif ($source instanceof Sabre_DAV_ICollection) { - - $destinationParent->createDirectory($destinationName); - - $destination = $destinationParent->getChild($destinationName); - foreach($source->getChildren() as $child) { - - $this->copyNode($child,$destination); - - } - - } - if ($source instanceof Sabre_DAV_IProperties && $destination instanceof Sabre_DAV_IProperties) { - - $props = $source->getProperties(array()); - $destination->updateProperties($props); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Tree/Filesystem.php b/3rdparty/Sabre/DAV/Tree/Filesystem.php deleted file mode 100644 index 5c611047e07..00000000000 --- a/3rdparty/Sabre/DAV/Tree/Filesystem.php +++ /dev/null @@ -1,124 +0,0 @@ -basePath = $basePath; - - } - - /** - * Returns a new node for the given path - * - * @param string $path - * @return void - */ - public function getNodeForPath($path) { - - $realPath = $this->getRealPath($path); - if (!file_exists($realPath)) throw new Sabre_DAV_Exception_FileNotFound('File at location ' . $realPath . ' not found'); - if (is_dir($realPath)) { - return new Sabre_DAV_FS_Directory($path); - } else { - return new Sabre_DAV_FS_File($path); - } - - } - - /** - * Returns the real filesystem path for a webdav url. - * - * @param string $publicPath - * @return string - */ - protected function getRealPath($publicPath) { - - return rtrim($this->basePath,'/') . '/' . trim($publicPath,'/'); - - } - - /** - * Copies a file or directory. - * - * This method must work recursively and delete the destination - * if it exists - * - * @param string $source - * @param string $destination - * @return void - */ - public function copy($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - $this->realCopy($source,$destination); - - } - - /** - * Used by self::copy - * - * @param string $source - * @param string $destination - * @return void - */ - protected function realCopy($source,$destination) { - - if (is_file($source)) { - copy($source,$destination); - } else { - mkdir($destination); - foreach(scandir($source) as $subnode) { - - if ($subnode=='.' || $subnode=='..') continue; - $this->realCopy($source.'/'.$subnode,$destination.'/'.$subnode); - - } - } - - } - - /** - * Moves a file or directory recursively. - * - * If the destination exists, delete it first. - * - * @param string $source - * @param string $destination - * @return void - */ - public function move($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - rename($source,$destination); - - } - -} - diff --git a/3rdparty/Sabre/DAV/URLUtil.php b/3rdparty/Sabre/DAV/URLUtil.php deleted file mode 100644 index 8f38749264b..00000000000 --- a/3rdparty/Sabre/DAV/URLUtil.php +++ /dev/null @@ -1,125 +0,0 @@ - - * will be returned as: - * {http://www.example.org}myelem - * - * This format is used throughout the SabreDAV sourcecode. - * Elements encoded with the urn:DAV namespace will - * be returned as if they were in the DAV: namespace. This is to avoid - * compatibility problems. - * - * This function will return null if a nodetype other than an Element is passed. - * - * @param DOMElement $dom - * @return string - */ - static function toClarkNotation(DOMNode $dom) { - - if ($dom->nodeType !== XML_ELEMENT_NODE) return null; - - // Mapping back to the real namespace, in case it was dav - if ($dom->namespaceURI=='urn:DAV') $ns = 'DAV:'; else $ns = $dom->namespaceURI; - - // Mapping to clark notation - return '{' . $ns . '}' . $dom->localName; - - } - - /** - * Parses a clark-notation string, and returns the namespace and element - * name components. - * - * If the string was invalid, it will throw an InvalidArgumentException. - * - * @param string $str - * @throws InvalidArgumentException - * @return array - */ - static function parseClarkNotation($str) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$str,$matches)) { - throw new InvalidArgumentException('\'' . $str . '\' is not a valid clark-notation formatted string'); - } - - return array( - $matches[1], - $matches[2] - ); - - } - - /** - * This method takes an XML document (as string) and converts all instances of the - * DAV: namespace to urn:DAV - * - * This is unfortunately needed, because the DAV: namespace violates the xml namespaces - * spec, and causes the DOM to throw errors - */ - static function convertDAVNamespace($xmlDocument) { - - // This is used to map the DAV: namespace to urn:DAV. This is needed, because the DAV: - // namespace is actually a violation of the XML namespaces specification, and will cause errors - return preg_replace("/xmlns(:[A-Za-z0-9_]*)?=(\"|\')DAV:(\\2)/","xmlns\\1=\\2urn:DAV\\2",$xmlDocument); - - } - - /** - * This method provides a generic way to load a DOMDocument for WebDAV use. - * - * This method throws a Sabre_DAV_Exception_BadRequest exception for any xml errors. - * It does not preserve whitespace, and it converts the DAV: namespace to urn:DAV. - * - * @param string $xml - * @throws Sabre_DAV_Exception_BadRequest - * @return DOMDocument - */ - static function loadDOMDocument($xml) { - - if (empty($xml)) - throw new Sabre_DAV_Exception_BadRequest('Empty XML document sent'); - - // The BitKinex client sends xml documents as UTF-16. PHP 5.3.1 (and presumably lower) - // does not support this, so we must intercept this and convert to UTF-8. - if (substr($xml,0,12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { - - // Note: the preceeding byte sequence is "]*)encoding="UTF-16"([^>]*)>|u','',$xml); - - } - - // Retaining old error setting - $oldErrorSetting = libxml_use_internal_errors(true); - - // Clearing any previous errors - libxml_clear_errors(); - - $dom = new DOMDocument(); - $dom->loadXML(self::convertDAVNamespace($xml),LIBXML_NOWARNING | LIBXML_NOERROR); - - // We don't generally care about any whitespace - $dom->preserveWhiteSpace = false; - - if ($error = libxml_get_last_error()) { - libxml_clear_errors(); - throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: ' . $error->message . ', errorcode: ' . $error->code . ', line: ' . $error->line . ')'); - } - - // Restoring old mechanism for error handling - if ($oldErrorSetting===false) libxml_use_internal_errors(false); - - return $dom; - - } - - /** - * Parses all WebDAV properties out of a DOM Element - * - * Generally WebDAV properties are encloded in {DAV:}prop elements. This - * method helps by going through all these and pulling out the actual - * propertynames, making them array keys and making the property values, - * well.. the array values. - * - * If no value was given (self-closing element) null will be used as the - * value. This is used in for example PROPFIND requests. - * - * Complex values are supported through the propertyMap argument. The - * propertyMap should have the clark-notation properties as it's keys, and - * classnames as values. - * - * When any of these properties are found, the unserialize() method will be - * (statically) called. The result of this method is used as the value. - * - * @param DOMElement $parentNode - * @param array $propertyMap - * @return array - */ - static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) { - - $propList = array(); - foreach($parentNode->childNodes as $propNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($propNode)!=='{DAV:}prop') continue; - - foreach($propNode->childNodes as $propNodeData) { - - /* If there are no elements in here, we actually get 1 text node, this special case is dedicated to netdrive */ - if ($propNodeData->nodeType != XML_ELEMENT_NODE) continue; - - $propertyName = Sabre_DAV_XMLUtil::toClarkNotation($propNodeData); - if (isset($propertyMap[$propertyName])) { - $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName],'unserialize'),$propNodeData); - } else { - $propList[$propertyName] = $propNodeData->textContent; - } - } - - - } - return $propList; - - } - -} diff --git a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php b/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php deleted file mode 100644 index a361e054610..00000000000 --- a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php +++ /dev/null @@ -1,121 +0,0 @@ -principalPrefix = $principalPrefix; - $this->principalBackend = $principalBackend; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principalInfo - * @return Sabre_DAVACL_IPrincipal - */ - abstract function getChildForPrincipal(array $principalInfo); - - /** - * Returns the name of this collection. - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); - return $name; - - } - - /** - * Return the list of users - * - * @return void - */ - public function getChildren() { - - if ($this->disableListing) - throw new Sabre_DAV_Exception_MethodNotAllowed('Listing members of this collection is disabled'); - - $children = array(); - foreach($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { - - $children[] = $this->getChildForPrincipal($principalInfo); - - - } - return $children; - - } - - /** - * Returns a child object, by its name. - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_IPrincipal - */ - public function getChild($name) { - - $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/' . $name); - if (!$principalInfo) throw new Sabre_DAV_Exception_FileNotFound('Principal with name ' . $name . ' not found'); - return $this->getChildForPrincipal($principalInfo); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php b/3rdparty/Sabre/DAVACL/Exception/AceConflict.php deleted file mode 100644 index d10aeb4345c..00000000000 --- a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-ace-conflict'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php b/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php deleted file mode 100644 index 024ab6641f3..00000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php +++ /dev/null @@ -1,80 +0,0 @@ -uri = $uri; - $this->privileges = $privileges; - - } - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}need-privileges element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:need-privileges'); - $errorNode->appendChild($np); - - foreach($this->privileges as $privilege) { - - $resource = $doc->createElementNS('DAV:','d:resource'); - $np->appendChild($resource); - - $resource->appendChild($doc->createElementNS('DAV:','d:href',$server->getBaseUri() . $this->uri)); - - $priv = $doc->createElementNS('DAV:','d:privilege'); - $resource->appendChild($priv); - - preg_match('/^{([^}]*)}(.*)$/',$privilege,$privilegeParts); - $priv->appendChild($doc->createElementNS($privilegeParts[1],'d:' . $privilegeParts[2])); - - - } - - } - -} - diff --git a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php b/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php deleted file mode 100644 index 60f49ebff4a..00000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-abstract'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php b/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php deleted file mode 100644 index e056dc9e4f7..00000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:recognized-principal'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php b/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php deleted file mode 100644 index 27db7cdd7dd..00000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php +++ /dev/null @@ -1,34 +0,0 @@ -ownerDocument; - - $np = $doc->createElementNS('DAV:','d:not-supported-privilege'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/IACL.php b/3rdparty/Sabre/DAVACL/IACL.php deleted file mode 100644 index 506be4248d7..00000000000 --- a/3rdparty/Sabre/DAVACL/IACL.php +++ /dev/null @@ -1,58 +0,0 @@ -getCurrentUserPrivilegeSet($uri); - - if (is_null($acl)) { - if ($this->allowAccessToNodesWithoutACL) { - return true; - } else { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$privileges); - else - return false; - - } - } - - $failed = array(); - foreach($privileges as $priv) { - - if (!in_array($priv, $acl)) { - $failed[] = $priv; - } - - } - - if ($failed) { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$failed); - else - return false; - } - return true; - - } - - /** - * Returns the standard users' principal. - * - * This is one authorative principal url for the current user. - * This method will return null if the user wasn't logged in. - * - * @return string|null - */ - public function getCurrentUserPrincipal() { - - $authPlugin = $this->server->getPlugin('auth'); - if (is_null($authPlugin)) return null; - - $userName = $authPlugin->getCurrentUser(); - if (!$userName) return null; - - return $this->defaultUsernamePath . '/' . $userName; - - } - - /** - * Returns a list of principals that's associated to the current - * user, either directly or through group membership. - * - * @return array - */ - public function getCurrentUserPrincipals() { - - $currentUser = $this->getCurrentUserPrincipal(); - - if (is_null($currentUser)) return array(); - - $check = array($currentUser); - $principals = array($currentUser); - - while(count($check)) { - - $principal = array_shift($check); - - $node = $this->server->tree->getNodeForPath($principal); - if ($node instanceof Sabre_DAVACL_IPrincipal) { - foreach($node->getGroupMembership() as $groupMember) { - - if (!in_array($groupMember, $principals)) { - - $check[] = $groupMember; - $principals[] = $groupMember; - - } - - } - - } - - } - - return $principals; - - } - - /** - * Returns the supported privilege structure for this ACL plugin. - * - * See RFC3744 for more details. Currently we default on a simple, - * standard structure. - * - * @return array - */ - public function getSupportedPrivilegeSet() { - - return array( - 'privilege' => '{DAV:}all', - 'abstract' => true, - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}read-current-user-privilege-set', - 'abstract' => true, - ), - ), - ), // {DAV:}read - array( - 'privilege' => '{DAV:}write', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}write-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-properties', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-content', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}bind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unbind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unlock', - 'abstract' => true, - ), - ), - ), // {DAV:}write - ), - ); // {DAV:}all - - } - - /** - * Returns the supported privilege set as a flat list - * - * This is much easier to parse. - * - * The returned list will be index by privilege name. - * The value is a struct containing the following properties: - * - aggregates - * - abstract - * - concrete - * - * @return array - */ - final public function getFlatPrivilegeSet() { - - $privs = $this->getSupportedPrivilegeSet(); - - $flat = array(); - $this->getFPSTraverse($privs, null, $flat); - - return $flat; - - } - - /** - * Traverses the privilege set tree for reordering - * - * This function is solely used by getFlatPrivilegeSet, and would have been - * a closure if it wasn't for the fact I need to support PHP 5.2. - * - * @return void - */ - final private function getFPSTraverse($priv, $concrete, &$flat) { - - $myPriv = array( - 'privilege' => $priv['privilege'], - 'abstract' => isset($priv['abstract']) && $priv['abstract'], - 'aggregates' => array(), - 'concrete' => isset($priv['abstract']) && $priv['abstract']?$concrete:$priv['privilege'], - ); - - if (isset($priv['aggregates'])) - foreach($priv['aggregates'] as $subPriv) $myPriv['aggregates'][] = $subPriv['privilege']; - - $flat[$priv['privilege']] = $myPriv; - - if (isset($priv['aggregates'])) { - - foreach($priv['aggregates'] as $subPriv) { - - $this->getFPSTraverse($subPriv, $myPriv['concrete'], $flat); - - } - - } - - } - - /** - * Returns the full ACL list. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getACL($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - if ($node instanceof Sabre_DAVACL_IACL) { - return $node->getACL(); - } - return null; - - } - - /** - * Returns a list of privileges the current user has - * on a particular node. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getCurrentUserPrivilegeSet($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - - $acl = $this->getACL($node); - if (is_null($acl)) return null; - - $principals = $this->getCurrentUserPrincipals(); - - $collected = array(); - - foreach($acl as $ace) { - - if (in_array($ace['principal'], $principals)) { - $collected[] = $ace; - } - - } - - // Now we deduct all aggregated privileges. - $flat = $this->getFlatPrivilegeSet(); - - $collected2 = array(); - foreach($collected as $privilege) { - - $collected2[] = $privilege['privilege']; - foreach($flat[$privilege['privilege']]['aggregates'] as $subPriv) { - if (!in_array($subPriv, $collected2)) - $collected2[] = $subPriv; - } - - } - - return $collected2; - - } - - /** - * Sets up the plugin - * - * This method is automatically called by the server class. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->subscribeEvent('beforeMethod', array($this,'beforeMethod'),20); - $server->subscribeEvent('beforeBind', array($this,'beforeBind'),20); - $server->subscribeEvent('beforeUnbind', array($this,'beforeUnbind'),20); - $server->subscribeEvent('updateProperties',array($this,'updateProperties')); - $server->subscribeEvent('beforeUnlock', array($this,'beforeUnlock'),20); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); - - array_push($server->protectedProperties, - '{DAV:}alternate-URI-set', - '{DAV:}principal-URL', - '{DAV:}group-membership', - '{DAV:}principal-collection-set', - '{DAV:}current-user-principal', - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - '{DAV:}owner', - '{DAV:}group' - ); - - // Automatically mapping nodes implementing IPrincipal to the - // {DAV:}principal resourcetype. - $server->resourceTypeMapping['Sabre_DAVACL_IPrincipal'] = '{DAV:}principal'; - - // Mapping the group-member-set property to the HrefList property - // class. - $server->propertyMap['{DAV:}group-member-set'] = 'Sabre_DAV_Property_HrefList'; - - } - - - /* {{{ Event handlers */ - - /** - * Triggered before any method is handled - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - $exists = $this->server->tree->nodeExists($uri); - - // If the node doesn't exists, none of these checks apply - if (!$exists) return; - - switch($method) { - - case 'GET' : - case 'HEAD' : - case 'OPTIONS' : - // For these 3 we only need to know if the node is readable. - $this->checkPrivileges($uri,'{DAV:}read'); - break; - - case 'PUT' : - case 'LOCK' : - case 'UNLOCK' : - // This method requires the write-content priv if the node - // already exists, and bind on the parent if the node is being - // created. - // The bind privilege is handled in the beforeBind event. - $this->checkPrivileges($uri,'{DAV:}write-content'); - break; - - - case 'PROPPATCH' : - $this->checkPrivileges($uri,'{DAV:}write-properties'); - break; - - case 'ACL' : - $this->checkPrivileges($uri,'{DAV:}write-acl'); - break; - - case 'COPY' : - case 'MOVE' : - // Copy requires read privileges on the entire source tree. - // If the target exists write-content normally needs to be - // checked, however, we're deleting the node beforehand and - // creating a new one after, so this is handled by the - // beforeUnbind event. - // - // The creation of the new node is handled by the beforeBind - // event. - // - // If MOVE is used beforeUnbind will also be used to check if - // the sourcenode can be deleted. - $this->checkPrivileges($uri,'{DAV:}read',self::R_RECURSIVE); - - break; - - } - - } - - /** - * Triggered before a new node is created. - * - * This allows us to check permissions for any operation that creates a - * new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. - * - * @param string $uri - * @return void - */ - public function beforeBind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}bind'); - - } - - /** - * Triggered before a node is deleted - * - * This allows us to check permissions for any operation that will delete - * an existing node. - * - * @param string $uri - * @return void - */ - public function beforeUnbind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}unbind',self::R_RECURSIVEPARENTS); - - } - - /** - * Triggered before a node is unlocked. - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lock - * @TODO: not yet implemented - * @return void - */ - public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) { - - - } - - /** - * Triggered before properties are looked up in specific nodes. - * - * @param string $uri - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @TODO really should be broken into multiple methods, or even a class. - * @return void - */ - public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - // Checking the read permission - if (!$this->checkPrivileges($uri,'{DAV:}read',self::R_PARENT,false)) { - - // User is not allowed to read properties - if ($this->hideNodesFromListings) { - return false; - } - - // Marking all requested properties as '403'. - foreach($requestedProperties as $key=>$requestedProperty) { - unset($requestedProperties[$key]); - $returnedProperties[403][$requestedProperty] = null; - } - return; - - } - - /* Adding principal properties */ - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - if (false !== ($index = array_search('{DAV:}alternate-URI-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}alternate-URI-set'] = new Sabre_DAV_Property_HrefList($node->getAlternateUriSet()); - - } - if (false !== ($index = array_search('{DAV:}principal-URL', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl() . '/'); - - } - if (false !== ($index = array_search('{DAV:}group-member-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-member-set'] = new Sabre_DAV_Property_HrefList($node->getGroupMemberSet()); - - } - if (false !== ($index = array_search('{DAV:}group-membership', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-membership'] = new Sabre_DAV_Property_HrefList($node->getGroupMembership()); - - } - - if (false !== ($index = array_search('{DAV:}displayname', $requestedProperties))) { - - $returnedProperties[200]['{DAV:}displayname'] = $node->getDisplayName(); - - } - - } - if (false !== ($index = array_search('{DAV:}principal-collection-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $val = $this->principalCollectionSet; - // Ensuring all collections end with a slash - foreach($val as $k=>$v) $val[$k] = $v . '/'; - $returnedProperties[200]['{DAV:}principal-collection-set'] = new Sabre_DAV_Property_HrefList($val); - - } - if (false !== ($index = array_search('{DAV:}current-user-principal', $requestedProperties))) { - - unset($requestedProperties[$index]); - if ($url = $this->getCurrentUserPrincipal()) { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url . '/'); - } else { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); - } - - } - if (false !== ($index = array_search('{DAV:}supported-privilege-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}supported-privilege-set'] = new Sabre_DAVACL_Property_SupportedPrivilegeSet($this->getSupportedPrivilegeSet()); - - } - if (false !== ($index = array_search('{DAV:}current-user-privilege-set', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) { - $returnedProperties[403]['{DAV:}current-user-privilege-set'] = null; - unset($requestedProperties[$index]); - } else { - $val = $this->getCurrentUserPrivilegeSet($node); - if (!is_null($val)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}current-user-privilege-set'] = new Sabre_DAVACL_Property_CurrentUserPrivilegeSet($val); - } - } - - } - - /* The ACL property contains all the permissions */ - if (false !== ($index = array_search('{DAV:}acl', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-acl', self::R_PARENT, false)) { - - unset($requestedProperties[$index]); - $returnedProperties[403]['{DAV:}acl'] = null; - - } else { - - $acl = $this->getACL($node); - if (!is_null($acl)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}acl'] = new Sabre_DAVACL_Property_Acl($this->getACL($node)); - } - - } - - } - - } - - /** - * This method intercepts PROPPATCH methods and make sure the - * group-member-set is updated correctly. - * - * @param array $propertyDelta - * @param array $result - * @param Sabre_DAV_INode $node - * @return void - */ - public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) { - - if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) - return; - - if (is_null($propertyDelta['{DAV:}group-member-set'])) { - $memberSet = array(); - } elseif ($propertyDelta['{DAV:}group-member-set'] instanceof Sabre_DAV_Property_HrefList) { - $memberSet = $propertyDelta['{DAV:}group-member-set']->getHrefs(); - } else { - throw new Sabre_DAV_Exception('The group-member-set property MUST be an instance of Sabre_DAV_Property_HrefList or null'); - } - - if (!($node instanceof Sabre_DAVACL_IPrincipal)) { - $result[403]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - // Returning false will stop the updateProperties process - return false; - } - - $node->setGroupMemberSet($memberSet); - - $result[200]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - } - - /** - * This method handels HTTP REPORT requests - * - * @param string $reportName - * @param DOMNode $dom - * @return void - */ - public function report($reportName, $dom) { - - switch($reportName) { - - case '{DAV:}principal-property-search' : - $this->principalPropertySearchReport($dom); - return false; - case '{DAV:}principal-search-property-set' : - $this->principalSearchPropertySetReport($dom); - return false; - case '{DAV:}expand-property' : - $this->expandPropertyReport($dom); - return false; - - } - - } - - /** - * This event is triggered for any HTTP method that is not known by the - * webserver. - * - * @param string $method - * @param string $uri - * @return void - */ - public function unknownMethod($method, $uri) { - - if ($method!=='ACL') return; - - $this->httpACL($uri); - return false; - - } - - /** - * This method is responsible for handling the 'ACL' event. - * - * @param string $uri - * @return void - */ - public function httpACL($uri) { - - $body = $this->server->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newAcl = - Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild) - ->getPrivileges(); - - // Normalizing urls - foreach($newAcl as $k=>$newAce) { - $newAcl[$k]['principal'] = $this->server->calculateUri($newAce['principal']); - } - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_DAVACL_IACL)) { - throw new Sabre_DAV_Exception_MethodNotAllowed('This node does not support the ACL method'); - } - - $oldAcl = $this->getACL($node); - - $supportedPrivileges = $this->getFlatPrivilegeSet(); - - /* Checking if protected principals from the existing principal set are - not overwritten. */ - foreach($oldAcl as $k=>$oldAce) { - - if (!isset($oldAce['protected']) || !$oldAce['protected']) continue; - - $found = false; - foreach($newAcl as $newAce) { - if ( - $newAce['privilege'] === $oldAce['privilege'] && - $newAce['principal'] === $oldAce['principal'] && - $newAce['protected'] - ) - $found = true; - } - - if (!$found) - throw new Sabre_DAVACL_Exception_AceConflict('This resource contained a protected {DAV:}ace, but this privilege did not occur in the ACL request'); - - } - - foreach($newAcl as $k=>$newAce) { - - // Do we recognize the privilege - if (!isset($supportedPrivileges[$newAce['privilege']])) { - throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified (' . $newAce['privilege'] . ') is not recognized by this server'); - } - - if ($supportedPrivileges[$newAce['privilege']]['abstract']) { - throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified (' . $newAce['privilege'] . ') is an abstract privilege'); - } - - // Looking up the principal - try { - $principal = $this->server->tree->getNodeForPath($newAce['principal']); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal (' . $newAce['principal'] . ') does not exist'); - } - if (!($principal instanceof Sabre_DAVACL_IPrincipal)) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri (' . $newAce['principal'] . ') is not a principal'); - } - - } - $node->setACL($newAcl); - - } - - /* }}} */ - - /* Reports {{{ */ - - /** - * The expand-property report is defined in RFC3253 section 3-8. - * - * This report is very similar to a standard PROPFIND. The difference is - * that it has the additional ability to look at properties containing a - * {DAV:}href element, follow that property and grab additional elements - * there. - * - * Other rfc's, such as ACL rely on this report, so it made sense to put - * it in this plugin. - * - * @param DOMElement $dom - * @return void - */ - protected function expandPropertyReport($dom) { - - $requestedProperties = $this->parseExpandPropertyReportRequest($dom->firstChild->firstChild); - $depth = $this->server->getHTTPDepth(0); - $requestUri = $this->server->getRequestUri(); - - $result = $this->expandProperties($requestUri,$requestedProperties,$depth); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($result as $response) { - $response->serialize($this->server, $multiStatus); - } - - $xml = $dom->saveXML(); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * This method is used by expandPropertyReport to parse - * out the entire HTTP request. - * - * @param DOMElement $node - * @return array - */ - protected function parseExpandPropertyReportRequest($node) { - - $requestedProperties = array(); - do { - - if (Sabre_DAV_XMLUtil::toClarkNotation($node)!=='{DAV:}property') continue; - - if ($node->firstChild) { - - $children = $this->parseExpandPropertyReportRequest($node->firstChild); - - } else { - - $children = array(); - - } - - $namespace = $node->getAttribute('namespace'); - if (!$namespace) $namespace = 'DAV:'; - - $propName = '{'.$namespace.'}' . $node->getAttribute('name'); - $requestedProperties[$propName] = $children; - - } while ($node = $node->nextSibling); - - return $requestedProperties; - - } - - /** - * This method expands all the properties and returns - * a list with property values - * - * @param array $path - * @param array $requestedProperties the list of required properties - * @param array $depth - */ - protected function expandProperties($path,array $requestedProperties,$depth) { - - $foundProperties = $this->server->getPropertiesForPath($path,array_keys($requestedProperties),$depth); - - $result = array(); - - foreach($foundProperties as $node) { - - foreach($requestedProperties as $propertyName=>$childRequestedProperties) { - - // We're only traversing if sub-properties were requested - if(count($childRequestedProperties)===0) continue; - - // We only have to do the expansion if the property was found - // and it contains an href element. - if (!array_key_exists($propertyName,$node[200])) continue; - - if ($node[200][$propertyName] instanceof Sabre_DAV_Property_IHref) { - $hrefs = array($node[200][$propertyName]->getHref()); - } elseif ($node[200][$propertyName] instanceof Sabre_DAV_Property_HrefList) { - $hrefs = $node[200][$propertyName]->getHrefs(); - } - - $childProps = array(); - foreach($hrefs as $href) { - $childProps = array_merge($childProps, $this->expandProperties($href,$childRequestedProperties,0)); - } - $node[200][$propertyName] = new Sabre_DAV_Property_ResponseList($childProps); - - } - $result[] = new Sabre_DAV_Property_Response($path, $node); - - } - - return $result; - - } - - /** - * principalSearchPropertySetReport - * - * This method responsible for handing the - * {DAV:}principal-search-property-set report. This report returns a list - * of properties the client may search on, using the - * {DAV:}principal-property-search report. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalSearchPropertySetReport(DOMDocument $dom) { - - $searchProperties = array( - '{DAV:}displayname' => 'display name' - ); - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - if ($dom->firstChild->hasChildNodes()) - throw new Sabre_DAV_Exception_BadRequest('The principal-search-property-set report element is not allowed to have child elements'); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $root = $dom->createElement('d:principal-search-property-set'); - $dom->appendChild($root); - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $root->setAttribute('xmlns:' . $prefix,$namespace); - - } - - $nsList = $this->server->xmlNamespaces; - - foreach($searchProperties as $propertyName=>$description) { - - $psp = $dom->createElement('d:principal-search-property'); - $root->appendChild($psp); - - $prop = $dom->createElement('d:prop'); - $psp->appendChild($prop); - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - $currentProperty = $dom->createElement($nsList[$propName[1]] . ':' . $propName[2]); - $prop->appendChild($currentProperty); - - $descriptionElem = $dom->createElement('d:description'); - $descriptionElem->setAttribute('xml:lang','en'); - $descriptionElem->appendChild($dom->createTextNode($description)); - $psp->appendChild($descriptionElem); - - - } - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($dom->saveXML()); - - } - - /** - * principalPropertySearchReport - * - * This method is reponsible for handing the - * {DAV:}principal-property-search report. This report can be used for - * clients to search for groups of principals, based on the value of one - * or more properties. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalPropertySearchReport(DOMDocument $dom) { - - $searchableProperties = array( - '{DAV:}displayname' => 'display name' - - ); - - list($searchProperties, $requestedProperties, $applyToPrincipalCollectionSet) = $this->parsePrincipalPropertySearchReportRequest($dom); - - $result = array(); - - if ($applyToPrincipalCollectionSet) { - $uris = array(); - } else { - $uris = array($this->server->getRequestUri()); - } - - $lookupResults = array(); - foreach($uris as $uri) { - - $p = array_keys($searchProperties); - $p[] = '{DAV:}resourcetype'; - $r = $this->server->getPropertiesForPath($uri, $p, 1); - - // The first item in the results is the parent, so we get rid of it. - array_shift($r); - $lookupResults = array_merge($lookupResults, $r); - } - - $matches = array(); - - foreach($lookupResults as $lookupResult) { - - // We're only looking for principals - if (!isset($lookupResult[200]['{DAV:}resourcetype']) || - (!($lookupResult[200]['{DAV:}resourcetype'] instanceof Sabre_DAV_Property_ResourceType)) || - !$lookupResult[200]['{DAV:}resourcetype']->is('{DAV:}principal')) continue; - - foreach($searchProperties as $searchProperty=>$searchValue) { - if (!isset($searchableProperties[$searchProperty])) { - // If a property is not 'searchable', the spec dictates - // this is not a match. - continue; - } - - if (isset($lookupResult[200][$searchProperty]) && - mb_stripos($lookupResult[200][$searchProperty], $searchValue, 0, 'UTF-8')!==false) { - $matches[] = $lookupResult['href']; - } - - } - - } - - $matchProperties = array(); - - foreach($matches as $match) { - - list($result) = $this->server->getPropertiesForPath($match, $requestedProperties, 0); - $matchProperties[] = $result; - - } - - $xml = $this->server->generateMultiStatus($matchProperties); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * parsePrincipalPropertySearchReportRequest - * - * This method parses the request body from a - * {DAV:}principal-property-search report. - * - * This method returns an array with two elements: - * 1. an array with properties to search on, and their values - * 2. a list of propertyvalues that should be returned for the request. - * - * @param DOMDocument $dom - * @return array - */ - protected function parsePrincipalPropertySearchReportRequest($dom) { - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - $searchProperties = array(); - - $applyToPrincipalCollectionSet = false; - - // Parsing the search request - foreach($dom->firstChild->childNodes as $searchNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) == '{DAV:}apply-to-principal-collection-set') - $applyToPrincipalCollectionSet = true; - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode)!=='{DAV:}property-search') - continue; - - $propertyName = null; - $propertyValue = null; - - foreach($searchNode->childNodes as $childNode) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - - case '{DAV:}prop' : - $property = Sabre_DAV_XMLUtil::parseProperties($searchNode); - reset($property); - $propertyName = key($property); - break; - - case '{DAV:}match' : - $propertyValue = $childNode->textContent; - break; - - } - - - } - - if (is_null($propertyName) || is_null($propertyValue)) - throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: ' . $propertyName . '. propertvvalue: ' . $propertyValue); - - $searchProperties[$propertyName] = $propertyValue; - - } - - return array($searchProperties, array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)), $applyToPrincipalCollectionSet); - - } - - - /* }}} */ - -} diff --git a/3rdparty/Sabre/DAVACL/Principal.php b/3rdparty/Sabre/DAVACL/Principal.php deleted file mode 100644 index 790603c900f..00000000000 --- a/3rdparty/Sabre/DAVACL/Principal.php +++ /dev/null @@ -1,263 +0,0 @@ -principalBackend = $principalBackend; - $this->principalProperties = $principalProperties; - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalProperties['uri']; - - } - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - $uris = array(); - if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { - - $uris = $this->principalProperties['{DAV:}alternate-URI-set']; - - } - - if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { - $uris[] = 'mailto:' . $this->principalProperties['{http://sabredav.org/ns}email-address']; - } - - return array_unique($uris); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->principalProperties['uri']); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMemberShip($this->principalProperties['uri']); - - } - - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $groupMembers) { - - $this->principalBackend->setGroupMemberSet($this->principalProperties['uri'], $groupMembers); - - } - - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - $uri = $this->principalProperties['uri']; - list(, $name) = Sabre_DAV_URLUtil::splitPath($uri); - - return $name; - - } - - /** - * Returns the name of the user - * - * @return void - */ - public function getDisplayName() { - - if (isset($this->principalProperties['{DAV:}displayname'])) { - return $this->principalProperties['{DAV:}displayname']; - } else { - return $this->getName(); - } - - } - - /** - * Returns a list of properties - * - * @param array $requestedProperties - * @return void - */ - public function getProperties($requestedProperties) { - - $newProperties = array(); - foreach($requestedProperties as $propName) { - - if (isset($this->principalProperties[$propName])) { - $newProperties[$propName] = $this->principalProperties[$propName]; - } - - } - - return $newProperties; - - } - - /** - * Updates this principals properties. - * - * Currently this is not supported - * - * @param array $properties - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - return false; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalProperties['uri']; - - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Updating ACLs is not allowed here'); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php b/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php deleted file mode 100644 index 55bd1903c9b..00000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php +++ /dev/null @@ -1,206 +0,0 @@ -pdo = $pdo; - $this->tableName = $tableName; - $this->groupMembersTableName = $groupMembersTableName; - - } - - - /** - * Returns a list of principals based on a prefix. - * - * This prefix will often contain something like 'principals'. You are only - * expected to return principals that are in this base path. - * - * You are expected to return at least a 'uri' for every user, you can - * return any additional properties if you wish so. Common properties are: - * {DAV:}displayname - * {http://sabredav.org/ns}email-address - This is a custom SabreDAV - * field that's actualy injected in a number of other properties. If - * you have an email address, use this property. - * - * @param string $prefixPath - * @return array - */ - public function getPrincipalsByPrefix($prefixPath) { - $result = $this->pdo->query('SELECT uri, email, displayname FROM `'. $this->tableName . '`'); - - $principals = array(); - - while($row = $result->fetch(PDO::FETCH_ASSOC)) { - - // Checking if the principal is in the prefix - list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); - if ($rowPrefix !== $prefixPath) continue; - - $principals[] = array( - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - return $principals; - - } - - /** - * Returns a specific principal, specified by it's path. - * The returned structure should be the exact same as from - * getPrincipalsByPrefix. - * - * @param string $path - * @return array - */ - public function getPrincipalByPath($path) { - - $stmt = $this->pdo->prepare('SELECT id, uri, email, displayname FROM `'.$this->tableName.'` WHERE uri = ?'); - $stmt->execute(array($path)); - - $users = array(); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) return; - - return array( - 'id' => $row['id'], - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - /** - * Returns the list of members for a group-principal - * - * @param string $principal - * @return array - */ - public function getGroupMemberSet($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Returns the list of groups a principal is a member of - * - * @param string $principal - * @return array - */ - public function getGroupMembership($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Updates the list of group members for a group principal. - * - * The principals should be passed as a list of uri's. - * - * @param string $principal - * @param array $members - * @return void - */ - public function setGroupMemberSet($principal, array $members) { - - // Grabbing the list of principal id's. - $stmt = $this->pdo->prepare('SELECT id, uri FROM `'.$this->tableName.'` WHERE uri IN (? ' . str_repeat(', ? ', count($members)) . ');'); - $stmt->execute(array_merge(array($principal), $members)); - - $memberIds = array(); - $principalId = null; - - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if ($row['uri'] == $principal) { - $principalId = $row['id']; - } else { - $memberIds[] = $row['id']; - } - } - if (!$principalId) throw new Sabre_DAV_Exception('Principal not found'); - - // Wiping out old members - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->groupMembersTableName.'` WHERE principal_id = ?;'); - $stmt->execute(array($principalId)); - - foreach($memberIds as $memberId) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->groupMembersTableName.'` (principal_id, member_id) VALUES (?, ?);'); - $stmt->execute(array($principalId, $memberId)); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalCollection.php b/3rdparty/Sabre/DAVACL/PrincipalCollection.php deleted file mode 100644 index 4d22bf8aa75..00000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalCollection.php +++ /dev/null @@ -1,35 +0,0 @@ -principalBackend, $principal); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Acl.php b/3rdparty/Sabre/DAVACL/Property/Acl.php deleted file mode 100644 index e41e7411310..00000000000 --- a/3rdparty/Sabre/DAVACL/Property/Acl.php +++ /dev/null @@ -1,186 +0,0 @@ -privileges = $privileges; - $this->prefixBaseUrl = $prefixBaseUrl; - - } - - /** - * Returns the list of privileges for this property - * - * @return array - */ - public function getPrivileges() { - - return $this->privileges; - - } - - /** - * Serializes the property into a DOMElement - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $ace) { - - $this->serializeAce($doc, $node, $ace, $server); - - } - - } - - /** - * Unserializes the {DAV:}acl xml element. - * - * @param DOMElement $dom - * @return Sabre_DAVACL_Property_Acl - */ - static public function unserialize(DOMElement $dom) { - - $privileges = array(); - $xaces = $dom->getElementsByTagNameNS('urn:DAV','ace'); - for($ii=0; $ii < $xaces->length; $ii++) { - - $xace = $xaces->item($ii); - $principal = $xace->getElementsByTagNameNS('urn:DAV','principal'); - if ($principal->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Each {DAV:}ace element must have one {DAV:}principal element'); - } - $principal = Sabre_DAVACL_Property_Principal::unserialize($principal->item(0)); - - if ($principal->getType()!==Sabre_DAVACL_Property_Principal::HREF) { - throw new Sabre_DAV_Exception_NotImplemented('Currently only uri based principals are support, {DAV:}all, {DAV:}unauthenticated and {DAV:}authenticated are not implemented yet'); - } - - $principal = $principal->getHref(); - $protected = false; - - if ($xace->getElementsByTagNameNS('urn:DAV','protected')->length > 0) { - $protected = true; - } - - $grants = $xace->getElementsByTagNameNS('urn:DAV','grant'); - if ($grants->length < 1) { - throw new Sabre_DAV_Exception_NotImplemented('Every {DAV:}ace element must have a {DAV:}grant element. {DAV:}deny is not yet supported'); - } - $grant = $grants->item(0); - - $xprivs = $grant->getElementsByTagNameNS('urn:DAV','privilege'); - for($jj=0; $jj<$xprivs->length; $jj++) { - - $xpriv = $xprivs->item($jj); - - $privilegeName = null; - - for ($kk=0;$kk<$xpriv->childNodes->length;$kk++) { - - $childNode = $xpriv->childNodes->item($kk); - if ($t = Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - $privilegeName = $t; - break; - } - } - if (is_null($privilegeName)) { - throw new Sabre_DAV_Exception_BadRequest('{DAV:}privilege elements must have a privilege element contained within them.'); - } - - $privileges[] = array( - 'principal' => $principal, - 'protected' => $protected, - 'privilege' => $privilegeName, - ); - - } - - } - - return new self($privileges); - - } - - /** - * Serializes a single access control entry. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $ace - * @param Sabre_DAV_Server $server - * @return void - */ - private function serializeAce($doc,$node,$ace, $server) { - - $xace = $doc->createElementNS('DAV:','d:ace'); - $node->appendChild($xace); - - $principal = $doc->createElementNS('DAV:','d:principal'); - $xace->appendChild($principal); - $principal->appendChild($doc->createElementNS('DAV:','d:href',($this->prefixBaseUrl?$server->getBaseUri():'') . $ace['principal'] . '/')); - - $grant = $doc->createElementNS('DAV:','d:grant'); - $xace->appendChild($grant); - - $privParts = null; - - preg_match('/^{([^}]*)}(.*)$/',$ace['privilege'],$privParts); - - $xprivilege = $doc->createElementNS('DAV:','d:privilege'); - $grant->appendChild($xprivilege); - - $xprivilege->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($ace['protected']) && $ace['protected']) - $xace->appendChild($doc->createElement('d:protected')); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php deleted file mode 100644 index 72274597b31..00000000000 --- a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php +++ /dev/null @@ -1,75 +0,0 @@ -privileges = $privileges; - - } - - /** - * Serializes the property in the DOM - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $privName) { - - $this->serializePriv($doc,$node,$privName); - - } - - } - - /** - * Serializes one privilege - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param string $privName - * @return void - */ - protected function serializePriv($doc,$node,$privName) { - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $node->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privName,$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Principal.php b/3rdparty/Sabre/DAVACL/Property/Principal.php deleted file mode 100644 index dad9a3550fb..00000000000 --- a/3rdparty/Sabre/DAVACL/Property/Principal.php +++ /dev/null @@ -1,154 +0,0 @@ -type = $type; - - if ($type===self::HREF && is_null($href)) { - throw new Sabre_DAV_Exception('The href argument must be specified for the HREF principal type.'); - } - $this->href = $href; - - } - - /** - * Returns the principal type - * - * @return int - */ - public function getType() { - - return $this->type; - - } - - /** - * Returns the principal uri. - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes the property into a DOMElement. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $node) { - - $prefix = $server->xmlNamespaces['DAV:']; - switch($this->type) { - - case self::UNAUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':unauthenticated') - ); - break; - case self::AUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':authenticated') - ); - break; - case self::HREF : - $href = $node->ownerDocument->createElement($prefix . ':href'); - $href->nodeValue = $server->getBaseUri() . $this->href; - $node->appendChild($href); - break; - - } - - } - - /** - * Deserializes a DOM element into a property object. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Principal - */ - static public function unserialize(DOMElement $dom) { - - $parent = $dom->firstChild; - while(!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - $parent = $parent->nextSibling; - } - - switch(Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - - case '{DAV:}unauthenticated' : - return new self(self::UNAUTHENTICATED); - case '{DAV:}authenticated' : - return new self(self::AUTHENTICATED); - case '{DAV:}href': - return new self(self::HREF, $parent->textContent); - default : - throw new Sabre_DAV_Exception_BadRequest('Unexpected element (' . Sabre_DAV_XMLUtil::toClarkNotation($parent) . '). Could not deserialize'); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php deleted file mode 100644 index 93c3895035d..00000000000 --- a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php +++ /dev/null @@ -1,92 +0,0 @@ -privileges = $privileges; - - } - - /** - * Serializes the property into a domdocument. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - $this->serializePriv($doc, $node, $this->privileges); - - } - - /** - * Serializes a property - * - * This is a recursive function. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $privilege - * @return void - */ - private function serializePriv($doc,$node,$privilege) { - - $xsp = $doc->createElementNS('DAV:','d:supported-privilege'); - $node->appendChild($xsp); - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $xsp->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privilege['privilege'],$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($privilege['abstract']) && $privilege['abstract']) { - $xsp->appendChild($doc->createElementNS('DAV:','d:abstract')); - } - - if (isset($privilege['description'])) { - $xsp->appendChild($doc->createElementNS('DAV:','d:description',$privilege['description'])); - } - - if (isset($privilege['aggregates'])) { - foreach($privilege['aggregates'] as $subPrivilege) { - $this->serializePriv($doc,$xsp,$subPrivilege); - } - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Version.php b/3rdparty/Sabre/DAVACL/Version.php deleted file mode 100644 index 124463e311e..00000000000 --- a/3rdparty/Sabre/DAVACL/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -httpRequest->getHeader('Authorization'); - $authHeader = explode(' ',$authHeader); - - if ($authHeader[0]!='AWS' || !isset($authHeader[1])) { - $this->errorCode = self::ERR_NOAWSHEADER; - return false; - } - - list($this->accessKey,$this->signature) = explode(':',$authHeader[1]); - - return true; - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getAccessKey() { - - return $this->accessKey; - - } - - /** - * Validates the signature based on the secretKey - * - * @return bool - */ - public function validate($secretKey) { - - $contentMD5 = $this->httpRequest->getHeader('Content-MD5'); - - if ($contentMD5) { - // We need to validate the integrity of the request - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - - if ($contentMD5!=base64_encode(md5($body,true))) { - // content-md5 header did not match md5 signature of body - $this->errorCode = self::ERR_MD5CHECKSUMWRONG; - return false; - } - - } - - if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) - $requestDate = $this->httpRequest->getHeader('Date'); - - if (!$this->validateRFC2616Date($requestDate)) - return false; - - $amzHeaders = $this->getAmzHeaders(); - - $signature = base64_encode( - $this->hmacsha1($secretKey, - $this->httpRequest->getMethod() . "\n" . - $contentMD5 . "\n" . - $this->httpRequest->getHeader('Content-type') . "\n" . - $requestDate . "\n" . - $amzHeaders . - $this->httpRequest->getURI() - ) - ); - - if ($this->signature != $signature) { - - $this->errorCode = self::ERR_INVALIDSIGNATURE; - return false; - - } - - return true; - - } - - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','AWS'); - $this->httpResponse->sendStatus(401); - - } - - /** - * Makes sure the supplied value is a valid RFC2616 date. - * - * If we would just use strtotime to get a valid timestamp, we have no way of checking if a - * user just supplied the word 'now' for the date header. - * - * This function also makes sure the Date header is within 15 minutes of the operating - * system date, to prevent replay attacks. - * - * @param string $dateHeader - * @return bool - */ - protected function validateRFC2616Date($dateHeader) { - - $date = Sabre_HTTP_Util::parseHTTPDate($dateHeader); - - // Unknown format - if (!$date) { - $this->errorCode = self::ERR_INVALIDDATEFORMAT; - return false; - } - - $min = new DateTime('-15 minutes'); - $max = new DateTime('+15 minutes'); - - // We allow 15 minutes around the current date/time - if ($date > $max || $date < $min) { - $this->errorCode = self::ERR_REQUESTTIMESKEWED; - return false; - } - - return $date; - - } - - /** - * Returns a list of AMZ headers - * - * @return void - */ - protected function getAmzHeaders() { - - $amzHeaders = array(); - $headers = $this->httpRequest->getHeaders(); - foreach($headers as $headerName => $headerValue) { - if (strpos(strtolower($headerName),'x-amz-')===0) { - $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"),array(' '),$headerValue) . "\n"; - } - } - ksort($amzHeaders); - - $headerStr = ''; - foreach($amzHeaders as $h=>$v) { - $headerStr.=$h.':'.$v; - } - - return $headerStr; - - } - - /** - * Generates an HMAC-SHA1 signature - * - * @param string $key - * @param string $message - * @return string - */ - private function hmacsha1($key, $message) { - - $blocksize=64; - if (strlen($key)>$blocksize) - $key=pack('H*', sha1($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); - return $hmac; - - } - -} diff --git a/3rdparty/Sabre/HTTP/AbstractAuth.php b/3rdparty/Sabre/HTTP/AbstractAuth.php deleted file mode 100644 index eb528f6fdee..00000000000 --- a/3rdparty/Sabre/HTTP/AbstractAuth.php +++ /dev/null @@ -1,111 +0,0 @@ -httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Sets an alternative HTTP response object - * - * @param Sabre_HTTP_Response $response - * @return void - */ - public function setHTTPResponse(Sabre_HTTP_Response $response) { - - $this->httpResponse = $response; - - } - - /** - * Sets an alternative HTTP request object - * - * @param Sabre_HTTP_Request $request - * @return void - */ - public function setHTTPRequest(Sabre_HTTP_Request $request) { - - $this->httpRequest = $request; - - } - - - /** - * Sets the realm - * - * The realm is often displayed in authentication dialog boxes - * Commonly an application name displayed here - * - * @param string $realm - * @return void - */ - public function setRealm($realm) { - - $this->realm = $realm; - - } - - /** - * Returns the realm - * - * @return string - */ - public function getRealm() { - - return $this->realm; - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - abstract public function requireLogin(); - -} diff --git a/3rdparty/Sabre/HTTP/BasicAuth.php b/3rdparty/Sabre/HTTP/BasicAuth.php deleted file mode 100644 index 35c22d22dc3..00000000000 --- a/3rdparty/Sabre/HTTP/BasicAuth.php +++ /dev/null @@ -1,61 +0,0 @@ -httpRequest->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->httpRequest->getRawServerValue('PHP_AUTH_PW'))) { - - return array($user,$pass); - - } - - // Most other webservers - $auth = $this->httpRequest->getHeader('Authorization'); - - if (!$auth) return false; - - if (strpos(strtolower($auth),'basic')!==0) return false; - - return explode(':', base64_decode(substr($auth, 6))); - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); - $this->httpResponse->sendStatus(401); - - } - -} diff --git a/3rdparty/Sabre/HTTP/DigestAuth.php b/3rdparty/Sabre/HTTP/DigestAuth.php deleted file mode 100644 index 5e755929571..00000000000 --- a/3rdparty/Sabre/HTTP/DigestAuth.php +++ /dev/null @@ -1,234 +0,0 @@ -nonce = uniqid(); - $this->opaque = md5($this->realm); - parent::__construct(); - - } - - /** - * Gathers all information from the headers - * - * This method needs to be called prior to anything else. - * - * @return void - */ - public function init() { - - $digest = $this->getDigest(); - $this->digestParts = $this->parseDigest($digest); - - } - - /** - * Sets the quality of protection value. - * - * Possible values are: - * Sabre_HTTP_DigestAuth::QOP_AUTH - * Sabre_HTTP_DigestAuth::QOP_AUTHINT - * - * Multiple values can be specified using logical OR. - * - * QOP_AUTHINT ensures integrity of the request body, but this is not - * supported by most HTTP clients. QOP_AUTHINT also requires the entire - * request body to be md5'ed, which can put strains on CPU and memory. - * - * @param int $qop - * @return void - */ - public function setQOP($qop) { - - $this->qop = $qop; - - } - - /** - * Validates the user. - * - * The A1 parameter should be md5($username . ':' . $realm . ':' . $password); - * - * @param string $A1 - * @return bool - */ - public function validateA1($A1) { - - $this->A1 = $A1; - return $this->validate(); - - } - - /** - * Validates authentication through a password. The actual password must be provided here. - * It is strongly recommended not store the password in plain-text and use validateA1 instead. - * - * @param string $password - * @return bool - */ - public function validatePassword($password) { - - $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password); - return $this->validate(); - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getUsername() { - - return $this->digestParts['username']; - - } - - /** - * Validates the digest challenge - * - * @return bool - */ - protected function validate() { - - $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri']; - - if ($this->digestParts['qop']=='auth-int') { - // Making sure we support this qop value - if (!($this->qop & self::QOP_AUTHINT)) return false; - // We need to add an md5 of the entire request body to the A2 part of the hash - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - $A2 .= ':' . md5($body); - } else { - - // We need to make sure we support this qop value - if (!($this->qop & self::QOP_AUTH)) return false; - } - - $A2 = md5($A2); - - $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}"); - - return $this->digestParts['response']==$validResponse; - - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $qop = ''; - switch($this->qop) { - case self::QOP_AUTH : $qop = 'auth'; break; - case self::QOP_AUTHINT : $qop = 'auth-int'; break; - case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break; - } - - $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"'); - $this->httpResponse->sendStatus(401); - - } - - - /** - * This method returns the full digest string. - * - * It should be compatibile with mod_php format and other webservers. - * - * If the header could not be found, null will be returned - * - * @return mixed - */ - public function getDigest() { - - // mod_php - $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST'); - if ($digest) return $digest; - - // most other servers - $digest = $this->httpRequest->getHeader('Authorization'); - - if ($digest && strpos(strtolower($digest),'digest')===0) { - return substr($digest,7); - } else { - return null; - } - - } - - - /** - * Parses the different pieces of the digest string into an array. - * - * This method returns false if an incomplete digest was supplied - * - * @param string $digest - * @return mixed - */ - protected function parseDigest($digest) { - - // protect against missing data - $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); - $data = array(); - - preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER); - - foreach ($matches as $m) { - $data[$m[1]] = $m[2] ? $m[2] : $m[3]; - unset($needed_parts[$m[1]]); - } - - return $needed_parts ? false : $data; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Request.php b/3rdparty/Sabre/HTTP/Request.php deleted file mode 100644 index 95a64171aab..00000000000 --- a/3rdparty/Sabre/HTTP/Request.php +++ /dev/null @@ -1,243 +0,0 @@ -_SERVER = $serverData; - else $this->_SERVER =& $_SERVER; - - } - - /** - * Returns the value for a specific http header. - * - * This method returns null if the header did not exist. - * - * @param string $name - * @return string - */ - public function getHeader($name) { - - $name = strtoupper(str_replace(array('-'),array('_'),$name)); - if (isset($this->_SERVER['HTTP_' . $name])) { - return $this->_SERVER['HTTP_' . $name]; - } - - // There's a few headers that seem to end up in the top-level - // server array. - switch($name) { - case 'CONTENT_TYPE' : - case 'CONTENT_LENGTH' : - if (isset($this->_SERVER[$name])) { - return $this->_SERVER[$name]; - } - break; - - } - return; - - } - - /** - * Returns all (known) HTTP headers. - * - * All headers are converted to lower-case, and additionally all underscores - * are automatically converted to dashes - * - * @return array - */ - public function getHeaders() { - - $hdrs = array(); - foreach($this->_SERVER as $key=>$value) { - - switch($key) { - case 'CONTENT_LENGTH' : - case 'CONTENT_TYPE' : - $hdrs[strtolower(str_replace('_','-',$key))] = $value; - break; - default : - if (strpos($key,'HTTP_')===0) { - $hdrs[substr(strtolower(str_replace('_','-',$key)),5)] = $value; - } - break; - } - - } - - return $hdrs; - - } - - /** - * Returns the HTTP request method - * - * This is for example POST or GET - * - * @return string - */ - public function getMethod() { - - return $this->_SERVER['REQUEST_METHOD']; - - } - - /** - * Returns the requested uri - * - * @return string - */ - public function getUri() { - - return $this->_SERVER['REQUEST_URI']; - - } - - /** - * Will return protocol + the hostname + the uri - * - * @return void - */ - public function getAbsoluteUri() { - - // Checking if the request was made through HTTPS. The last in line is for IIS - $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']!='off'); - return ($protocol?'https':'http') . '://' . $this->getHeader('Host') . $this->getUri(); - - } - - /** - * Returns everything after the ? from the current url - * - * @return string - */ - public function getQueryString() { - - return isset($this->_SERVER['QUERY_STRING'])?$this->_SERVER['QUERY_STRING']:''; - - } - - /** - * Returns the HTTP request body body - * - * This method returns a readable stream resource. - * If the asString parameter is set to true, a string is sent instead. - * - * @param bool asString - * @return resource - */ - public function getBody($asString = false) { - - if (is_null($this->body)) { - if (!is_null(self::$defaultInputStream)) { - $this->body = self::$defaultInputStream; - } else { - $this->body = fopen('php://input','r'); - self::$defaultInputStream = $this->body; - } - } - if ($asString) { - $body = stream_get_contents($this->body); - return $body; - } else { - return $this->body; - } - - } - - /** - * Sets the contents of the HTTP request body - * - * This method can either accept a string, or a readable stream resource. - * - * If the setAsDefaultInputStream is set to true, it means for this run of the - * script the supplied body will be used instead of php://input. - * - * @param mixed $body - * @param bool $setAsDefaultInputStream - * @return void - */ - public function setBody($body,$setAsDefaultInputStream = false) { - - if(is_resource($body)) { - $this->body = $body; - } else { - - $stream = fopen('php://temp','r+'); - fputs($stream,$body); - rewind($stream); - // String is assumed - $this->body = $stream; - } - if ($setAsDefaultInputStream) { - self::$defaultInputStream = $this->body; - } - - } - - /** - * Returns a specific item from the _SERVER array. - * - * Do not rely on this feature, it is for internal use only. - * - * @param string $field - * @return string - */ - public function getRawServerValue($field) { - - return isset($this->_SERVER[$field])?$this->_SERVER[$field]:null; - - } - -} - diff --git a/3rdparty/Sabre/HTTP/Response.php b/3rdparty/Sabre/HTTP/Response.php deleted file mode 100644 index dce6feac553..00000000000 --- a/3rdparty/Sabre/HTTP/Response.php +++ /dev/null @@ -1,152 +0,0 @@ - 'Continue', - 101 => 'Switching Protocols', - 102 => 'Processing', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authorative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 207 => 'Multi-Status', // RFC 4918 - 208 => 'Already Reported', // RFC 5842 - 226 => 'IM Used', // RFC 3229 - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 306 => 'Reserved', - 307 => 'Temporary Redirect', - 400 => 'Bad request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - 418 => 'I\'m a teapot', // RFC 2324 - 422 => 'Unprocessable Entity', // RFC 4918 - 423 => 'Locked', // RFC 4918 - 424 => 'Failed Dependency', // RFC 4918 - 426 => 'Upgrade required', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version not supported', - 506 => 'Variant Also Negotiates', - 507 => 'Unsufficient Storage', // RFC 4918 - 508 => 'Loop Detected', // RFC 5842 - 509 => 'Bandwidth Limit Exceeded', // non-standard - 510 => 'Not extended', - ); - - return 'HTTP/1.1 ' . $code . ' ' . $msg[$code]; - - } - - /** - * Sends an HTTP status header to the client - * - * @param int $code HTTP status code - * @return void - */ - public function sendStatus($code) { - - if (!headers_sent()) - return header($this->getStatusMessage($code)); - else return false; - - } - - /** - * Sets an HTTP header for the response - * - * @param string $name - * @param string $value - * @return void - */ - public function setHeader($name, $value, $replace = true) { - - $value = str_replace(array("\r","\n"),array('\r','\n'),$value); - if (!headers_sent()) - return header($name . ': ' . $value, $replace); - else return false; - - } - - /** - * Sets a bunch of HTTP Headers - * - * headersnames are specified as keys, value in the array value - * - * @param array $headers - * @return void - */ - public function setHeaders(array $headers) { - - foreach($headers as $key=>$value) - $this->setHeader($key, $value); - - } - - /** - * Sends the entire response body - * - * This method can accept either an open filestream, or a string. - * - * @param mixed $body - * @return void - */ - public function sendBody($body) { - - if (is_resource($body)) { - - fpassthru($body); - - } else { - - // We assume a string - echo $body; - - } - - } - -} diff --git a/3rdparty/Sabre/HTTP/Util.php b/3rdparty/Sabre/HTTP/Util.php deleted file mode 100644 index 8a6bd7df487..00000000000 --- a/3rdparty/Sabre/HTTP/Util.php +++ /dev/null @@ -1,65 +0,0 @@ -= 0) - return new DateTime('@' . $realDate, new DateTimeZone('UTC')); - - return false; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Version.php b/3rdparty/Sabre/HTTP/Version.php deleted file mode 100644 index 67be232fc26..00000000000 --- a/3rdparty/Sabre/HTTP/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -name = strtoupper($name); - if (!is_null($iterator)) $this->iterator = $iterator; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = "BEGIN:" . $this->name . "\r\n"; - foreach($this->children as $child) $str.=$child->serialize(); - $str.= "END:" . $this->name . "\r\n"; - - return $str; - - } - - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Element $element) - * add(string $name, $value) - * - * The first version adds an Element - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Element) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->children[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $item = new Sabre_VObject_Property($item,$itemValue); - $item->parent = $this; - $this->children[] = $item; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - /** - * Returns an iterable list of children - * - * @return Sabre_VObject_ElementList - */ - public function children() { - - return new Sabre_VObject_ElementList($this->children); - - } - - /** - * Returns an array with elements that match the specified name. - * - * This function is also aware of MIME-Directory groups (as they appear in - * vcards). This means that if a property is grouped as "HOME.EMAIL", it - * will also be returned when searching for just "EMAIL". If you want to - * search for a property in a specific group, you can select on the entire - * string ("HOME.EMAIL"). If you want to search on a specific property that - * has not been assigned a group, specify ".EMAIL". - * - * Keys are retained from the 'children' array, which may be confusing in - * certain cases. - * - * @param string $name - * @return array - */ - public function select($name) { - - $group = null; - $name = strtoupper($name); - if (strpos($name,'.')!==false) { - list($group,$name) = explode('.', $name, 2); - } - - $result = array(); - foreach($this->children as $key=>$child) { - - if ( - strtoupper($child->name) === $name && - (is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group)) - ) { - - $result[$key] = $child; - - } - } - - reset($result); - return $result; - - } - - /* Magic property accessors {{{ */ - - /** - * Using 'get' you will either get a propery or component, - * - * If there were no child-elements found with the specified name, - * null is returned. - * - * @param string $name - * @return void - */ - public function __get($name) { - - $matches = $this->select($name); - if (count($matches)===0) { - return null; - } else { - $firstMatch = current($matches); - $firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches))); - return $firstMatch; - } - - } - - /** - * This method checks if a sub-element with the specified name exists. - * - * @param string $name - * @return bool - */ - public function __isset($name) { - - $matches = $this->select($name); - return count($matches)>0; - - } - - /** - * Using the setter method you can add properties or subcomponents - * - * You can either pass a Sabre_VObject_Component, Sabre_VObject_Property - * object, or a string to automatically create a Property. - * - * If the item already exists, it will be removed. If you want to add - * a new item with the same name, always use the add() method. - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) { - - $matches = $this->select($name); - $overWrite = count($matches)?key($matches):null; - - if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) { - $value->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $value; - } else { - $this->children[] = $value; - } - } elseif (is_scalar($value)) { - $property = new Sabre_VObject_Property($name,$value); - $property->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $property; - } else { - $this->children[] = $property; - } - } else { - throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type'); - } - - } - - /** - * Removes all properties and components within this component. - * - * @param string $name - * @return void - */ - public function __unset($name) { - - $matches = $this->select($name); - foreach($matches as $k=>$child) { - - unset($this->children[$k]); - $child->parent = null; - - } - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Element.php b/3rdparty/Sabre/VObject/Element.php deleted file mode 100644 index 8d2b0aaacd1..00000000000 --- a/3rdparty/Sabre/VObject/Element.php +++ /dev/null @@ -1,15 +0,0 @@ -setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::UTC : - $dt->setTimeZone(new DateTimeZone('UTC')); - $this->setValue($dt->format('Ymd\\THis\\Z')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::LOCALTZ : - $this->setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt->getTimeZone()->getName()); - break; - case self::DATE : - $this->setValue($dt->format('Ymd')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTime = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return DateTime|null - */ - public function getDateTime() { - - if ($this->dateTime) - return $this->dateTime; - - list( - $this->dateType, - $this->dateTime - ) = self::parseData($this->value, $this); - return $this->dateTime; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - list( - $this->dateType, - $this->dateTime, - ) = self::parseData($this->value, $this); - return $this->dateType; - - } - - /** - * Parses the internal data structure to figure out what the current date - * and time is. - * - * The returned array contains two elements: - * 1. A 'DateType' constant (as defined on this class), or null. - * 2. A DateTime object (or null) - * - * @param string|null $propertyValue The string to parse (yymmdd or - * ymmddThhmmss, etc..) - * @param Sabre_VObject_Property|null $property The instance of the - * property we're parsing. - * @return array - */ - static public function parseData($propertyValue, Sabre_VObject_Property $property = null) { - - if (is_null($propertyValue)) { - return array(null, null); - } - - $date = '(?P[1-2][0-9]{3})(?P[0-1][0-9])(?P[0-3][0-9])'; - $time = '(?P[0-2][0-9])(?P[0-5][0-9])(?P[0-5][0-9])'; - $regex = "/^$date(T$time(?PZ)?)?$/"; - - if (!preg_match($regex, $propertyValue, $matches)) { - throw new InvalidArgumentException($propertyValue . ' is not a valid DateTime or Date string'); - } - - if (!isset($matches['hour'])) { - // Date-only - return array( - self::DATE, - new DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00'), - ); - } - - $dateStr = - $matches['year'] .'-' . - $matches['month'] . '-' . - $matches['date'] . ' ' . - $matches['hour'] . ':' . - $matches['minute'] . ':' . - $matches['second']; - - if (isset($matches['isutc'])) { - $dt = new DateTime($dateStr,new DateTimeZone('UTC')); - $dt->setTimeZone(new DateTimeZone('UTC')); - return array( - self::UTC, - $dt - ); - } - - // Finding the timezone. - $tzid = $property['TZID']; - if (!$tzid) { - return array( - self::LOCAL, - new DateTime($dateStr) - ); - } - - try { - $tz = new DateTimeZone($tzid->value); - } catch (Exception $e) { - - // The id was invalid, we're going to try to find the information - // through the VTIMEZONE object. - - // First we find the root object - $root = $property; - while($root->parent) { - $root = $root->parent; - } - - if (isset($root->VTIMEZONE)) { - foreach($root->VTIMEZONE as $vtimezone) { - if (((string)$vtimezone->TZID) == $tzid) { - if (isset($vtimezone->{'X-LIC-LOCATION'})) { - $tzid = (string)$vtimezone->{'X-LIC-LOCATION'}; - } - } - } - } - - $tz = new DateTimeZone($tzid); - - } - $dt = new DateTime($dateStr, $tz); - $dt->setTimeZone($tz); - - return array( - self::LOCALTZ, - $dt - ); - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/Element/MultiDateTime.php b/3rdparty/Sabre/VObject/Element/MultiDateTime.php deleted file mode 100644 index dc6ca5abb80..00000000000 --- a/3rdparty/Sabre/VObject/Element/MultiDateTime.php +++ /dev/null @@ -1,168 +0,0 @@ -offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - switch($dateType) { - - case Sabre_VObject_Element_DateTime::LOCAL : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::UTC : - $val = array(); - foreach($dt as $i) { - $i->setTimeZone(new DateTimeZone('UTC')); - $val[] = $i->format('Ymd\\THis\\Z'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::LOCALTZ : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt[0]->getTimeZone()->getName()); - break; - case Sabre_VObject_Element_DateTime::DATE : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTimes = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return array|null - */ - public function getDateTimes() { - - if ($this->dateTimes) - return $this->dateTimes; - - $dts = array(); - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateTimes; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - $dts = array(); - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateType; - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/ElementList.php b/3rdparty/Sabre/VObject/ElementList.php deleted file mode 100644 index 9922cd587bc..00000000000 --- a/3rdparty/Sabre/VObject/ElementList.php +++ /dev/null @@ -1,172 +0,0 @@ -vevent where there's multiple VEVENT objects. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess { - - /** - * Inner elements - * - * @var array - */ - protected $elements = array(); - - /** - * Creates the element list. - * - * @param array $elements - */ - public function __construct(array $elements) { - - $this->elements = $elements; - - } - - /* {{{ Iterator interface */ - - /** - * Current position - * - * @var int - */ - private $key = 0; - - /** - * Returns current item in iteration - * - * @return Sabre_VObject_Element - */ - public function current() { - - return $this->elements[$this->key]; - - } - - /** - * To the next item in the iterator - * - * @return void - */ - public function next() { - - $this->key++; - - } - - /** - * Returns the current iterator key - * - * @return int - */ - public function key() { - - return $this->key; - - } - - /** - * Returns true if the current position in the iterator is a valid one - * - * @return bool - */ - public function valid() { - - return isset($this->elements[$this->key]); - - } - - /** - * Rewinds the iterator - * - * @return void - */ - public function rewind() { - - $this->key = 0; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - return count($this->elements); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - return isset($this->elements[$offset]); - - } - - /** - * Gets an item through ArrayAccess. - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - return $this->elements[$offset]; - - } - - /** - * Sets an item through ArrayAccess. - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - throw new LogicException('You can not add new objects to an ElementList'); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - throw new LogicException('You can not remove objects from an ElementList'); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Node.php b/3rdparty/Sabre/VObject/Node.php deleted file mode 100644 index 7100b62f1cb..00000000000 --- a/3rdparty/Sabre/VObject/Node.php +++ /dev/null @@ -1,149 +0,0 @@ -iterator)) - return $this->iterator; - - return new Sabre_VObject_ElementList(array($this)); - - } - - /** - * Sets the overridden iterator - * - * Note that this is not actually part of the iterator interface - * - * @param Sabre_VObject_ElementList $iterator - * @return void - */ - public function setIterator(Sabre_VObject_ElementList $iterator) { - - $this->iterator = $iterator; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - $it = $this->getIterator(); - return $it->count(); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetExists($offset); - - } - - /** - * Gets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetGet($offset); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - $iterator = $this->getIterator(); - return $iterator->offsetSet($offset,$value); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetUnset($offset); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Parameter.php b/3rdparty/Sabre/VObject/Parameter.php deleted file mode 100644 index 9ebab6ec69b..00000000000 --- a/3rdparty/Sabre/VObject/Parameter.php +++ /dev/null @@ -1,81 +0,0 @@ -name = strtoupper($name); - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $src = array( - '\\', - "\n", - ';', - ',', - ); - $out = array( - '\\\\', - '\n', - '\;', - '\,', - ); - - return $this->name . '=' . str_replace($src, $out, $this->value); - - } - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - -} diff --git a/3rdparty/Sabre/VObject/ParseException.php b/3rdparty/Sabre/VObject/ParseException.php deleted file mode 100644 index ed4ef2e8592..00000000000 --- a/3rdparty/Sabre/VObject/ParseException.php +++ /dev/null @@ -1,12 +0,0 @@ -name = $name; - $this->group = $group; - if (!is_null($iterator)) $this->iterator = $iterator; - $this->setValue($value); - - } - - /** - * Updates the internal value - * - * @param string $value - * @return void - */ - public function setValue($value) { - - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = $this->name; - if ($this->group) $str = $this->group . '.' . $this->name; - - if (count($this->parameters)) { - foreach($this->parameters as $param) { - - $str.=';' . $param->serialize(); - - } - } - $src = array( - '\\', - "\n", - ); - $out = array( - '\\\\', - '\n', - ); - $str.=':' . str_replace($src, $out, $this->value); - - $out = ''; - while(strlen($str)>0) { - if (strlen($str)>75) { - $out.= substr($str,0,75) . "\r\n"; - $str = ' ' . substr($str,75); - } else { - $out.=$str . "\r\n"; - $str=''; - break; - } - } - - return $out; - - } - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Parameter $element) - * add(string $name, $value) - * - * The first version adds an Parameter - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Parameter) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->parameters[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $parameter = new Sabre_VObject_Parameter($item,$itemValue); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - - /* ArrayAccess interface {{{ */ - - /** - * Checks if an array element exists - * - * @param mixed $name - * @return bool - */ - public function offsetExists($name) { - - if (is_int($name)) return parent::offsetExists($name); - - $name = strtoupper($name); - - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) return true; - } - return false; - - } - - /** - * Returns a parameter, or parameter list. - * - * @param string $name - * @return Sabre_VObject_Element - */ - public function offsetGet($name) { - - if (is_int($name)) return parent::offsetGet($name); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) - $result[] = $parameter; - } - - if (count($result)===0) { - return null; - } elseif (count($result)===1) { - return $result[0]; - } else { - $result[0]->setIterator(new Sabre_VObject_ElementList($result)); - return $result[0]; - } - - } - - /** - * Creates a new parameter - * - * @param string $name - * @param mixed $value - * @return void - */ - public function offsetSet($name, $value) { - - if (is_int($name)) return parent::offsetSet($name, $value); - - if (is_scalar($value)) { - if (!is_string($name)) - throw new InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.'); - - $this->offsetUnset($name); - $parameter = new Sabre_VObject_Parameter($name, $value); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } elseif ($value instanceof Sabre_VObject_Parameter) { - if (!is_null($name)) - throw new InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a Sabre_VObject_Parameter. Add using $array[]=$parameterObject.'); - - $value->parent = $this; - $this->parameters[] = $value; - } else { - throw new InvalidArgumentException('You can only add parameters to the property object'); - } - - } - - /** - * Removes one or more parameters with the specified name - * - * @param string $name - * @return void - */ - public function offsetUnset($name) { - - if (is_int($name)) return parent::offsetUnset($name, $value); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $key=>$parameter) { - if ($parameter->name == $name) { - $parameter->parent = null; - unset($this->parameters[$key]); - } - - } - - } - - /* }}} */ - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Reader.php b/3rdparty/Sabre/VObject/Reader.php deleted file mode 100644 index 7d1c282838e..00000000000 --- a/3rdparty/Sabre/VObject/Reader.php +++ /dev/null @@ -1,191 +0,0 @@ - 'Sabre_VObject_Element_DateTime', - 'DTEND' => 'Sabre_VObject_Element_DateTime', - 'COMPLETED' => 'Sabre_VObject_Element_DateTime', - 'DUE' => 'Sabre_VObject_Element_DateTime', - 'EXDATE' => 'Sabre_VObject_Element_MultiDateTime', - ); - - /** - * Parses the file and returns the top component - * - * @param string $data - * @return Sabre_VObject_Element - */ - static function read($data) { - - // Normalizing newlines - $data = str_replace(array("\r","\n\n"), array("\n","\n"), $data); - - $lines = explode("\n", $data); - - // Unfolding lines - $lines2 = array(); - foreach($lines as $line) { - - // Skipping empty lines - if (!$line) continue; - - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - } else { - $lines2[] = $line; - } - - } - - unset($lines); - - reset($lines2); - - return self::readLine($lines2); - - } - - /** - * Reads and parses a single line. - * - * This method receives the full array of lines. The array pointer is used - * to traverse. - * - * @param array $lines - * @return Sabre_VObject_Element - */ - static private function readLine(&$lines) { - - $line = current($lines); - $lineNr = key($lines); - next($lines); - - // Components - if (stripos($line,"BEGIN:")===0) { - - // This is a component - $obj = new Sabre_VObject_Component(strtoupper(substr($line,6))); - - $nextLine = current($lines); - - while(stripos($nextLine,"END:")!==0) { - - $obj->add(self::readLine($lines)); - $nextLine = current($lines); - - if ($nextLine===false) - throw new Sabre_VObject_ParseException('Invalid VObject. Document ended prematurely.'); - - } - - // Checking component name of the 'END:' line. - if (substr($nextLine,4)!==$obj->name) { - throw new Sabre_VObject_ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"'); - } - next($lines); - - return $obj; - - } - - // Properties - //$result = preg_match('/(?P[A-Z0-9-]+)(?:;(?P^(?([^:^\"]|\"([^\"]*)\")*))?"; - $regex = "/^(?P$token)$parameters:(?P.*)$/i"; - - $result = preg_match($regex,$line,$matches); - - if (!$result) { - throw new Sabre_VObject_ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format'); - } - - $propertyName = strtoupper($matches['name']); - $propertyValue = stripcslashes($matches['value']); - - if (isset(self::$elementMap[$propertyName])) { - $className = self::$elementMap[$propertyName]; - } else { - $className = 'Sabre_VObject_Property'; - } - - $obj = new $className($propertyName, $propertyValue); - - if ($matches['parameters']) { - - foreach(self::readParameters($matches['parameters']) as $param) { - $obj->add($param); - } - } - - return $obj; - - - } - - /** - * Reads a parameter list from a property - * - * This method returns an array of Sabre_VObject_Parameter - * - * @param string $parameters - * @return array - */ - static private function readParameters($parameters) { - - $token = '[A-Z0-9-]+'; - - $paramValue = '(?P[^\"^;]*|"[^"]*")'; - - $regex = "/(?<=^|;)(?P$token)(=$paramValue(?=$|;))?/i"; - preg_match_all($regex, $parameters, $matches, PREG_SET_ORDER); - - $params = array(); - foreach($matches as $match) { - - $value = isset($match['paramValue'])?$match['paramValue']:null; - - if (isset($value[0])) { - // Stripping quotes, if needed - if ($value[0] === '"') $value = substr($value,1,strlen($value)-2); - } else { - $value = ''; - } - - $params[] = new Sabre_VObject_Parameter($match['paramName'], stripcslashes($value)); - - } - - return $params; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Version.php b/3rdparty/Sabre/VObject/Version.php deleted file mode 100644 index 937c367e222..00000000000 --- a/3rdparty/Sabre/VObject/Version.php +++ /dev/null @@ -1,24 +0,0 @@ - Date: Sat, 21 Apr 2012 23:24:39 +0200 Subject: [PATCH 216/430] update to SabreDav 1.6.2 --- 3rdparty/Sabre.includes.php | 26 + 3rdparty/Sabre/CalDAV/Backend/Abstract.php | 168 ++ 3rdparty/Sabre/CalDAV/Backend/PDO.php | 396 ++++ 3rdparty/Sabre/CalDAV/Calendar.php | 343 +++ 3rdparty/Sabre/CalDAV/CalendarObject.php | 273 +++ 3rdparty/Sabre/CalDAV/CalendarQueryParser.php | 296 +++ .../Sabre/CalDAV/CalendarQueryValidator.php | 347 +++ 3rdparty/Sabre/CalDAV/CalendarRootNode.php | 75 + 3rdparty/Sabre/CalDAV/ICSExportPlugin.php | 139 ++ 3rdparty/Sabre/CalDAV/ICalendar.php | 18 + 3rdparty/Sabre/CalDAV/ICalendarObject.php | 20 + 3rdparty/Sabre/CalDAV/Plugin.php | 829 +++++++ .../Sabre/CalDAV/Principal/Collection.php | 31 + 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php | 178 ++ .../Sabre/CalDAV/Principal/ProxyWrite.php | 178 ++ 3rdparty/Sabre/CalDAV/Principal/User.php | 132 ++ .../SupportedCalendarComponentSet.php | 85 + .../CalDAV/Property/SupportedCalendarData.php | 38 + .../CalDAV/Property/SupportedCollationSet.php | 44 + 3rdparty/Sabre/CalDAV/Schedule/IMip.php | 104 + 3rdparty/Sabre/CalDAV/Schedule/IOutbox.php | 16 + 3rdparty/Sabre/CalDAV/Schedule/Outbox.php | 152 ++ 3rdparty/Sabre/CalDAV/Server.php | 68 + 3rdparty/Sabre/CalDAV/UserCalendars.php | 298 +++ 3rdparty/Sabre/CalDAV/Version.php | 24 + 3rdparty/Sabre/CalDAV/includes.php | 43 + 3rdparty/Sabre/CardDAV/AddressBook.php | 310 +++ .../Sabre/CardDAV/AddressBookQueryParser.php | 209 ++ 3rdparty/Sabre/CardDAV/AddressBookRoot.php | 78 + 3rdparty/Sabre/CardDAV/Backend/Abstract.php | 166 ++ 3rdparty/Sabre/CardDAV/Backend/PDO.php | 330 +++ 3rdparty/Sabre/CardDAV/Card.php | 250 +++ 3rdparty/Sabre/CardDAV/IAddressBook.php | 18 + 3rdparty/Sabre/CardDAV/ICard.php | 18 + 3rdparty/Sabre/CardDAV/IDirectory.php | 21 + 3rdparty/Sabre/CardDAV/Plugin.php | 587 +++++ .../CardDAV/Property/SupportedAddressData.php | 69 + 3rdparty/Sabre/CardDAV/UserAddressBooks.php | 257 +++ 3rdparty/Sabre/CardDAV/Version.php | 26 + 3rdparty/Sabre/CardDAV/includes.php | 32 + .../Sabre/DAV/Auth/Backend/AbstractBasic.php | 83 + .../Sabre/DAV/Auth/Backend/AbstractDigest.php | 98 + 3rdparty/Sabre/DAV/Auth/Backend/Apache.php | 62 + 3rdparty/Sabre/DAV/Auth/Backend/File.php | 75 + 3rdparty/Sabre/DAV/Auth/Backend/PDO.php | 65 + 3rdparty/Sabre/DAV/Auth/IBackend.php | 36 + 3rdparty/Sabre/DAV/Auth/Plugin.php | 111 + .../Sabre/DAV/Browser/GuessContentType.php | 97 + .../Sabre/DAV/Browser/MapGetToPropFind.php | 55 + 3rdparty/Sabre/DAV/Browser/Plugin.php | 489 ++++ 3rdparty/Sabre/DAV/Browser/assets/favicon.ico | Bin 0 -> 4286 bytes .../DAV/Browser/assets/icons/addressbook.png | Bin 0 -> 7232 bytes .../DAV/Browser/assets/icons/calendar.png | Bin 0 -> 4388 bytes .../Sabre/DAV/Browser/assets/icons/card.png | Bin 0 -> 5695 bytes .../DAV/Browser/assets/icons/collection.png | Bin 0 -> 3474 bytes .../Sabre/DAV/Browser/assets/icons/file.png | Bin 0 -> 2837 bytes .../Sabre/DAV/Browser/assets/icons/parent.png | Bin 0 -> 3474 bytes .../DAV/Browser/assets/icons/principal.png | Bin 0 -> 5480 bytes 3rdparty/Sabre/DAV/Client.php | 460 ++++ 3rdparty/Sabre/DAV/Collection.php | 106 + 3rdparty/Sabre/DAV/Directory.php | 17 + 3rdparty/Sabre/DAV/Exception.php | 64 + 3rdparty/Sabre/DAV/Exception/BadRequest.php | 28 + 3rdparty/Sabre/DAV/Exception/Conflict.php | 28 + .../Sabre/DAV/Exception/ConflictingLock.php | 35 + 3rdparty/Sabre/DAV/Exception/FileNotFound.php | 19 + 3rdparty/Sabre/DAV/Exception/Forbidden.php | 27 + .../DAV/Exception/InsufficientStorage.php | 27 + .../DAV/Exception/InvalidResourceType.php | 33 + .../Exception/LockTokenMatchesRequestUri.php | 39 + 3rdparty/Sabre/DAV/Exception/Locked.php | 67 + .../Sabre/DAV/Exception/MethodNotAllowed.php | 45 + .../Sabre/DAV/Exception/NotAuthenticated.php | 28 + 3rdparty/Sabre/DAV/Exception/NotFound.php | 28 + .../Sabre/DAV/Exception/NotImplemented.php | 27 + .../Sabre/DAV/Exception/PaymentRequired.php | 28 + .../DAV/Exception/PreconditionFailed.php | 69 + .../DAV/Exception/ReportNotImplemented.php | 30 + .../RequestedRangeNotSatisfiable.php | 29 + .../DAV/Exception/UnsupportedMediaType.php | 28 + 3rdparty/Sabre/DAV/FS/Directory.php | 136 ++ 3rdparty/Sabre/DAV/FS/File.php | 89 + 3rdparty/Sabre/DAV/FS/Node.php | 80 + 3rdparty/Sabre/DAV/FSExt/Directory.php | 154 ++ 3rdparty/Sabre/DAV/FSExt/File.php | 93 + 3rdparty/Sabre/DAV/FSExt/Node.php | 212 ++ 3rdparty/Sabre/DAV/File.php | 85 + 3rdparty/Sabre/DAV/ICollection.php | 74 + 3rdparty/Sabre/DAV/IExtendedCollection.php | 28 + 3rdparty/Sabre/DAV/IFile.php | 77 + 3rdparty/Sabre/DAV/INode.php | 46 + 3rdparty/Sabre/DAV/IProperties.php | 67 + 3rdparty/Sabre/DAV/IQuota.php | 27 + 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php | 50 + 3rdparty/Sabre/DAV/Locks/Backend/FS.php | 191 ++ 3rdparty/Sabre/DAV/Locks/Backend/File.php | 181 ++ 3rdparty/Sabre/DAV/Locks/Backend/PDO.php | 165 ++ 3rdparty/Sabre/DAV/Locks/LockInfo.php | 81 + 3rdparty/Sabre/DAV/Locks/Plugin.php | 633 ++++++ 3rdparty/Sabre/DAV/Mount/Plugin.php | 80 + 3rdparty/Sabre/DAV/Node.php | 55 + 3rdparty/Sabre/DAV/ObjectTree.php | 153 ++ 3rdparty/Sabre/DAV/Property.php | 25 + .../Sabre/DAV/Property/GetLastModified.php | 75 + 3rdparty/Sabre/DAV/Property/Href.php | 91 + 3rdparty/Sabre/DAV/Property/HrefList.php | 96 + 3rdparty/Sabre/DAV/Property/IHref.php | 25 + 3rdparty/Sabre/DAV/Property/LockDiscovery.php | 102 + 3rdparty/Sabre/DAV/Property/ResourceType.php | 125 ++ 3rdparty/Sabre/DAV/Property/Response.php | 155 ++ 3rdparty/Sabre/DAV/Property/ResponseList.php | 57 + 3rdparty/Sabre/DAV/Property/SupportedLock.php | 76 + .../Sabre/DAV/Property/SupportedReportSet.php | 109 + 3rdparty/Sabre/DAV/Server.php | 1999 +++++++++++++++++ 3rdparty/Sabre/DAV/ServerPlugin.php | 90 + 3rdparty/Sabre/DAV/SimpleCollection.php | 105 + 3rdparty/Sabre/DAV/SimpleDirectory.php | 21 + 3rdparty/Sabre/DAV/SimpleFile.php | 121 + 3rdparty/Sabre/DAV/StringUtil.php | 91 + .../Sabre/DAV/TemporaryFileFilterPlugin.php | 289 +++ 3rdparty/Sabre/DAV/Tree.php | 193 ++ 3rdparty/Sabre/DAV/Tree/Filesystem.php | 123 + 3rdparty/Sabre/DAV/URLUtil.php | 121 + 3rdparty/Sabre/DAV/UUIDUtil.php | 64 + 3rdparty/Sabre/DAV/Version.php | 24 + 3rdparty/Sabre/DAV/XMLUtil.php | 186 ++ 3rdparty/Sabre/DAV/includes.php | 97 + .../DAVACL/AbstractPrincipalCollection.php | 154 ++ .../Sabre/DAVACL/Exception/AceConflict.php | 32 + .../Sabre/DAVACL/Exception/NeedPrivileges.php | 81 + .../Sabre/DAVACL/Exception/NoAbstract.php | 32 + .../Exception/NotRecognizedPrincipal.php | 32 + .../Exception/NotSupportedPrivilege.php | 32 + 3rdparty/Sabre/DAVACL/IACL.php | 73 + 3rdparty/Sabre/DAVACL/IPrincipal.php | 75 + 3rdparty/Sabre/DAVACL/IPrincipalBackend.php | 153 ++ 3rdparty/Sabre/DAVACL/Plugin.php | 1348 +++++++++++ 3rdparty/Sabre/DAVACL/Principal.php | 279 +++ .../Sabre/DAVACL/PrincipalBackend/PDO.php | 427 ++++ 3rdparty/Sabre/DAVACL/PrincipalCollection.php | 35 + 3rdparty/Sabre/DAVACL/Property/Acl.php | 209 ++ .../Sabre/DAVACL/Property/AclRestrictions.php | 32 + .../Property/CurrentUserPrivilegeSet.php | 75 + 3rdparty/Sabre/DAVACL/Property/Principal.php | 160 ++ .../DAVACL/Property/SupportedPrivilegeSet.php | 92 + 3rdparty/Sabre/DAVACL/Version.php | 24 + 3rdparty/Sabre/DAVACL/includes.php | 38 + 3rdparty/Sabre/HTTP/AWSAuth.php | 227 ++ 3rdparty/Sabre/HTTP/AbstractAuth.php | 111 + 3rdparty/Sabre/HTTP/BasicAuth.php | 67 + 3rdparty/Sabre/HTTP/DigestAuth.php | 240 ++ 3rdparty/Sabre/HTTP/Request.php | 268 +++ 3rdparty/Sabre/HTTP/Response.php | 157 ++ 3rdparty/Sabre/HTTP/Util.php | 82 + 3rdparty/Sabre/HTTP/Version.php | 24 + 3rdparty/Sabre/HTTP/includes.php | 27 + 3rdparty/Sabre/VObject/Component.php | 365 +++ 3rdparty/Sabre/VObject/Component/VAlarm.php | 102 + .../Sabre/VObject/Component/VCalendar.php | 133 ++ 3rdparty/Sabre/VObject/Component/VEvent.php | 70 + 3rdparty/Sabre/VObject/Component/VJournal.php | 46 + 3rdparty/Sabre/VObject/Component/VTodo.php | 68 + 3rdparty/Sabre/VObject/DateTimeParser.php | 177 ++ 3rdparty/Sabre/VObject/Element.php | 16 + 3rdparty/Sabre/VObject/Element/DateTime.php | 37 + .../Sabre/VObject/Element/MultiDateTime.php | 17 + 3rdparty/Sabre/VObject/ElementList.php | 172 ++ 3rdparty/Sabre/VObject/FreeBusyGenerator.php | 297 +++ 3rdparty/Sabre/VObject/Node.php | 149 ++ 3rdparty/Sabre/VObject/Parameter.php | 84 + 3rdparty/Sabre/VObject/ParseException.php | 12 + 3rdparty/Sabre/VObject/Property.php | 348 +++ 3rdparty/Sabre/VObject/Property/DateTime.php | 260 +++ .../Sabre/VObject/Property/MultiDateTime.php | 166 ++ 3rdparty/Sabre/VObject/Reader.php | 183 ++ 3rdparty/Sabre/VObject/RecurrenceIterator.php | 1009 +++++++++ 3rdparty/Sabre/VObject/Version.php | 24 + 3rdparty/Sabre/VObject/WindowsTimezoneMap.php | 128 ++ 3rdparty/Sabre/VObject/includes.php | 41 + 3rdparty/Sabre/autoload.php | 31 + 180 files changed, 24863 insertions(+) create mode 100755 3rdparty/Sabre.includes.php create mode 100755 3rdparty/Sabre/CalDAV/Backend/Abstract.php create mode 100755 3rdparty/Sabre/CalDAV/Backend/PDO.php create mode 100755 3rdparty/Sabre/CalDAV/Calendar.php create mode 100755 3rdparty/Sabre/CalDAV/CalendarObject.php create mode 100755 3rdparty/Sabre/CalDAV/CalendarQueryParser.php create mode 100755 3rdparty/Sabre/CalDAV/CalendarQueryValidator.php create mode 100755 3rdparty/Sabre/CalDAV/CalendarRootNode.php create mode 100755 3rdparty/Sabre/CalDAV/ICSExportPlugin.php create mode 100755 3rdparty/Sabre/CalDAV/ICalendar.php create mode 100755 3rdparty/Sabre/CalDAV/ICalendarObject.php create mode 100755 3rdparty/Sabre/CalDAV/Plugin.php create mode 100755 3rdparty/Sabre/CalDAV/Principal/Collection.php create mode 100755 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php create mode 100755 3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php create mode 100755 3rdparty/Sabre/CalDAV/Principal/User.php create mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php create mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php create mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php create mode 100755 3rdparty/Sabre/CalDAV/Schedule/IMip.php create mode 100755 3rdparty/Sabre/CalDAV/Schedule/IOutbox.php create mode 100755 3rdparty/Sabre/CalDAV/Schedule/Outbox.php create mode 100755 3rdparty/Sabre/CalDAV/Server.php create mode 100755 3rdparty/Sabre/CalDAV/UserCalendars.php create mode 100755 3rdparty/Sabre/CalDAV/Version.php create mode 100755 3rdparty/Sabre/CalDAV/includes.php create mode 100755 3rdparty/Sabre/CardDAV/AddressBook.php create mode 100755 3rdparty/Sabre/CardDAV/AddressBookQueryParser.php create mode 100755 3rdparty/Sabre/CardDAV/AddressBookRoot.php create mode 100755 3rdparty/Sabre/CardDAV/Backend/Abstract.php create mode 100755 3rdparty/Sabre/CardDAV/Backend/PDO.php create mode 100755 3rdparty/Sabre/CardDAV/Card.php create mode 100755 3rdparty/Sabre/CardDAV/IAddressBook.php create mode 100755 3rdparty/Sabre/CardDAV/ICard.php create mode 100755 3rdparty/Sabre/CardDAV/IDirectory.php create mode 100755 3rdparty/Sabre/CardDAV/Plugin.php create mode 100755 3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php create mode 100755 3rdparty/Sabre/CardDAV/UserAddressBooks.php create mode 100755 3rdparty/Sabre/CardDAV/Version.php create mode 100755 3rdparty/Sabre/CardDAV/includes.php create mode 100755 3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php create mode 100755 3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php create mode 100755 3rdparty/Sabre/DAV/Auth/Backend/Apache.php create mode 100755 3rdparty/Sabre/DAV/Auth/Backend/File.php create mode 100755 3rdparty/Sabre/DAV/Auth/Backend/PDO.php create mode 100755 3rdparty/Sabre/DAV/Auth/IBackend.php create mode 100755 3rdparty/Sabre/DAV/Auth/Plugin.php create mode 100755 3rdparty/Sabre/DAV/Browser/GuessContentType.php create mode 100755 3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php create mode 100755 3rdparty/Sabre/DAV/Browser/Plugin.php create mode 100755 3rdparty/Sabre/DAV/Browser/assets/favicon.ico create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/addressbook.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/calendar.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/card.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/collection.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/file.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/parent.png create mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/principal.png create mode 100755 3rdparty/Sabre/DAV/Client.php create mode 100755 3rdparty/Sabre/DAV/Collection.php create mode 100755 3rdparty/Sabre/DAV/Directory.php create mode 100755 3rdparty/Sabre/DAV/Exception.php create mode 100755 3rdparty/Sabre/DAV/Exception/BadRequest.php create mode 100755 3rdparty/Sabre/DAV/Exception/Conflict.php create mode 100755 3rdparty/Sabre/DAV/Exception/ConflictingLock.php create mode 100755 3rdparty/Sabre/DAV/Exception/FileNotFound.php create mode 100755 3rdparty/Sabre/DAV/Exception/Forbidden.php create mode 100755 3rdparty/Sabre/DAV/Exception/InsufficientStorage.php create mode 100755 3rdparty/Sabre/DAV/Exception/InvalidResourceType.php create mode 100755 3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php create mode 100755 3rdparty/Sabre/DAV/Exception/Locked.php create mode 100755 3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php create mode 100755 3rdparty/Sabre/DAV/Exception/NotAuthenticated.php create mode 100755 3rdparty/Sabre/DAV/Exception/NotFound.php create mode 100755 3rdparty/Sabre/DAV/Exception/NotImplemented.php create mode 100755 3rdparty/Sabre/DAV/Exception/PaymentRequired.php create mode 100755 3rdparty/Sabre/DAV/Exception/PreconditionFailed.php create mode 100755 3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php create mode 100755 3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php create mode 100755 3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php create mode 100755 3rdparty/Sabre/DAV/FS/Directory.php create mode 100755 3rdparty/Sabre/DAV/FS/File.php create mode 100755 3rdparty/Sabre/DAV/FS/Node.php create mode 100755 3rdparty/Sabre/DAV/FSExt/Directory.php create mode 100755 3rdparty/Sabre/DAV/FSExt/File.php create mode 100755 3rdparty/Sabre/DAV/FSExt/Node.php create mode 100755 3rdparty/Sabre/DAV/File.php create mode 100755 3rdparty/Sabre/DAV/ICollection.php create mode 100755 3rdparty/Sabre/DAV/IExtendedCollection.php create mode 100755 3rdparty/Sabre/DAV/IFile.php create mode 100755 3rdparty/Sabre/DAV/INode.php create mode 100755 3rdparty/Sabre/DAV/IProperties.php create mode 100755 3rdparty/Sabre/DAV/IQuota.php create mode 100755 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php create mode 100755 3rdparty/Sabre/DAV/Locks/Backend/FS.php create mode 100755 3rdparty/Sabre/DAV/Locks/Backend/File.php create mode 100755 3rdparty/Sabre/DAV/Locks/Backend/PDO.php create mode 100755 3rdparty/Sabre/DAV/Locks/LockInfo.php create mode 100755 3rdparty/Sabre/DAV/Locks/Plugin.php create mode 100755 3rdparty/Sabre/DAV/Mount/Plugin.php create mode 100755 3rdparty/Sabre/DAV/Node.php create mode 100755 3rdparty/Sabre/DAV/ObjectTree.php create mode 100755 3rdparty/Sabre/DAV/Property.php create mode 100755 3rdparty/Sabre/DAV/Property/GetLastModified.php create mode 100755 3rdparty/Sabre/DAV/Property/Href.php create mode 100755 3rdparty/Sabre/DAV/Property/HrefList.php create mode 100755 3rdparty/Sabre/DAV/Property/IHref.php create mode 100755 3rdparty/Sabre/DAV/Property/LockDiscovery.php create mode 100755 3rdparty/Sabre/DAV/Property/ResourceType.php create mode 100755 3rdparty/Sabre/DAV/Property/Response.php create mode 100755 3rdparty/Sabre/DAV/Property/ResponseList.php create mode 100755 3rdparty/Sabre/DAV/Property/SupportedLock.php create mode 100755 3rdparty/Sabre/DAV/Property/SupportedReportSet.php create mode 100755 3rdparty/Sabre/DAV/Server.php create mode 100755 3rdparty/Sabre/DAV/ServerPlugin.php create mode 100755 3rdparty/Sabre/DAV/SimpleCollection.php create mode 100755 3rdparty/Sabre/DAV/SimpleDirectory.php create mode 100755 3rdparty/Sabre/DAV/SimpleFile.php create mode 100755 3rdparty/Sabre/DAV/StringUtil.php create mode 100755 3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php create mode 100755 3rdparty/Sabre/DAV/Tree.php create mode 100755 3rdparty/Sabre/DAV/Tree/Filesystem.php create mode 100755 3rdparty/Sabre/DAV/URLUtil.php create mode 100755 3rdparty/Sabre/DAV/UUIDUtil.php create mode 100755 3rdparty/Sabre/DAV/Version.php create mode 100755 3rdparty/Sabre/DAV/XMLUtil.php create mode 100755 3rdparty/Sabre/DAV/includes.php create mode 100755 3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php create mode 100755 3rdparty/Sabre/DAVACL/Exception/AceConflict.php create mode 100755 3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php create mode 100755 3rdparty/Sabre/DAVACL/Exception/NoAbstract.php create mode 100755 3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php create mode 100755 3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php create mode 100755 3rdparty/Sabre/DAVACL/IACL.php create mode 100755 3rdparty/Sabre/DAVACL/IPrincipal.php create mode 100755 3rdparty/Sabre/DAVACL/IPrincipalBackend.php create mode 100755 3rdparty/Sabre/DAVACL/Plugin.php create mode 100755 3rdparty/Sabre/DAVACL/Principal.php create mode 100755 3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php create mode 100755 3rdparty/Sabre/DAVACL/PrincipalCollection.php create mode 100755 3rdparty/Sabre/DAVACL/Property/Acl.php create mode 100755 3rdparty/Sabre/DAVACL/Property/AclRestrictions.php create mode 100755 3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php create mode 100755 3rdparty/Sabre/DAVACL/Property/Principal.php create mode 100755 3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php create mode 100755 3rdparty/Sabre/DAVACL/Version.php create mode 100755 3rdparty/Sabre/DAVACL/includes.php create mode 100755 3rdparty/Sabre/HTTP/AWSAuth.php create mode 100755 3rdparty/Sabre/HTTP/AbstractAuth.php create mode 100755 3rdparty/Sabre/HTTP/BasicAuth.php create mode 100755 3rdparty/Sabre/HTTP/DigestAuth.php create mode 100755 3rdparty/Sabre/HTTP/Request.php create mode 100755 3rdparty/Sabre/HTTP/Response.php create mode 100755 3rdparty/Sabre/HTTP/Util.php create mode 100755 3rdparty/Sabre/HTTP/Version.php create mode 100755 3rdparty/Sabre/HTTP/includes.php create mode 100755 3rdparty/Sabre/VObject/Component.php create mode 100755 3rdparty/Sabre/VObject/Component/VAlarm.php create mode 100755 3rdparty/Sabre/VObject/Component/VCalendar.php create mode 100755 3rdparty/Sabre/VObject/Component/VEvent.php create mode 100755 3rdparty/Sabre/VObject/Component/VJournal.php create mode 100755 3rdparty/Sabre/VObject/Component/VTodo.php create mode 100755 3rdparty/Sabre/VObject/DateTimeParser.php create mode 100755 3rdparty/Sabre/VObject/Element.php create mode 100755 3rdparty/Sabre/VObject/Element/DateTime.php create mode 100755 3rdparty/Sabre/VObject/Element/MultiDateTime.php create mode 100755 3rdparty/Sabre/VObject/ElementList.php create mode 100755 3rdparty/Sabre/VObject/FreeBusyGenerator.php create mode 100755 3rdparty/Sabre/VObject/Node.php create mode 100755 3rdparty/Sabre/VObject/Parameter.php create mode 100755 3rdparty/Sabre/VObject/ParseException.php create mode 100755 3rdparty/Sabre/VObject/Property.php create mode 100755 3rdparty/Sabre/VObject/Property/DateTime.php create mode 100755 3rdparty/Sabre/VObject/Property/MultiDateTime.php create mode 100755 3rdparty/Sabre/VObject/Reader.php create mode 100755 3rdparty/Sabre/VObject/RecurrenceIterator.php create mode 100755 3rdparty/Sabre/VObject/Version.php create mode 100755 3rdparty/Sabre/VObject/WindowsTimezoneMap.php create mode 100755 3rdparty/Sabre/VObject/includes.php create mode 100755 3rdparty/Sabre/autoload.php diff --git a/3rdparty/Sabre.includes.php b/3rdparty/Sabre.includes.php new file mode 100755 index 00000000000..c1334373663 --- /dev/null +++ b/3rdparty/Sabre.includes.php @@ -0,0 +1,26 @@ + array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param string $calendarId + * @param array $mutations + * @return bool|array + */ + public function updateCalendar($calendarId, array $mutations) { + + return false; + + } + + /** + * Delete a calendar and all it's objects + * + * @param string $calendarId + * @return void + */ + abstract function deleteCalendar($calendarId); + + /** + * Returns all calendar objects within a calendar. + * + * Every item contains an array with the following keys: + * * id - unique identifier which will be used for subsequent updates + * * calendardata - The iCalendar-compatible calendar data + * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. + * * lastmodified - a timestamp of the last modification time + * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: + * ' "abcdef"') + * * calendarid - The calendarid as it was passed to this function. + * * size - The size of the calendar objects, in bytes. + * + * Note that the etag is optional, but it's highly encouraged to return for + * speed reasons. + * + * The calendardata is also optional. If it's not returned + * 'getCalendarObject' will be called later, which *is* expected to return + * calendardata. + * + * If neither etag or size are specified, the calendardata will be + * used/fetched to determine these numbers. If both are specified the + * amount of times this is needed is reduced by a great degree. + * + * @param string $calendarId + * @return array + */ + abstract function getCalendarObjects($calendarId); + + /** + * Returns information from a single calendar object, based on it's object + * uri. + * + * The returned array must have the same keys as getCalendarObjects. The + * 'calendardata' object is required here though, while it's not required + * for getCalendarObjects. + * + * @param string $calendarId + * @param string $objectUri + * @return array + */ + abstract function getCalendarObject($calendarId,$objectUri); + + /** + * Creates a new calendar object. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * @return void + */ + abstract function createCalendarObject($calendarId,$objectUri,$calendarData); + + /** + * Updates an existing calendarobject, based on it's uri. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * @return void + */ + abstract function updateCalendarObject($calendarId,$objectUri,$calendarData); + + /** + * Deletes an existing calendar object. + * + * @param string $calendarId + * @param string $objectUri + * @return void + */ + abstract function deleteCalendarObject($calendarId,$objectUri); + +} diff --git a/3rdparty/Sabre/CalDAV/Backend/PDO.php b/3rdparty/Sabre/CalDAV/Backend/PDO.php new file mode 100755 index 00000000000..ddacf940c74 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Backend/PDO.php @@ -0,0 +1,396 @@ + 'displayname', + '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', + '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', + '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', + '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', + ); + + /** + * Creates the backend + * + * @param PDO $pdo + * @param string $calendarTableName + * @param string $calendarObjectTableName + */ + public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') { + + $this->pdo = $pdo; + $this->calendarTableName = $calendarTableName; + $this->calendarObjectTableName = $calendarObjectTableName; + + } + + /** + * Returns a list of calendars for a principal. + * + * Every project is an array with the following keys: + * * id, a unique id that will be used by other functions to modify the + * calendar. This can be the same as the uri or a database key. + * * uri, which the basename of the uri with which the calendar is + * accessed. + * * principaluri. The owner of the calendar. Almost always the same as + * principalUri passed to this method. + * + * Furthermore it can contain webdav properties in clark notation. A very + * common one is '{DAV:}displayname'. + * + * @param string $principalUri + * @return array + */ + public function getCalendarsForUser($principalUri) { + + $fields = array_values($this->propertyMap); + $fields[] = 'id'; + $fields[] = 'uri'; + $fields[] = 'ctag'; + $fields[] = 'components'; + $fields[] = 'principaluri'; + + // Making fields a comma-delimited list + $fields = implode(', ', $fields); + $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM ".$this->calendarTableName." WHERE principaluri = ? ORDER BY calendarorder ASC"); + $stmt->execute(array($principalUri)); + + $calendars = array(); + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + + $components = array(); + if ($row['components']) { + $components = explode(',',$row['components']); + } + + $calendar = array( + 'id' => $row['id'], + 'uri' => $row['uri'], + 'principaluri' => $row['principaluri'], + '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0', + '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), + ); + + + foreach($this->propertyMap as $xmlName=>$dbName) { + $calendar[$xmlName] = $row[$dbName]; + } + + $calendars[] = $calendar; + + } + + return $calendars; + + } + + /** + * Creates a new calendar for a principal. + * + * If the creation was a success, an id must be returned that can be used to reference + * this calendar in other methods, such as updateCalendar + * + * @param string $principalUri + * @param string $calendarUri + * @param array $properties + * @return string + */ + public function createCalendar($principalUri, $calendarUri, array $properties) { + + $fieldNames = array( + 'principaluri', + 'uri', + 'ctag', + ); + $values = array( + ':principaluri' => $principalUri, + ':uri' => $calendarUri, + ':ctag' => 1, + ); + + // Default value + $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; + $fieldNames[] = 'components'; + if (!isset($properties[$sccs])) { + $values[':components'] = 'VEVENT,VTODO'; + } else { + if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { + throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); + } + $values[':components'] = implode(',',$properties[$sccs]->getValue()); + } + + foreach($this->propertyMap as $xmlName=>$dbName) { + if (isset($properties[$xmlName])) { + + $values[':' . $dbName] = $properties[$xmlName]; + $fieldNames[] = $dbName; + } + } + + $stmt = $this->pdo->prepare("INSERT INTO ".$this->calendarTableName." (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")"); + $stmt->execute($values); + + return $this->pdo->lastInsertId(); + + } + + /** + * Updates properties for a calendar. + * + * The mutations array uses the propertyName in clark-notation as key, + * and the array value for the property value. In the case a property + * should be deleted, the property value will be null. + * + * This method must be atomic. If one property cannot be changed, the + * entire operation must fail. + * + * If the operation was successful, true can be returned. + * If the operation failed, false can be returned. + * + * Deletion of a non-existent property is always successful. + * + * Lastly, it is optional to return detailed information about any + * failures. In this case an array should be returned with the following + * structure: + * + * array( + * 403 => array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param string $calendarId + * @param array $mutations + * @return bool|array + */ + public function updateCalendar($calendarId, array $mutations) { + + $newValues = array(); + $result = array( + 200 => array(), // Ok + 403 => array(), // Forbidden + 424 => array(), // Failed Dependency + ); + + $hasError = false; + + foreach($mutations as $propertyName=>$propertyValue) { + + // We don't know about this property. + if (!isset($this->propertyMap[$propertyName])) { + $hasError = true; + $result[403][$propertyName] = null; + unset($mutations[$propertyName]); + continue; + } + + $fieldName = $this->propertyMap[$propertyName]; + $newValues[$fieldName] = $propertyValue; + + } + + // If there were any errors we need to fail the request + if ($hasError) { + // Properties has the remaining properties + foreach($mutations as $propertyName=>$propertyValue) { + $result[424][$propertyName] = null; + } + + // Removing unused statuscodes for cleanliness + foreach($result as $status=>$properties) { + if (is_array($properties) && count($properties)===0) unset($result[$status]); + } + + return $result; + + } + + // Success + + // Now we're generating the sql query. + $valuesSql = array(); + foreach($newValues as $fieldName=>$value) { + $valuesSql[] = $fieldName . ' = ?'; + } + $valuesSql[] = 'ctag = ctag + 1'; + + $stmt = $this->pdo->prepare("UPDATE " . $this->calendarTableName . " SET " . implode(', ',$valuesSql) . " WHERE id = ?"); + $newValues['id'] = $calendarId; + $stmt->execute(array_values($newValues)); + + return true; + + } + + /** + * Delete a calendar and all it's objects + * + * @param string $calendarId + * @return void + */ + public function deleteCalendar($calendarId) { + + $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'); + $stmt->execute(array($calendarId)); + + $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?'); + $stmt->execute(array($calendarId)); + + } + + /** + * Returns all calendar objects within a calendar. + * + * Every item contains an array with the following keys: + * * id - unique identifier which will be used for subsequent updates + * * calendardata - The iCalendar-compatible calendar data + * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. + * * lastmodified - a timestamp of the last modification time + * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: + * ' "abcdef"') + * * calendarid - The calendarid as it was passed to this function. + * * size - The size of the calendar objects, in bytes. + * + * Note that the etag is optional, but it's highly encouraged to return for + * speed reasons. + * + * The calendardata is also optional. If it's not returned + * 'getCalendarObject' will be called later, which *is* expected to return + * calendardata. + * + * If neither etag or size are specified, the calendardata will be + * used/fetched to determine these numbers. If both are specified the + * amount of times this is needed is reduced by a great degree. + * + * @param string $calendarId + * @return array + */ + public function getCalendarObjects($calendarId) { + + $stmt = $this->pdo->prepare('SELECT * FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'); + $stmt->execute(array($calendarId)); + return $stmt->fetchAll(); + + } + + /** + * Returns information from a single calendar object, based on it's object + * uri. + * + * The returned array must have the same keys as getCalendarObjects. The + * 'calendardata' object is required here though, while it's not required + * for getCalendarObjects. + * + * @param string $calendarId + * @param string $objectUri + * @return array + */ + public function getCalendarObject($calendarId,$objectUri) { + + $stmt = $this->pdo->prepare('SELECT * FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?'); + $stmt->execute(array($calendarId, $objectUri)); + return $stmt->fetch(); + + } + + /** + * Creates a new calendar object. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * @return void + */ + public function createCalendarObject($calendarId,$objectUri,$calendarData) { + + $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified) VALUES (?,?,?,?)'); + $stmt->execute(array($calendarId,$objectUri,$calendarData,time())); + $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?'); + $stmt->execute(array($calendarId)); + + } + + /** + * Updates an existing calendarobject, based on it's uri. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * @return void + */ + public function updateCalendarObject($calendarId,$objectUri,$calendarData) { + + $stmt = $this->pdo->prepare('UPDATE '.$this->calendarObjectTableName.' SET calendardata = ?, lastmodified = ? WHERE calendarid = ? AND uri = ?'); + $stmt->execute(array($calendarData,time(),$calendarId,$objectUri)); + $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?'); + $stmt->execute(array($calendarId)); + + } + + /** + * Deletes an existing calendar object. + * + * @param string $calendarId + * @param string $objectUri + * @return void + */ + public function deleteCalendarObject($calendarId,$objectUri) { + + $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?'); + $stmt->execute(array($calendarId,$objectUri)); + $stmt = $this->pdo->prepare('UPDATE '. $this->calendarTableName .' SET ctag = ctag + 1 WHERE id = ?'); + $stmt->execute(array($calendarId)); + + } + + +} diff --git a/3rdparty/Sabre/CalDAV/Calendar.php b/3rdparty/Sabre/CalDAV/Calendar.php new file mode 100755 index 00000000000..623df2dd1b8 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Calendar.php @@ -0,0 +1,343 @@ +caldavBackend = $caldavBackend; + $this->principalBackend = $principalBackend; + $this->calendarInfo = $calendarInfo; + + + } + + /** + * Returns the name of the calendar + * + * @return string + */ + public function getName() { + + return $this->calendarInfo['uri']; + + } + + /** + * Updates properties such as the display name and description + * + * @param array $mutations + * @return array + */ + public function updateProperties($mutations) { + + return $this->caldavBackend->updateCalendar($this->calendarInfo['id'],$mutations); + + } + + /** + * Returns the list of properties + * + * @param array $requestedProperties + * @return array + */ + public function getProperties($requestedProperties) { + + $response = array(); + + foreach($requestedProperties as $prop) switch($prop) { + + case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data' : + $response[$prop] = new Sabre_CalDAV_Property_SupportedCalendarData(); + break; + case '{urn:ietf:params:xml:ns:caldav}supported-collation-set' : + $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); + break; + case '{DAV:}owner' : + $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,$this->calendarInfo['principaluri']); + break; + default : + if (isset($this->calendarInfo[$prop])) $response[$prop] = $this->calendarInfo[$prop]; + break; + + } + return $response; + + } + + /** + * Returns a calendar object + * + * The contained calendar objects are for example Events or Todo's. + * + * @param string $name + * @return Sabre_DAV_ICalendarObject + */ + public function getChild($name) { + + $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); + if (!$obj) throw new Sabre_DAV_Exception_NotFound('Calendar object not found'); + return new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); + + } + + /** + * Returns the full list of calendar objects + * + * @return array + */ + public function getChildren() { + + $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); + $children = array(); + foreach($objs as $obj) { + $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); + } + return $children; + + } + + /** + * Checks if a child-node exists. + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); + if (!$obj) + return false; + else + return true; + + } + + /** + * Creates a new directory + * + * We actually block this, as subdirectories are not allowed in calendars. + * + * @param string $name + * @return void + */ + public function createDirectory($name) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in calendar objects is not allowed'); + + } + + /** + * Creates a new file + * + * The contents of the new file must be a valid ICalendar string. + * + * @param string $name + * @param resource $calendarData + * @return string|null + */ + public function createFile($name,$calendarData = null) { + + if (is_resource($calendarData)) { + $calendarData = stream_get_contents($calendarData); + } + return $this->caldavBackend->createCalendarObject($this->calendarInfo['id'],$name,$calendarData); + + } + + /** + * Deletes the calendar. + * + * @return void + */ + public function delete() { + + $this->caldavBackend->deleteCalendar($this->calendarInfo['id']); + + } + + /** + * Renames the calendar. Note that most calendars use the + * {DAV:}displayname to display a name to display a name. + * + * @param string $newName + * @return void + */ + public function setName($newName) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming calendars is not yet supported'); + + } + + /** + * Returns the last modification date as a unix timestamp. + * + * @return void + */ + public function getLastModified() { + + return null; + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->calendarInfo['principaluri']; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', + 'protected' => true, + ), + array( + 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + 'principal' => '{DAV:}authenticated', + 'protected' => true, + ), + + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + $default = Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet(); + + // We need to inject 'read-free-busy' in the tree, aggregated under + // {DAV:}read. + foreach($default['aggregates'] as &$agg) { + + if ($agg['privilege'] !== '{DAV:}read') continue; + + $agg['aggregates'][] = array( + 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + ); + + } + return $default; + + } + +} diff --git a/3rdparty/Sabre/CalDAV/CalendarObject.php b/3rdparty/Sabre/CalDAV/CalendarObject.php new file mode 100755 index 00000000000..72f0a578d16 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/CalendarObject.php @@ -0,0 +1,273 @@ +caldavBackend = $caldavBackend; + + if (!isset($objectData['calendarid'])) { + throw new InvalidArgumentException('The objectData argument must contain a \'calendarid\' property'); + } + if (!isset($objectData['uri'])) { + throw new InvalidArgumentException('The objectData argument must contain an \'uri\' property'); + } + + $this->calendarInfo = $calendarInfo; + $this->objectData = $objectData; + + } + + /** + * Returns the uri for this object + * + * @return string + */ + public function getName() { + + return $this->objectData['uri']; + + } + + /** + * Returns the ICalendar-formatted object + * + * @return string + */ + public function get() { + + // Pre-populating the 'calendardata' is optional, if we don't have it + // already we fetch it from the backend. + if (!isset($this->objectData['calendardata'])) { + $this->objectData = $this->caldavBackend->getCalendarObject($this->objectData['calendarid'], $this->objectData['uri']); + } + return $this->objectData['calendardata']; + + } + + /** + * Updates the ICalendar-formatted object + * + * @param string $calendarData + * @return void + */ + public function put($calendarData) { + + if (is_resource($calendarData)) { + $calendarData = stream_get_contents($calendarData); + } + $etag = $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'],$this->objectData['uri'],$calendarData); + $this->objectData['calendardata'] = $calendarData; + $this->objectData['etag'] = $etag; + + return $etag; + + } + + /** + * Deletes the calendar object + * + * @return void + */ + public function delete() { + + $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'],$this->objectData['uri']); + + } + + /** + * Returns the mime content-type + * + * @return string + */ + public function getContentType() { + + return 'text/calendar'; + + } + + /** + * Returns an ETag for this object. + * + * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. + * + * @return string + */ + public function getETag() { + + if (isset($this->objectData['etag'])) { + return $this->objectData['etag']; + } else { + return '"' . md5($this->get()). '"'; + } + + } + + /** + * Returns the last modification date as a unix timestamp + * + * @return time + */ + public function getLastModified() { + + return $this->objectData['lastmodified']; + + } + + /** + * Returns the size of this object in bytes + * + * @return int + */ + public function getSize() { + + if (array_key_exists('size',$this->objectData)) { + return $this->objectData['size']; + } else { + return strlen($this->get()); + } + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->calendarInfo['principaluri']; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', + 'protected' => true, + ), + + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} + diff --git a/3rdparty/Sabre/CalDAV/CalendarQueryParser.php b/3rdparty/Sabre/CalDAV/CalendarQueryParser.php new file mode 100755 index 00000000000..bd0d343382f --- /dev/null +++ b/3rdparty/Sabre/CalDAV/CalendarQueryParser.php @@ -0,0 +1,296 @@ +dom = $dom; + + $this->xpath = new DOMXPath($dom); + $this->xpath->registerNameSpace('cal',Sabre_CalDAV_Plugin::NS_CALDAV); + $this->xpath->registerNameSpace('dav','urn:DAV'); + + } + + /** + * Parses the request. + * + * @return void + */ + public function parse() { + + $filterNode = null; + + $filter = $this->xpath->query('/cal:calendar-query/cal:filter'); + if ($filter->length !== 1) { + throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); + } + + $compFilters = $this->parseCompFilters($filter->item(0)); + if (count($compFilters)!==1) { + throw new Sabre_DAV_Exception_BadRequest('There must be exactly 1 top-level comp-filter.'); + } + + $this->filters = $compFilters[0]; + $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); + + $expand = $this->xpath->query('/cal:calendar-query/dav:prop/cal:calendar-data/cal:expand'); + if ($expand->length>0) { + $this->expand = $this->parseExpand($expand->item(0)); + } + + + } + + /** + * Parses all the 'comp-filter' elements from a node + * + * @param DOMElement $parentNode + * @return array + */ + protected function parseCompFilters(DOMElement $parentNode) { + + $compFilterNodes = $this->xpath->query('cal:comp-filter', $parentNode); + $result = array(); + + for($ii=0; $ii < $compFilterNodes->length; $ii++) { + + $compFilterNode = $compFilterNodes->item($ii); + + $compFilter = array(); + $compFilter['name'] = $compFilterNode->getAttribute('name'); + $compFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $compFilterNode)->length>0; + $compFilter['comp-filters'] = $this->parseCompFilters($compFilterNode); + $compFilter['prop-filters'] = $this->parsePropFilters($compFilterNode); + $compFilter['time-range'] = $this->parseTimeRange($compFilterNode); + + if ($compFilter['time-range'] && !in_array($compFilter['name'],array( + 'VEVENT', + 'VTODO', + 'VJOURNAL', + 'VFREEBUSY', + 'VALARM', + ))) { + throw new Sabre_DAV_Exception_BadRequest('The time-range filter is not defined for the ' . $compFilter['name'] . ' component'); + }; + + $result[] = $compFilter; + + } + + return $result; + + } + + /** + * Parses all the prop-filter elements from a node + * + * @param DOMElement $parentNode + * @return array + */ + protected function parsePropFilters(DOMElement $parentNode) { + + $propFilterNodes = $this->xpath->query('cal:prop-filter', $parentNode); + $result = array(); + + for ($ii=0; $ii < $propFilterNodes->length; $ii++) { + + $propFilterNode = $propFilterNodes->item($ii); + $propFilter = array(); + $propFilter['name'] = $propFilterNode->getAttribute('name'); + $propFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $propFilterNode)->length>0; + $propFilter['param-filters'] = $this->parseParamFilters($propFilterNode); + $propFilter['text-match'] = $this->parseTextMatch($propFilterNode); + $propFilter['time-range'] = $this->parseTimeRange($propFilterNode); + + $result[] = $propFilter; + + } + + return $result; + + } + + /** + * Parses the param-filter element + * + * @param DOMElement $parentNode + * @return array + */ + protected function parseParamFilters(DOMElement $parentNode) { + + $paramFilterNodes = $this->xpath->query('cal:param-filter', $parentNode); + $result = array(); + + for($ii=0;$ii<$paramFilterNodes->length;$ii++) { + + $paramFilterNode = $paramFilterNodes->item($ii); + $paramFilter = array(); + $paramFilter['name'] = $paramFilterNode->getAttribute('name'); + $paramFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $paramFilterNode)->length>0; + $paramFilter['text-match'] = $this->parseTextMatch($paramFilterNode); + + $result[] = $paramFilter; + + } + + return $result; + + } + + /** + * Parses the text-match element + * + * @param DOMElement $parentNode + * @return array|null + */ + protected function parseTextMatch(DOMElement $parentNode) { + + $textMatchNodes = $this->xpath->query('cal:text-match', $parentNode); + + if ($textMatchNodes->length === 0) + return null; + + $textMatchNode = $textMatchNodes->item(0); + $negateCondition = $textMatchNode->getAttribute('negate-condition'); + $negateCondition = $negateCondition==='yes'; + $collation = $textMatchNode->getAttribute('collation'); + if (!$collation) $collation = 'i;ascii-casemap'; + + return array( + 'negate-condition' => $negateCondition, + 'collation' => $collation, + 'value' => $textMatchNode->nodeValue + ); + + } + + /** + * Parses the time-range element + * + * @param DOMElement $parentNode + * @return array|null + */ + protected function parseTimeRange(DOMElement $parentNode) { + + $timeRangeNodes = $this->xpath->query('cal:time-range', $parentNode); + if ($timeRangeNodes->length === 0) { + return null; + } + + $timeRangeNode = $timeRangeNodes->item(0); + + if ($start = $timeRangeNode->getAttribute('start')) { + $start = Sabre_VObject_DateTimeParser::parseDateTime($start); + } else { + $start = null; + } + if ($end = $timeRangeNode->getAttribute('end')) { + $end = Sabre_VObject_DateTimeParser::parseDateTime($end); + } else { + $end = null; + } + + if (!is_null($start) && !is_null($end) && $end <= $start) { + throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the time-range filter'); + } + + return array( + 'start' => $start, + 'end' => $end, + ); + + } + + /** + * Parses the CALDAV:expand element + * + * @param DOMElement $parentNode + * @return void + */ + protected function parseExpand(DOMElement $parentNode) { + + $start = $parentNode->getAttribute('start'); + if(!$start) { + throw new Sabre_DAV_Exception_BadRequest('The "start" attribute is required for the CALDAV:expand element'); + } + $start = Sabre_VObject_DateTimeParser::parseDateTime($start); + + $end = $parentNode->getAttribute('end'); + if(!$end) { + throw new Sabre_DAV_Exception_BadRequest('The "end" attribute is required for the CALDAV:expand element'); + } + $end = Sabre_VObject_DateTimeParser::parseDateTime($end); + + if ($end <= $start) { + throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the expand element.'); + } + + return array( + 'start' => $start, + 'end' => $end, + ); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/CalendarQueryValidator.php b/3rdparty/Sabre/CalDAV/CalendarQueryValidator.php new file mode 100755 index 00000000000..1bb6b5d53fa --- /dev/null +++ b/3rdparty/Sabre/CalDAV/CalendarQueryValidator.php @@ -0,0 +1,347 @@ +name !== $filters['name']) { + return false; + } + + return + $this->validateCompFilters($vObject, $filters['comp-filters']) && + $this->validatePropFilters($vObject, $filters['prop-filters']); + + + } + + /** + * This method checks the validity of comp-filters. + * + * A list of comp-filters needs to be specified. Also the parent of the + * component we're checking should be specified, not the component to check + * itself. + * + * @param Sabre_VObject_Component $parent + * @param array $filters + * @return bool + */ + protected function validateCompFilters(Sabre_VObject_Component $parent, array $filters) { + + foreach($filters as $filter) { + + $isDefined = isset($parent->$filter['name']); + + if ($filter['is-not-defined']) { + + if ($isDefined) { + return false; + } else { + continue; + } + + } + if (!$isDefined) { + return false; + } + + if ($filter['time-range']) { + foreach($parent->$filter['name'] as $subComponent) { + if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { + continue 2; + } + } + return false; + } + + if (!$filter['comp-filters'] && !$filter['prop-filters']) { + continue; + } + + // If there are sub-filters, we need to find at least one component + // for which the subfilters hold true. + foreach($parent->$filter['name'] as $subComponent) { + + if ( + $this->validateCompFilters($subComponent, $filter['comp-filters']) && + $this->validatePropFilters($subComponent, $filter['prop-filters'])) { + // We had a match, so this comp-filter succeeds + continue 2; + } + + } + + // If we got here it means there were sub-comp-filters or + // sub-prop-filters and there was no match. This means this filter + // needs to return false. + return false; + + } + + // If we got here it means we got through all comp-filters alive so the + // filters were all true. + return true; + + } + + /** + * This method checks the validity of prop-filters. + * + * A list of prop-filters needs to be specified. Also the parent of the + * property we're checking should be specified, not the property to check + * itself. + * + * @param Sabre_VObject_Component $parent + * @param array $filters + * @return bool + */ + protected function validatePropFilters(Sabre_VObject_Component $parent, array $filters) { + + foreach($filters as $filter) { + + $isDefined = isset($parent->$filter['name']); + + if ($filter['is-not-defined']) { + + if ($isDefined) { + return false; + } else { + continue; + } + + } + if (!$isDefined) { + return false; + } + + if ($filter['time-range']) { + foreach($parent->$filter['name'] as $subComponent) { + if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { + continue 2; + } + } + return false; + } + + if (!$filter['param-filters'] && !$filter['text-match']) { + continue; + } + + // If there are sub-filters, we need to find at least one property + // for which the subfilters hold true. + foreach($parent->$filter['name'] as $subComponent) { + + if( + $this->validateParamFilters($subComponent, $filter['param-filters']) && + (!$filter['text-match'] || $this->validateTextMatch($subComponent, $filter['text-match'])) + ) { + // We had a match, so this prop-filter succeeds + continue 2; + } + + } + + // If we got here it means there were sub-param-filters or + // text-match filters and there was no match. This means the + // filter needs to return false. + return false; + + } + + // If we got here it means we got through all prop-filters alive so the + // filters were all true. + return true; + + } + + /** + * This method checks the validity of param-filters. + * + * A list of param-filters needs to be specified. Also the parent of the + * parameter we're checking should be specified, not the parameter to check + * itself. + * + * @param Sabre_VObject_Property $parent + * @param array $filters + * @return bool + */ + protected function validateParamFilters(Sabre_VObject_Property $parent, array $filters) { + + foreach($filters as $filter) { + + $isDefined = isset($parent[$filter['name']]); + + if ($filter['is-not-defined']) { + + if ($isDefined) { + return false; + } else { + continue; + } + + } + if (!$isDefined) { + return false; + } + + if (!$filter['text-match']) { + continue; + } + + // If there are sub-filters, we need to find at least one parameter + // for which the subfilters hold true. + foreach($parent[$filter['name']] as $subParam) { + + if($this->validateTextMatch($subParam,$filter['text-match'])) { + // We had a match, so this param-filter succeeds + continue 2; + } + + } + + // If we got here it means there was a text-match filter and there + // were no matches. This means the filter needs to return false. + return false; + + } + + // If we got here it means we got through all param-filters alive so the + // filters were all true. + return true; + + } + + /** + * This method checks the validity of a text-match. + * + * A single text-match should be specified as well as the specific property + * or parameter we need to validate. + * + * @param Sabre_VObject_Node $parent + * @param array $textMatch + * @return bool + */ + protected function validateTextMatch(Sabre_VObject_Node $parent, array $textMatch) { + + $value = (string)$parent; + + $isMatching = Sabre_DAV_StringUtil::textMatch($value, $textMatch['value'], $textMatch['collation']); + + return ($textMatch['negate-condition'] xor $isMatching); + + } + + /** + * Validates if a component matches the given time range. + * + * This is all based on the rules specified in rfc4791, which are quite + * complex. + * + * @param Sabre_VObject_Node $component + * @param DateTime $start + * @param DateTime $end + * @return bool + */ + protected function validateTimeRange(Sabre_VObject_Node $component, $start, $end) { + + if (is_null($start)) { + $start = new DateTime('1900-01-01'); + } + if (is_null($end)) { + $end = new DateTime('3000-01-01'); + } + + switch($component->name) { + + case 'VEVENT' : + case 'VTODO' : + case 'VJOURNAL' : + + return $component->isInTimeRange($start, $end); + + case 'VALARM' : + + // If the valarm is wrapped in a recurring event, we need to + // expand the recursions, and validate each. + // + // Our datamodel doesn't easily allow us to do this straight + // in the VALARM component code, so this is a hack, and an + // expensive one too. + if ($component->parent->name === 'VEVENT' && $component->parent->RRULE) { + // Fire up the iterator! + $it = new Sabre_VObject_RecurrenceIterator($component->parent->parent, (string)$component->parent->UID); + while($it->valid()) { + $expandedEvent = $it->getEventObject(); + + // We need to check from these expanded alarms, which + // one is the first to trigger. Based on this, we can + // determine if we can 'give up' expanding events. + $firstAlarm = null; + foreach($expandedEvent->VALARM as $expandedAlarm) { + $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime(); + if (!$firstAlarm || $effectiveTrigger < $firstAlarm) { + $firstAlarm = $effectiveTrigger; + } + if ($expandedAlarm->isInTimeRange($start, $end)) { + return true; + } + + } + if ($firstAlarm > $end) { + return false; + } + $it->next(); + } + return false; + } else { + return $component->isInTimeRange($start, $end); + } + + case 'VFREEBUSY' : + throw new Sabre_DAV_Exception_NotImplemented('time-range filters are currently not supported on ' . $component->name . ' components'); + + case 'COMPLETED' : + case 'CREATED' : + case 'DTEND' : + case 'DTSTAMP' : + case 'DTSTART' : + case 'DUE' : + case 'LAST-MODIFIED' : + return ($start <= $component->getDateTime() && $end >= $component->getDateTime()); + + + + default : + throw new Sabre_DAV_Exception_BadRequest('You cannot create a time-range filter on a ' . $component->name . ' component'); + + } + + } + +} diff --git a/3rdparty/Sabre/CalDAV/CalendarRootNode.php b/3rdparty/Sabre/CalDAV/CalendarRootNode.php new file mode 100755 index 00000000000..3907913cc78 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/CalendarRootNode.php @@ -0,0 +1,75 @@ +caldavBackend = $caldavBackend; + + } + + /** + * Returns the nodename + * + * We're overriding this, because the default will be the 'principalPrefix', + * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT + * + * @return string + */ + public function getName() { + + return Sabre_CalDAV_Plugin::CALENDAR_ROOT; + + } + + /** + * This method returns a node for a principal. + * + * The passed array contains principal information, and is guaranteed to + * at least contain a uri item. Other properties may or may not be + * supplied by the authentication backend. + * + * @param array $principal + * @return Sabre_DAV_INode + */ + public function getChildForPrincipal(array $principal) { + + return new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->caldavBackend, $principal['uri']); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/ICSExportPlugin.php b/3rdparty/Sabre/CalDAV/ICSExportPlugin.php new file mode 100755 index 00000000000..ec42b406b2f --- /dev/null +++ b/3rdparty/Sabre/CalDAV/ICSExportPlugin.php @@ -0,0 +1,139 @@ +server = $server; + $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); + + } + + /** + * 'beforeMethod' event handles. This event handles intercepts GET requests ending + * with ?export + * + * @param string $method + * @param string $uri + * @return bool + */ + public function beforeMethod($method, $uri) { + + if ($method!='GET') return; + if ($this->server->httpRequest->getQueryString()!='export') return; + + // splitting uri + list($uri) = explode('?',$uri,2); + + $node = $this->server->tree->getNodeForPath($uri); + + if (!($node instanceof Sabre_CalDAV_Calendar)) return; + + // Checking ACL, if available. + if ($aclPlugin = $this->server->getPlugin('acl')) { + $aclPlugin->checkPrivileges($uri, '{DAV:}read'); + } + + $this->server->httpResponse->setHeader('Content-Type','text/calendar'); + $this->server->httpResponse->sendStatus(200); + + $nodes = $this->server->getPropertiesForPath($uri, array( + '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data', + ),1); + + $this->server->httpResponse->sendBody($this->generateICS($nodes)); + + // Returning false to break the event chain + return false; + + } + + /** + * Merges all calendar objects, and builds one big ics export + * + * @param array $nodes + * @return string + */ + public function generateICS(array $nodes) { + + $calendar = new Sabre_VObject_Component('vcalendar'); + $calendar->version = '2.0'; + if (Sabre_DAV_Server::$exposeVersion) { + $calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN'; + } else { + $calendar->prodid = '-//SabreDAV//SabreDAV//EN'; + } + $calendar->calscale = 'GREGORIAN'; + + $collectedTimezones = array(); + + $timezones = array(); + $objects = array(); + + foreach($nodes as $node) { + + if (!isset($node[200]['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'])) { + continue; + } + $nodeData = $node[200]['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data']; + + $nodeComp = Sabre_VObject_Reader::read($nodeData); + + foreach($nodeComp->children() as $child) { + + switch($child->name) { + case 'VEVENT' : + case 'VTODO' : + case 'VJOURNAL' : + $objects[] = $child; + break; + + // VTIMEZONE is special, because we need to filter out the duplicates + case 'VTIMEZONE' : + // Naively just checking tzid. + if (in_array((string)$child->TZID, $collectedTimezones)) continue; + + $timezones[] = $child; + $collectedTimezones[] = $child->TZID; + break; + + } + + } + + } + + foreach($timezones as $tz) $calendar->add($tz); + foreach($objects as $obj) $calendar->add($obj); + + return $calendar->serialize(); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/ICalendar.php b/3rdparty/Sabre/CalDAV/ICalendar.php new file mode 100755 index 00000000000..15d51ebcf79 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/ICalendar.php @@ -0,0 +1,18 @@ +imipHandler = $imipHandler; + + } + + /** + * Use this method to tell the server this plugin defines additional + * HTTP methods. + * + * This method is passed a uri. It should only return HTTP methods that are + * available for the specified uri. + * + * @param string $uri + * @return array + */ + public function getHTTPMethods($uri) { + + // The MKCALENDAR is only available on unmapped uri's, whose + // parents extend IExtendedCollection + list($parent, $name) = Sabre_DAV_URLUtil::splitPath($uri); + + $node = $this->server->tree->getNodeForPath($parent); + + if ($node instanceof Sabre_DAV_IExtendedCollection) { + try { + $node->getChild($name); + } catch (Sabre_DAV_Exception_NotFound $e) { + return array('MKCALENDAR'); + } + } + return array(); + + } + + /** + * Returns a list of features for the DAV: HTTP header. + * + * @return array + */ + public function getFeatures() { + + return array('calendar-access', 'calendar-proxy'); + + } + + /** + * Returns a plugin name. + * + * Using this name other plugins will be able to access other plugins + * using Sabre_DAV_Server::getPlugin + * + * @return string + */ + public function getPluginName() { + + return 'caldav'; + + } + + /** + * Returns a list of reports this plugin supports. + * + * This will be used in the {DAV:}supported-report-set property. + * Note that you still need to subscribe to the 'report' event to actually + * implement them + * + * @param string $uri + * @return array + */ + public function getSupportedReportSet($uri) { + + $node = $this->server->tree->getNodeForPath($uri); + + $reports = array(); + if ($node instanceof Sabre_CalDAV_ICalendar || $node instanceof Sabre_CalDAV_ICalendarObject) { + $reports[] = '{' . self::NS_CALDAV . '}calendar-multiget'; + $reports[] = '{' . self::NS_CALDAV . '}calendar-query'; + } + if ($node instanceof Sabre_CalDAV_ICalendar) { + $reports[] = '{' . self::NS_CALDAV . '}free-busy-query'; + } + return $reports; + + } + + /** + * Initializes the plugin + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + + $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); + //$server->subscribeEvent('unknownMethod',array($this,'unknownMethod2'),1000); + $server->subscribeEvent('report',array($this,'report')); + $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); + $server->subscribeEvent('onHTMLActionsPanel', array($this,'htmlActionsPanel')); + $server->subscribeEvent('onBrowserPostAction', array($this,'browserPostAction')); + $server->subscribeEvent('beforeWriteContent', array($this, 'beforeWriteContent')); + $server->subscribeEvent('beforeCreateFile', array($this, 'beforeCreateFile')); + + $server->xmlNamespaces[self::NS_CALDAV] = 'cal'; + $server->xmlNamespaces[self::NS_CALENDARSERVER] = 'cs'; + + $server->propertyMap['{' . self::NS_CALDAV . '}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; + + $server->resourceTypeMapping['Sabre_CalDAV_ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar'; + $server->resourceTypeMapping['Sabre_CalDAV_Schedule_IOutbox'] = '{urn:ietf:params:xml:ns:caldav}schedule-outbox'; + $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read'; + $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write'; + + array_push($server->protectedProperties, + + '{' . self::NS_CALDAV . '}supported-calendar-component-set', + '{' . self::NS_CALDAV . '}supported-calendar-data', + '{' . self::NS_CALDAV . '}max-resource-size', + '{' . self::NS_CALDAV . '}min-date-time', + '{' . self::NS_CALDAV . '}max-date-time', + '{' . self::NS_CALDAV . '}max-instances', + '{' . self::NS_CALDAV . '}max-attendees-per-instance', + '{' . self::NS_CALDAV . '}calendar-home-set', + '{' . self::NS_CALDAV . '}supported-collation-set', + '{' . self::NS_CALDAV . '}calendar-data', + + // scheduling extension + '{' . self::NS_CALDAV . '}schedule-inbox-URL', + '{' . self::NS_CALDAV . '}schedule-outbox-URL', + '{' . self::NS_CALDAV . '}calendar-user-address-set', + '{' . self::NS_CALDAV . '}calendar-user-type', + + // CalendarServer extensions + '{' . self::NS_CALENDARSERVER . '}getctag', + '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for', + '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for' + + ); + } + + /** + * This function handles support for the MKCALENDAR method + * + * @param string $method + * @param string $uri + * @return bool + */ + public function unknownMethod($method, $uri) { + + switch ($method) { + case 'MKCALENDAR' : + $this->httpMkCalendar($uri); + // false is returned to stop the propagation of the + // unknownMethod event. + return false; + case 'POST' : + // Checking if we're talking to an outbox + try { + $node = $this->server->tree->getNodeForPath($uri); + } catch (Sabre_DAV_Exception_NotFound $e) { + return; + } + if (!$node instanceof Sabre_CalDAV_Schedule_IOutbox) + return; + + $this->outboxRequest($node); + return false; + + } + + } + + /** + * This functions handles REPORT requests specific to CalDAV + * + * @param string $reportName + * @param DOMNode $dom + * @return bool + */ + public function report($reportName,$dom) { + + switch($reportName) { + case '{'.self::NS_CALDAV.'}calendar-multiget' : + $this->calendarMultiGetReport($dom); + return false; + case '{'.self::NS_CALDAV.'}calendar-query' : + $this->calendarQueryReport($dom); + return false; + case '{'.self::NS_CALDAV.'}free-busy-query' : + $this->freeBusyQueryReport($dom); + return false; + + } + + + } + + /** + * This function handles the MKCALENDAR HTTP method, which creates + * a new calendar. + * + * @param string $uri + * @return void + */ + public function httpMkCalendar($uri) { + + // Due to unforgivable bugs in iCal, we're completely disabling MKCALENDAR support + // for clients matching iCal in the user agent + //$ua = $this->server->httpRequest->getHeader('User-Agent'); + //if (strpos($ua,'iCal/')!==false) { + // throw new Sabre_DAV_Exception_Forbidden('iCal has major bugs in it\'s RFC3744 support. Therefore we are left with no other choice but disabling this feature.'); + //} + + $body = $this->server->httpRequest->getBody(true); + $properties = array(); + + if ($body) { + + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); + + foreach($dom->firstChild->childNodes as $child) { + + if (Sabre_DAV_XMLUtil::toClarkNotation($child)!=='{DAV:}set') continue; + foreach(Sabre_DAV_XMLUtil::parseProperties($child,$this->server->propertyMap) as $k=>$prop) { + $properties[$k] = $prop; + } + + } + } + + $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); + + $this->server->createCollection($uri,$resourceType,$properties); + + $this->server->httpResponse->sendStatus(201); + $this->server->httpResponse->setHeader('Content-Length',0); + } + + /** + * beforeGetProperties + * + * This method handler is invoked before any after properties for a + * resource are fetched. This allows us to add in any CalDAV specific + * properties. + * + * @param string $path + * @param Sabre_DAV_INode $node + * @param array $requestedProperties + * @param array $returnedProperties + * @return void + */ + public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { + + if ($node instanceof Sabre_DAVACL_IPrincipal) { + + // calendar-home-set property + $calHome = '{' . self::NS_CALDAV . '}calendar-home-set'; + if (in_array($calHome,$requestedProperties)) { + $principalId = $node->getName(); + $calendarHomePath = self::CALENDAR_ROOT . '/' . $principalId . '/'; + unset($requestedProperties[$calHome]); + $returnedProperties[200][$calHome] = new Sabre_DAV_Property_Href($calendarHomePath); + } + + // schedule-outbox-URL property + $scheduleProp = '{' . self::NS_CALDAV . '}schedule-outbox-URL'; + if (in_array($scheduleProp,$requestedProperties)) { + $principalId = $node->getName(); + $outboxPath = self::CALENDAR_ROOT . '/' . $principalId . '/outbox'; + unset($requestedProperties[$scheduleProp]); + $returnedProperties[200][$scheduleProp] = new Sabre_DAV_Property_Href($outboxPath); + } + + // calendar-user-address-set property + $calProp = '{' . self::NS_CALDAV . '}calendar-user-address-set'; + if (in_array($calProp,$requestedProperties)) { + + $addresses = $node->getAlternateUriSet(); + $addresses[] = $this->server->getBaseUri() . $node->getPrincipalUrl(); + unset($requestedProperties[$calProp]); + $returnedProperties[200][$calProp] = new Sabre_DAV_Property_HrefList($addresses, false); + + } + + // These two properties are shortcuts for ical to easily find + // other principals this principal has access to. + $propRead = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for'; + $propWrite = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for'; + if (in_array($propRead,$requestedProperties) || in_array($propWrite,$requestedProperties)) { + + $membership = $node->getGroupMembership(); + $readList = array(); + $writeList = array(); + + foreach($membership as $group) { + + $groupNode = $this->server->tree->getNodeForPath($group); + + // If the node is either ap proxy-read or proxy-write + // group, we grab the parent principal and add it to the + // list. + if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyRead) { + list($readList[]) = Sabre_DAV_URLUtil::splitPath($group); + } + if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyWrite) { + list($writeList[]) = Sabre_DAV_URLUtil::splitPath($group); + } + + } + if (in_array($propRead,$requestedProperties)) { + unset($requestedProperties[$propRead]); + $returnedProperties[200][$propRead] = new Sabre_DAV_Property_HrefList($readList); + } + if (in_array($propWrite,$requestedProperties)) { + unset($requestedProperties[$propWrite]); + $returnedProperties[200][$propWrite] = new Sabre_DAV_Property_HrefList($writeList); + } + + } + + } // instanceof IPrincipal + + + if ($node instanceof Sabre_CalDAV_ICalendarObject) { + // The calendar-data property is not supposed to be a 'real' + // property, but in large chunks of the spec it does act as such. + // Therefore we simply expose it as a property. + $calDataProp = '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'; + if (in_array($calDataProp, $requestedProperties)) { + unset($requestedProperties[$calDataProp]); + $val = $node->get(); + if (is_resource($val)) + $val = stream_get_contents($val); + + // Taking out \r to not screw up the xml output + $returnedProperties[200][$calDataProp] = str_replace("\r","", $val); + + } + } + + } + + /** + * This function handles the calendar-multiget REPORT. + * + * This report is used by the client to fetch the content of a series + * of urls. Effectively avoiding a lot of redundant requests. + * + * @param DOMNode $dom + * @return void + */ + public function calendarMultiGetReport($dom) { + + $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); + $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); + + $xpath = new DOMXPath($dom); + $xpath->registerNameSpace('cal',Sabre_CalDAV_Plugin::NS_CALDAV); + $xpath->registerNameSpace('dav','urn:DAV'); + + $expand = $xpath->query('/cal:calendar-multiget/dav:prop/cal:calendar-data/cal:expand'); + if ($expand->length>0) { + $expandElem = $expand->item(0); + $start = $expandElem->getAttribute('start'); + $end = $expandElem->getAttribute('end'); + if(!$start || !$end) { + throw new Sabre_DAV_Exception_BadRequest('The "start" and "end" attributes are required for the CALDAV:expand element'); + } + $start = Sabre_VObject_DateTimeParser::parseDateTime($start); + $end = Sabre_VObject_DateTimeParser::parseDateTime($end); + + if ($end <= $start) { + throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the expand element.'); + } + + $expand = true; + + } else { + + $expand = false; + + } + + foreach($hrefElems as $elem) { + $uri = $this->server->calculateUri($elem->nodeValue); + list($objProps) = $this->server->getPropertiesForPath($uri,$properties); + + if ($expand && isset($objProps[200]['{' . self::NS_CALDAV . '}calendar-data'])) { + $vObject = Sabre_VObject_Reader::read($objProps[200]['{' . self::NS_CALDAV . '}calendar-data']); + $vObject->expand($start, $end); + $objProps[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); + } + + $propertyList[]=$objProps; + + } + + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); + + } + + /** + * This function handles the calendar-query REPORT + * + * This report is used by clients to request calendar objects based on + * complex conditions. + * + * @param DOMNode $dom + * @return void + */ + public function calendarQueryReport($dom) { + + $parser = new Sabre_CalDAV_CalendarQueryParser($dom); + $parser->parse(); + + $requestedCalendarData = true; + $requestedProperties = $parser->requestedProperties; + + if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar-data', $requestedProperties)) { + + // We always retrieve calendar-data, as we need it for filtering. + $requestedProperties[] = '{urn:ietf:params:xml:ns:caldav}calendar-data'; + + // If calendar-data wasn't explicitly requested, we need to remove + // it after processing. + $requestedCalendarData = false; + } + + // These are the list of nodes that potentially match the requirement + $candidateNodes = $this->server->getPropertiesForPath( + $this->server->getRequestUri(), + $requestedProperties, + $this->server->getHTTPDepth(0) + ); + + $verifiedNodes = array(); + + $validator = new Sabre_CalDAV_CalendarQueryValidator(); + + foreach($candidateNodes as $node) { + + // If the node didn't have a calendar-data property, it must not be a calendar object + if (!isset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) + continue; + + $vObject = Sabre_VObject_Reader::read($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); + if ($validator->validate($vObject,$parser->filters)) { + + if (!$requestedCalendarData) { + unset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); + } + if ($parser->expand) { + $vObject->expand($parser->expand['start'], $parser->expand['end']); + $node[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); + } + $verifiedNodes[] = $node; + } + + } + + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendBody($this->server->generateMultiStatus($verifiedNodes)); + + } + + /** + * This method is responsible for parsing the request and generating the + * response for the CALDAV:free-busy-query REPORT. + * + * @param DOMNode $dom + * @return void + */ + protected function freeBusyQueryReport(DOMNode $dom) { + + $start = null; + $end = null; + + foreach($dom->firstChild->childNodes as $childNode) { + + $clark = Sabre_DAV_XMLUtil::toClarkNotation($childNode); + if ($clark == '{' . self::NS_CALDAV . '}time-range') { + $start = $childNode->getAttribute('start'); + $end = $childNode->getAttribute('end'); + break; + } + + } + if ($start) { + $start = Sabre_VObject_DateTimeParser::parseDateTime($start); + } + if ($end) { + $end = Sabre_VObject_DateTimeParser::parseDateTime($end); + } + + if (!$start && !$end) { + throw new Sabre_DAV_Exception_BadRequest('The freebusy report must have a time-range filter'); + } + $acl = $this->server->getPlugin('acl'); + + if (!$acl) { + throw new Sabre_DAV_Exception('The ACL plugin must be loaded for free-busy queries to work'); + } + $uri = $this->server->getRequestUri(); + $acl->checkPrivileges($uri,'{' . self::NS_CALDAV . '}read-free-busy'); + + $calendar = $this->server->tree->getNodeForPath($uri); + if (!$calendar instanceof Sabre_CalDAV_ICalendar) { + throw new Sabre_DAV_Exception_NotImplemented('The free-busy-query REPORT is only implemented on calendars'); + } + + $objects = array_map(function($child) { + $obj = $child->get(); + if (is_resource($obj)) { + $obj = stream_get_contents($obj); + } + return $obj; + }, $calendar->getChildren()); + + $generator = new Sabre_VObject_FreeBusyGenerator(); + $generator->setObjects($objects); + $generator->setTimeRange($start, $end); + $result = $generator->getResult(); + $result = $result->serialize(); + + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->setHeader('Content-Type', 'text/calendar'); + $this->server->httpResponse->setHeader('Content-Length', strlen($result)); + $this->server->httpResponse->sendBody($result); + + } + + /** + * This method is triggered before a file gets updated with new content. + * + * This plugin uses this method to ensure that CalDAV objects receive + * valid calendar data. + * + * @param string $path + * @param Sabre_DAV_IFile $node + * @param resource $data + * @return void + */ + public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) { + + if (!$node instanceof Sabre_CalDAV_ICalendarObject) + return; + + $this->validateICalendar($data); + + } + + /** + * This method is triggered before a new file is created. + * + * This plugin uses this method to ensure that newly created calendar + * objects contain valid calendar data. + * + * @param string $path + * @param resource $data + * @param Sabre_DAV_ICollection $parentNode + * @return void + */ + public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) { + + if (!$parentNode instanceof Sabre_CalDAV_Calendar) + return; + + $this->validateICalendar($data); + + } + + /** + * Checks if the submitted iCalendar data is in fact, valid. + * + * An exception is thrown if it's not. + * + * @param resource|string $data + * @return void + */ + protected function validateICalendar(&$data) { + + // If it's a stream, we convert it to a string first. + if (is_resource($data)) { + $data = stream_get_contents($data); + } + + // Converting the data to unicode, if needed. + $data = Sabre_DAV_StringUtil::ensureUTF8($data); + + try { + + $vobj = Sabre_VObject_Reader::read($data); + + } catch (Sabre_VObject_ParseException $e) { + + throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid iCalendar 2.0 data. Parse error: ' . $e->getMessage()); + + } + + } + + /** + * This method handles POST requests to the schedule-outbox + * + * @param Sabre_CalDAV_Schedule_IOutbox $outboxNode + * @return void + */ + public function outboxRequest(Sabre_CalDAV_Schedule_IOutbox $outboxNode) { + + $originator = $this->server->httpRequest->getHeader('Originator'); + $recipients = $this->server->httpRequest->getHeader('Recipient'); + + if (!$originator) { + throw new Sabre_DAV_Exception_BadRequest('The Originator: header must be specified when making POST requests'); + } + if (!$recipients) { + throw new Sabre_DAV_Exception_BadRequest('The Recipient: header must be specified when making POST requests'); + } + + if (!preg_match('/^mailto:(.*)@(.*)$/', $originator)) { + throw new Sabre_DAV_Exception_BadRequest('Originator must start with mailto: and must be valid email address'); + } + $originator = substr($originator,7); + + $recipients = explode(',',$recipients); + foreach($recipients as $k=>$recipient) { + + $recipient = trim($recipient); + if (!preg_match('/^mailto:(.*)@(.*)$/', $recipient)) { + throw new Sabre_DAV_Exception_BadRequest('Recipients must start with mailto: and must be valid email address'); + } + $recipient = substr($recipient, 7); + $recipients[$k] = $recipient; + } + + // We need to make sure that 'originator' matches one of the email + // addresses of the selected principal. + $principal = $outboxNode->getOwner(); + $props = $this->server->getProperties($principal,array( + '{' . self::NS_CALDAV . '}calendar-user-address-set', + )); + + $addresses = array(); + if (isset($props['{' . self::NS_CALDAV . '}calendar-user-address-set'])) { + $addresses = $props['{' . self::NS_CALDAV . '}calendar-user-address-set']->getHrefs(); + } + + if (!in_array('mailto:' . $originator, $addresses)) { + throw new Sabre_DAV_Exception_Forbidden('The addresses specified in the Originator header did not match any addresses in the owners calendar-user-address-set header'); + } + + try { + $vObject = Sabre_VObject_Reader::read($this->server->httpRequest->getBody(true)); + } catch (Sabre_VObject_ParseException $e) { + throw new Sabre_DAV_Exception_BadRequest('The request body must be a valid iCalendar object. Parse error: ' . $e->getMessage()); + } + + // Checking for the object type + $componentType = null; + foreach($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { + $componentType = $component->name; + break; + } + } + if (is_null($componentType)) { + throw new Sabre_DAV_Exception_BadRequest('We expected at least one VTODO, VJOURNAL, VFREEBUSY or VEVENT component'); + } + + // Validating the METHOD + $method = strtoupper((string)$vObject->METHOD); + if (!$method) { + throw new Sabre_DAV_Exception_BadRequest('A METHOD property must be specified in iTIP messages'); + } + + if (in_array($method, array('REQUEST','REPLY','ADD','CANCEL')) && $componentType==='VEVENT') { + $this->iMIPMessage($originator, $recipients, $vObject); + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->sendBody('Messages sent'); + } else { + throw new Sabre_DAV_Exception_NotImplemented('This iTIP method is currently not implemented'); + } + + } + + /** + * Sends an iMIP message by email. + * + * @param string $originator + * @param array $recipients + * @param Sabre_VObject_Component $vObject + * @return void + */ + protected function iMIPMessage($originator, array $recipients, Sabre_VObject_Component $vObject) { + + if (!$this->imipHandler) { + throw new Sabre_DAV_Exception_NotImplemented('No iMIP handler is setup on this server.'); + } + $this->imipHandler->sendMessage($originator, $recipients, $vObject); + + } + + /** + * This method is used to generate HTML output for the + * Sabre_DAV_Browser_Plugin. This allows us to generate an interface users + * can use to create new calendars. + * + * @param Sabre_DAV_INode $node + * @param string $output + * @return bool + */ + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { + + if (!$node instanceof Sabre_CalDAV_UserCalendars) + return; + + $output.= '
    +

    Create new calendar

    + +
    +
    + +
    + '; + + return false; + + } + + /** + * This method allows us to intercept the 'mkcalendar' sabreAction. This + * action enables the user to create new calendars from the browser plugin. + * + * @param string $uri + * @param string $action + * @param array $postVars + * @return bool + */ + public function browserPostAction($uri, $action, array $postVars) { + + if ($action!=='mkcalendar') + return; + + $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); + $properties = array(); + if (isset($postVars['{DAV:}displayname'])) { + $properties['{DAV:}displayname'] = $postVars['{DAV:}displayname']; + } + $this->server->createCollection($uri . '/' . $postVars['name'],$resourceType,$properties); + return false; + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Principal/Collection.php b/3rdparty/Sabre/CalDAV/Principal/Collection.php new file mode 100755 index 00000000000..abbefa5567a --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Principal/Collection.php @@ -0,0 +1,31 @@ +principalBackend, $principalInfo); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php b/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php new file mode 100755 index 00000000000..4b3f035634a --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php @@ -0,0 +1,178 @@ +principalInfo = $principalInfo; + $this->principalBackend = $principalBackend; + + } + + /** + * Returns this principals name. + * + * @return string + */ + public function getName() { + + return 'calendar-proxy-read'; + + } + + /** + * Returns the last modification time + * + * @return null + */ + public function getLastModified() { + + return null; + + } + + /** + * Deletes the current node + * + * @throws Sabre_DAV_Exception_Forbidden + * @return void + */ + public function delete() { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); + + } + + /** + * Renames the node + * + * @throws Sabre_DAV_Exception_Forbidden + * @param string $name The new name + * @return void + */ + public function setName($name) { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); + + } + + + /** + * Returns a list of alternative urls for a principal + * + * This can for example be an email address, or ldap url. + * + * @return array + */ + public function getAlternateUriSet() { + + return array(); + + } + + /** + * Returns the full principal url + * + * @return string + */ + public function getPrincipalUrl() { + + return $this->principalInfo['uri'] . '/' . $this->getName(); + + } + + /** + * Returns the list of group members + * + * If this principal is a group, this function should return + * all member principal uri's for the group. + * + * @return array + */ + public function getGroupMemberSet() { + + return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); + + } + + /** + * Returns the list of groups this principal is member of + * + * If this principal is a member of a (list of) groups, this function + * should return a list of principal uri's for it's members. + * + * @return array + */ + public function getGroupMembership() { + + return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); + + } + + /** + * Sets a list of group members + * + * If this principal is a group, this method sets all the group members. + * The list of members is always overwritten, never appended to. + * + * This method should throw an exception if the members could not be set. + * + * @param array $principals + * @return void + */ + public function setGroupMemberSet(array $principals) { + + $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); + + } + + /** + * Returns the displayname + * + * This should be a human readable name for the principal. + * If none is available, return the nodename. + * + * @return string + */ + public function getDisplayName() { + + return $this->getName(); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php b/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php new file mode 100755 index 00000000000..dd0c2e86edd --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php @@ -0,0 +1,178 @@ +principalInfo = $principalInfo; + $this->principalBackend = $principalBackend; + + } + + /** + * Returns this principals name. + * + * @return string + */ + public function getName() { + + return 'calendar-proxy-write'; + + } + + /** + * Returns the last modification time + * + * @return null + */ + public function getLastModified() { + + return null; + + } + + /** + * Deletes the current node + * + * @throws Sabre_DAV_Exception_Forbidden + * @return void + */ + public function delete() { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); + + } + + /** + * Renames the node + * + * @throws Sabre_DAV_Exception_Forbidden + * @param string $name The new name + * @return void + */ + public function setName($name) { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); + + } + + + /** + * Returns a list of alternative urls for a principal + * + * This can for example be an email address, or ldap url. + * + * @return array + */ + public function getAlternateUriSet() { + + return array(); + + } + + /** + * Returns the full principal url + * + * @return string + */ + public function getPrincipalUrl() { + + return $this->principalInfo['uri'] . '/' . $this->getName(); + + } + + /** + * Returns the list of group members + * + * If this principal is a group, this function should return + * all member principal uri's for the group. + * + * @return array + */ + public function getGroupMemberSet() { + + return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); + + } + + /** + * Returns the list of groups this principal is member of + * + * If this principal is a member of a (list of) groups, this function + * should return a list of principal uri's for it's members. + * + * @return array + */ + public function getGroupMembership() { + + return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); + + } + + /** + * Sets a list of group members + * + * If this principal is a group, this method sets all the group members. + * The list of members is always overwritten, never appended to. + * + * This method should throw an exception if the members could not be set. + * + * @param array $principals + * @return void + */ + public function setGroupMemberSet(array $principals) { + + $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); + + } + + /** + * Returns the displayname + * + * This should be a human readable name for the principal. + * If none is available, return the nodename. + * + * @return string + */ + public function getDisplayName() { + + return $this->getName(); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Principal/User.php b/3rdparty/Sabre/CalDAV/Principal/User.php new file mode 100755 index 00000000000..8453b877a73 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Principal/User.php @@ -0,0 +1,132 @@ +principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/' . $name); + if (!$principal) { + throw new Sabre_DAV_Exception_NotFound('Node with name ' . $name . ' was not found'); + } + if ($name === 'calendar-proxy-read') + return new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties); + + if ($name === 'calendar-proxy-write') + return new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); + + throw new Sabre_DAV_Exception_NotFound('Node with name ' . $name . ' was not found'); + + } + + /** + * Returns an array with all the child nodes + * + * @return Sabre_DAV_INode[] + */ + public function getChildren() { + + $r = array(); + if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/calendar-proxy-read')) { + $r[] = new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties); + } + if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/calendar-proxy-write')) { + $r[] = new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); + } + + return $r; + + } + + /** + * Returns whether or not the child node exists + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + try { + $this->getChild($name); + return true; + } catch (Sabre_DAV_Exception_NotFound $e) { + return false; + } + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + $acl = parent::getACL(); + $acl[] = array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-read', + 'protected' => true, + ); + $acl[] = array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-write', + 'protected' => true, + ); + return $acl; + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php new file mode 100755 index 00000000000..2ea078d7dac --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php @@ -0,0 +1,85 @@ +components = $components; + + } + + /** + * Returns the list of supported components + * + * @return array + */ + public function getValue() { + + return $this->components; + + } + + /** + * Serializes the property in a DOMDocument + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $node) { + + $doc = $node->ownerDocument; + foreach($this->components as $component) { + + $xcomp = $doc->createElement('cal:comp'); + $xcomp->setAttribute('name',$component); + $node->appendChild($xcomp); + + } + + } + + /** + * Unserializes the DOMElement back into a Property class. + * + * @param DOMElement $node + * @return Sabre_CalDAV_Property_SupportedCalendarComponentSet + */ + static function unserialize(DOMElement $node) { + + $components = array(); + foreach($node->childNodes as $childNode) { + if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)==='{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}comp') { + $components[] = $childNode->getAttribute('name'); + } + } + return new self($components); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php new file mode 100755 index 00000000000..1d848dd5cf6 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php @@ -0,0 +1,38 @@ +ownerDocument; + + $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV])?$server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]:'cal'; + + $caldata = $doc->createElement($prefix . ':calendar-data'); + $caldata->setAttribute('content-type','text/calendar'); + $caldata->setAttribute('version','2.0'); + + $node->appendChild($caldata); + } + +} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php new file mode 100755 index 00000000000..24e84d4c17d --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php @@ -0,0 +1,44 @@ +ownerDocument; + + $prefix = $node->lookupPrefix('urn:ietf:params:xml:ns:caldav'); + if (!$prefix) $prefix = 'cal'; + + $node->appendChild( + $doc->createElement($prefix . ':supported-collation','i;ascii-casemap') + ); + $node->appendChild( + $doc->createElement($prefix . ':supported-collation','i;octet') + ); + $node->appendChild( + $doc->createElement($prefix . ':supported-collation','i;unicode-casemap') + ); + + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Schedule/IMip.php b/3rdparty/Sabre/CalDAV/Schedule/IMip.php new file mode 100755 index 00000000000..37e75fcc4a7 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Schedule/IMip.php @@ -0,0 +1,104 @@ +senderEmail = $senderEmail; + + } + + /** + * Sends one or more iTip messages through email. + * + * @param string $originator + * @param array $recipients + * @param Sabre_VObject_Component $vObject + * @return void + */ + public function sendMessage($originator, array $recipients, Sabre_VObject_Component $vObject) { + + foreach($recipients as $recipient) { + + $to = $recipient; + $replyTo = $originator; + $subject = 'SabreDAV iTIP message'; + + switch(strtoupper($vObject->METHOD)) { + case 'REPLY' : + $subject = 'Response for: ' . $vObject->VEVENT->SUMMARY; + break; + case 'REQUEST' : + $subject = 'Invitation for: ' .$vObject->VEVENT->SUMMARY; + break; + case 'CANCEL' : + $subject = 'Cancelled event: ' . $vObject->VEVENT->SUMMARY; + break; + } + + $headers = array(); + $headers[] = 'Reply-To: ' . $replyTo; + $headers[] = 'From: ' . $this->senderEmail; + $headers[] = 'Content-Type: text/calendar; method=' . (string)$vObject->method . '; charset=utf-8'; + if (Sabre_DAV_Server::$exposeVersion) { + $headers[] = 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY; + } + + $vcalBody = $vObject->serialize(); + + $this->mail($to, $subject, $vcalBody, $headers); + + } + + } + + /** + * This function is reponsible for sending the actual email. + * + * @param string $to Recipient email address + * @param string $subject Subject of the email + * @param string $body iCalendar body + * @param array $headers List of headers + * @return void + */ + protected function mail($to, $subject, $body, array $headers) { + + mail($to, $subject, $body, implode("\r\n", $headers)); + + } + + +} + +?> diff --git a/3rdparty/Sabre/CalDAV/Schedule/IOutbox.php b/3rdparty/Sabre/CalDAV/Schedule/IOutbox.php new file mode 100755 index 00000000000..46d77514bc0 --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Schedule/IOutbox.php @@ -0,0 +1,16 @@ +principalUri = $principalUri; + + } + + /** + * Returns the name of the node. + * + * This is used to generate the url. + * + * @return string + */ + public function getName() { + + return 'outbox'; + + } + + /** + * Returns an array with all the child nodes + * + * @return Sabre_DAV_INode[] + */ + public function getChildren() { + + return array(); + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->principalUri; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy', + 'principal' => $this->getOwner(), + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->getOwner(), + 'protected' => true, + ), + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('You\'re not allowed to update the ACL'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + $default = Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet(); + $default['aggregates'][] = array( + 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy', + ); + + return $default; + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Server.php b/3rdparty/Sabre/CalDAV/Server.php new file mode 100755 index 00000000000..325e3d80a7f --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Server.php @@ -0,0 +1,68 @@ +authRealm); + $this->addPlugin($authPlugin); + + $aclPlugin = new Sabre_DAVACL_Plugin(); + $this->addPlugin($aclPlugin); + + $caldavPlugin = new Sabre_CalDAV_Plugin(); + $this->addPlugin($caldavPlugin); + + } + +} diff --git a/3rdparty/Sabre/CalDAV/UserCalendars.php b/3rdparty/Sabre/CalDAV/UserCalendars.php new file mode 100755 index 00000000000..b8d3f0573fa --- /dev/null +++ b/3rdparty/Sabre/CalDAV/UserCalendars.php @@ -0,0 +1,298 @@ +principalBackend = $principalBackend; + $this->caldavBackend = $caldavBackend; + $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); + + } + + /** + * Returns the name of this object + * + * @return string + */ + public function getName() { + + list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); + return $name; + + } + + /** + * Updates the name of this object + * + * @param string $name + * @return void + */ + public function setName($name) { + + throw new Sabre_DAV_Exception_Forbidden(); + + } + + /** + * Deletes this object + * + * @return void + */ + public function delete() { + + throw new Sabre_DAV_Exception_Forbidden(); + + } + + /** + * Returns the last modification date + * + * @return int + */ + public function getLastModified() { + + return null; + + } + + /** + * Creates a new file under this object. + * + * This is currently not allowed + * + * @param string $filename + * @param resource $data + * @return void + */ + public function createFile($filename, $data=null) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); + + } + + /** + * Creates a new directory under this object. + * + * This is currently not allowed. + * + * @param string $filename + * @return void + */ + public function createDirectory($filename) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); + + } + + /** + * Returns a single calendar, by name + * + * @param string $name + * @todo needs optimizing + * @return Sabre_CalDAV_Calendar + */ + public function getChild($name) { + + foreach($this->getChildren() as $child) { + if ($name==$child->getName()) + return $child; + + } + throw new Sabre_DAV_Exception_NotFound('Calendar with name \'' . $name . '\' could not be found'); + + } + + /** + * Checks if a calendar exists. + * + * @param string $name + * @todo needs optimizing + * @return bool + */ + public function childExists($name) { + + foreach($this->getChildren() as $child) { + if ($name==$child->getName()) + return true; + + } + return false; + + } + + /** + * Returns a list of calendars + * + * @return array + */ + public function getChildren() { + + $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']); + $objs = array(); + foreach($calendars as $calendar) { + $objs[] = new Sabre_CalDAV_Calendar($this->principalBackend, $this->caldavBackend, $calendar); + } + $objs[] = new Sabre_CalDAV_Schedule_Outbox($this->principalInfo['uri']); + return $objs; + + } + + /** + * Creates a new calendar + * + * @param string $name + * @param array $resourceType + * @param array $properties + * @return void + */ + public function createExtendedCollection($name, array $resourceType, array $properties) { + + if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { + throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); + } + $this->caldavBackend->createCalendar($this->principalInfo['uri'], $name, $properties); + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->principalInfo['uri']; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalInfo['uri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->principalInfo['uri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', + 'protected' => true, + ), + + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} diff --git a/3rdparty/Sabre/CalDAV/Version.php b/3rdparty/Sabre/CalDAV/Version.php new file mode 100755 index 00000000000..939e903c89f --- /dev/null +++ b/3rdparty/Sabre/CalDAV/Version.php @@ -0,0 +1,24 @@ +carddavBackend = $carddavBackend; + $this->addressBookInfo = $addressBookInfo; + + } + + /** + * Returns the name of the addressbook + * + * @return string + */ + public function getName() { + + return $this->addressBookInfo['uri']; + + } + + /** + * Returns a card + * + * @param string $name + * @return Sabre_DAV_Card + */ + public function getChild($name) { + + $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'],$name); + if (!$obj) throw new Sabre_DAV_Exception_NotFound('Card not found'); + return new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); + + } + + /** + * Returns the full list of cards + * + * @return array + */ + public function getChildren() { + + $objs = $this->carddavBackend->getCards($this->addressBookInfo['id']); + $children = array(); + foreach($objs as $obj) { + $children[] = new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); + } + return $children; + + } + + /** + * Creates a new directory + * + * We actually block this, as subdirectories are not allowed in addressbooks. + * + * @param string $name + * @return void + */ + public function createDirectory($name) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in addressbooks is not allowed'); + + } + + /** + * Creates a new file + * + * The contents of the new file must be a valid VCARD. + * + * This method may return an ETag. + * + * @param string $name + * @param resource $vcardData + * @return void|null + */ + public function createFile($name,$vcardData = null) { + + $vcardData = stream_get_contents($vcardData); + // Converting to UTF-8, if needed + $vcardData = Sabre_DAV_StringUtil::ensureUTF8($vcardData); + + return $this->carddavBackend->createCard($this->addressBookInfo['id'],$name,$vcardData); + + } + + /** + * Deletes the entire addressbook. + * + * @return void + */ + public function delete() { + + $this->carddavBackend->deleteAddressBook($this->addressBookInfo['id']); + + } + + /** + * Renames the addressbook + * + * @param string $newName + * @return void + */ + public function setName($newName) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming addressbooks is not yet supported'); + + } + + /** + * Returns the last modification date as a unix timestamp. + * + * @return void + */ + public function getLastModified() { + + return null; + + } + + /** + * Updates properties on this node, + * + * The properties array uses the propertyName in clark-notation as key, + * and the array value for the property value. In the case a property + * should be deleted, the property value will be null. + * + * This method must be atomic. If one property cannot be changed, the + * entire operation must fail. + * + * If the operation was successful, true can be returned. + * If the operation failed, false can be returned. + * + * Deletion of a non-existent property is always successful. + * + * Lastly, it is optional to return detailed information about any + * failures. In this case an array should be returned with the following + * structure: + * + * array( + * 403 => array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param array $mutations + * @return bool|array + */ + public function updateProperties($mutations) { + + return $this->carddavBackend->updateAddressBook($this->addressBookInfo['id'], $mutations); + + } + + /** + * Returns a list of properties for this nodes. + * + * The properties list is a list of propertynames the client requested, + * encoded in clark-notation {xmlnamespace}tagname + * + * If the array is empty, it means 'all properties' were requested. + * + * @param array $properties + * @return array + */ + public function getProperties($properties) { + + $response = array(); + foreach($properties as $propertyName) { + + if (isset($this->addressBookInfo[$propertyName])) { + + $response[$propertyName] = $this->addressBookInfo[$propertyName]; + + } + + } + + return $response; + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->addressBookInfo['principaluri']; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->addressBookInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->addressBookInfo['principaluri'], + 'protected' => true, + ), + + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} diff --git a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php b/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php new file mode 100755 index 00000000000..85a4963127b --- /dev/null +++ b/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php @@ -0,0 +1,209 @@ +dom = $dom; + + $this->xpath = new DOMXPath($dom); + $this->xpath->registerNameSpace('card',Sabre_CardDAV_Plugin::NS_CARDDAV); + + } + + /** + * Parses the request. + * + * @return void + */ + public function parse() { + + $filterNode = null; + + $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); + if (is_nan($limit)) $limit = null; + + $filter = $this->xpath->query('/card:addressbook-query/card:filter'); + if ($filter->length !== 1) { + throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); + } + + $filter = $filter->item(0); + $test = $this->xpath->evaluate('string(@test)', $filter); + if (!$test) $test = self::TEST_ANYOF; + if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { + throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"'); + } + + $propFilters = array(); + + $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); + for($ii=0; $ii < $propFilterNodes->length; $ii++) { + + $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); + + + } + + $this->filters = $propFilters; + $this->limit = $limit; + $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); + $this->test = $test; + + } + + /** + * Parses the prop-filter xml element + * + * @param DOMElement $propFilterNode + * @return array + */ + protected function parsePropFilterNode(DOMElement $propFilterNode) { + + $propFilter = array(); + $propFilter['name'] = $propFilterNode->getAttribute('name'); + $propFilter['test'] = $propFilterNode->getAttribute('test'); + if (!$propFilter['test']) $propFilter['test'] = 'anyof'; + + $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; + + $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); + + $propFilter['param-filters'] = array(); + + + for($ii=0;$ii<$paramFilterNodes->length;$ii++) { + + $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); + + } + $propFilter['text-matches'] = array(); + $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); + + for($ii=0;$ii<$textMatchNodes->length;$ii++) { + + $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); + + } + + return $propFilter; + + } + + /** + * Parses the param-filter element + * + * @param DOMElement $paramFilterNode + * @return array + */ + public function parseParamFilterNode(DOMElement $paramFilterNode) { + + $paramFilter = array(); + $paramFilter['name'] = $paramFilterNode->getAttribute('name'); + $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; + $paramFilter['text-match'] = null; + + $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); + if ($textMatch->length>0) { + $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); + } + + return $paramFilter; + + } + + /** + * Text match + * + * @param DOMElement $textMatchNode + * @return array + */ + public function parseTextMatchNode(DOMElement $textMatchNode) { + + $matchType = $textMatchNode->getAttribute('match-type'); + if (!$matchType) $matchType = 'contains'; + + if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { + throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: ' . $matchType); + } + + $negateCondition = $textMatchNode->getAttribute('negate-condition'); + $negateCondition = $negateCondition==='yes'; + $collation = $textMatchNode->getAttribute('collation'); + if (!$collation) $collation = 'i;unicode-casemap'; + + return array( + 'negate-condition' => $negateCondition, + 'collation' => $collation, + 'match-type' => $matchType, + 'value' => $textMatchNode->nodeValue + ); + + + } + +} diff --git a/3rdparty/Sabre/CardDAV/AddressBookRoot.php b/3rdparty/Sabre/CardDAV/AddressBookRoot.php new file mode 100755 index 00000000000..9d37b15f08e --- /dev/null +++ b/3rdparty/Sabre/CardDAV/AddressBookRoot.php @@ -0,0 +1,78 @@ +carddavBackend = $carddavBackend; + parent::__construct($principalBackend, $principalPrefix); + + } + + /** + * Returns the name of the node + * + * @return string + */ + public function getName() { + + return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; + + } + + /** + * This method returns a node for a principal. + * + * The passed array contains principal information, and is guaranteed to + * at least contain a uri item. Other properties may or may not be + * supplied by the authentication backend. + * + * @param array $principal + * @return Sabre_DAV_INode + */ + public function getChildForPrincipal(array $principal) { + + return new Sabre_CardDAV_UserAddressBooks($this->carddavBackend, $principal['uri']); + + } + +} diff --git a/3rdparty/Sabre/CardDAV/Backend/Abstract.php b/3rdparty/Sabre/CardDAV/Backend/Abstract.php new file mode 100755 index 00000000000..e4806b7161f --- /dev/null +++ b/3rdparty/Sabre/CardDAV/Backend/Abstract.php @@ -0,0 +1,166 @@ +pdo = $pdo; + $this->addressBooksTableName = $addressBooksTableName; + $this->cardsTableName = $cardsTableName; + + } + + /** + * Returns the list of addressbooks for a specific user. + * + * @param string $principalUri + * @return array + */ + public function getAddressBooksForUser($principalUri) { + + $stmt = $this->pdo->prepare('SELECT id, uri, displayname, principaluri, description, ctag FROM '.$this->addressBooksTableName.' WHERE principaluri = ?'); + $stmt->execute(array($principalUri)); + + $addressBooks = array(); + + foreach($stmt->fetchAll() as $row) { + + $addressBooks[] = array( + 'id' => $row['id'], + 'uri' => $row['uri'], + 'principaluri' => $row['principaluri'], + '{DAV:}displayname' => $row['displayname'], + '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], + '{http://calendarserver.org/ns/}getctag' => $row['ctag'], + '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => + new Sabre_CardDAV_Property_SupportedAddressData(), + ); + + } + + return $addressBooks; + + } + + + /** + * Updates an addressbook's properties + * + * See Sabre_DAV_IProperties for a description of the mutations array, as + * well as the return value. + * + * @param mixed $addressBookId + * @param array $mutations + * @see Sabre_DAV_IProperties::updateProperties + * @return bool|array + */ + public function updateAddressBook($addressBookId, array $mutations) { + + $updates = array(); + + foreach($mutations as $property=>$newValue) { + + switch($property) { + case '{DAV:}displayname' : + $updates['displayname'] = $newValue; + break; + case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : + $updates['description'] = $newValue; + break; + default : + // If any unsupported values were being updated, we must + // let the entire request fail. + return false; + } + + } + + // No values are being updated? + if (!$updates) { + return false; + } + + $query = 'UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 '; + foreach($updates as $key=>$value) { + $query.=', `' . $key . '` = :' . $key . ' '; + } + $query.=' WHERE id = :addressbookid'; + + $stmt = $this->pdo->prepare($query); + $updates['addressbookid'] = $addressBookId; + + $stmt->execute($updates); + + return true; + + } + + /** + * Creates a new address book + * + * @param string $principalUri + * @param string $url Just the 'basename' of the url. + * @param array $properties + * @return void + */ + public function createAddressBook($principalUri, $url, array $properties) { + + $values = array( + 'displayname' => null, + 'description' => null, + 'principaluri' => $principalUri, + 'uri' => $url, + ); + + foreach($properties as $property=>$newValue) { + + switch($property) { + case '{DAV:}displayname' : + $values['displayname'] = $newValue; + break; + case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : + $values['description'] = $newValue; + break; + default : + throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); + } + + } + + $query = 'INSERT INTO ' . $this->addressBooksTableName . ' (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; + $stmt = $this->pdo->prepare($query); + $stmt->execute($values); + + } + + /** + * Deletes an entire addressbook and all its contents + * + * @param int $addressBookId + * @return void + */ + public function deleteAddressBook($addressBookId) { + + $stmt = $this->pdo->prepare('DELETE FROM ' . $this->cardsTableName . ' WHERE addressbookid = ?'); + $stmt->execute(array($addressBookId)); + + $stmt = $this->pdo->prepare('DELETE FROM ' . $this->addressBooksTableName . ' WHERE id = ?'); + $stmt->execute(array($addressBookId)); + + } + + /** + * Returns all cards for a specific addressbook id. + * + * This method should return the following properties for each card: + * * carddata - raw vcard data + * * uri - Some unique url + * * lastmodified - A unix timestamp + * + * It's recommended to also return the following properties: + * * etag - A unique etag. This must change every time the card changes. + * * size - The size of the card in bytes. + * + * If these last two properties are provided, less time will be spent + * calculating them. If they are specified, you can also ommit carddata. + * This may speed up certain requests, especially with large cards. + * + * @param mixed $addressbookId + * @return array + */ + public function getCards($addressbookId) { + + $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM ' . $this->cardsTableName . ' WHERE addressbookid = ?'); + $stmt->execute(array($addressbookId)); + + return $stmt->fetchAll(PDO::FETCH_ASSOC); + + + } + + /** + * Returns a specfic card. + * + * The same set of properties must be returned as with getCards. The only + * exception is that 'carddata' is absolutely required. + * + * @param mixed $addressBookId + * @param string $cardUri + * @return array + */ + public function getCard($addressBookId, $cardUri) { + + $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM ' . $this->cardsTableName . ' WHERE addressbookid = ? AND uri = ? LIMIT 1'); + $stmt->execute(array($addressBookId, $cardUri)); + + $result = $stmt->fetchAll(PDO::FETCH_ASSOC); + + return (count($result)>0?$result[0]:false); + + } + + /** + * Creates a new card. + * + * The addressbook id will be passed as the first argument. This is the + * same id as it is returned from the getAddressbooksForUser method. + * + * The cardUri is a base uri, and doesn't include the full path. The + * cardData argument is the vcard body, and is passed as a string. + * + * It is possible to return an ETag from this method. This ETag is for the + * newly created resource, and must be enclosed with double quotes (that + * is, the string itself must contain the double quotes). + * + * You should only return the ETag if you store the carddata as-is. If a + * subsequent GET request on the same card does not have the same body, + * byte-by-byte and you did return an ETag here, clients tend to get + * confused. + * + * If you don't return an ETag, you can just return null. + * + * @param mixed $addressBookId + * @param string $cardUri + * @param string $cardData + * @return string|null + */ + public function createCard($addressBookId, $cardUri, $cardData) { + + $stmt = $this->pdo->prepare('INSERT INTO ' . $this->cardsTableName . ' (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); + + $result = $stmt->execute(array($cardData, $cardUri, time(), $addressBookId)); + + $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2->execute(array($addressBookId)); + + return '"' . md5($cardData) . '"'; + + } + + /** + * Updates a card. + * + * The addressbook id will be passed as the first argument. This is the + * same id as it is returned from the getAddressbooksForUser method. + * + * The cardUri is a base uri, and doesn't include the full path. The + * cardData argument is the vcard body, and is passed as a string. + * + * It is possible to return an ETag from this method. This ETag should + * match that of the updated resource, and must be enclosed with double + * quotes (that is: the string itself must contain the actual quotes). + * + * You should only return the ETag if you store the carddata as-is. If a + * subsequent GET request on the same card does not have the same body, + * byte-by-byte and you did return an ETag here, clients tend to get + * confused. + * + * If you don't return an ETag, you can just return null. + * + * @param mixed $addressBookId + * @param string $cardUri + * @param string $cardData + * @return string|null + */ + public function updateCard($addressBookId, $cardUri, $cardData) { + + $stmt = $this->pdo->prepare('UPDATE ' . $this->cardsTableName . ' SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); + $stmt->execute(array($cardData, time(), $cardUri, $addressBookId)); + + $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2->execute(array($addressBookId)); + + return '"' . md5($cardData) . '"'; + + } + + /** + * Deletes a card + * + * @param mixed $addressBookId + * @param string $cardUri + * @return bool + */ + public function deleteCard($addressBookId, $cardUri) { + + $stmt = $this->pdo->prepare('DELETE FROM ' . $this->cardsTableName . ' WHERE addressbookid = ? AND uri = ?'); + $stmt->execute(array($addressBookId, $cardUri)); + + $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2->execute(array($addressBookId)); + + return $stmt->rowCount()===1; + + } +} diff --git a/3rdparty/Sabre/CardDAV/Card.php b/3rdparty/Sabre/CardDAV/Card.php new file mode 100755 index 00000000000..d7c66333837 --- /dev/null +++ b/3rdparty/Sabre/CardDAV/Card.php @@ -0,0 +1,250 @@ +carddavBackend = $carddavBackend; + $this->addressBookInfo = $addressBookInfo; + $this->cardData = $cardData; + + } + + /** + * Returns the uri for this object + * + * @return string + */ + public function getName() { + + return $this->cardData['uri']; + + } + + /** + * Returns the VCard-formatted object + * + * @return string + */ + public function get() { + + // Pre-populating 'carddata' is optional. If we don't yet have it + // already, we fetch it from the backend. + if (!isset($this->cardData['carddata'])) { + $this->cardData = $this->carddavBackend->getCard($this->addressBookInfo['id'], $this->cardData['uri']); + } + return $this->cardData['carddata']; + + } + + /** + * Updates the VCard-formatted object + * + * @param string $cardData + * @return void + */ + public function put($cardData) { + + if (is_resource($cardData)) + $cardData = stream_get_contents($cardData); + + // Converting to UTF-8, if needed + $cardData = Sabre_DAV_StringUtil::ensureUTF8($cardData); + + $etag = $this->carddavBackend->updateCard($this->addressBookInfo['id'],$this->cardData['uri'],$cardData); + $this->cardData['carddata'] = $cardData; + $this->cardData['etag'] = $etag; + + return $etag; + + } + + /** + * Deletes the card + * + * @return void + */ + public function delete() { + + $this->carddavBackend->deleteCard($this->addressBookInfo['id'],$this->cardData['uri']); + + } + + /** + * Returns the mime content-type + * + * @return string + */ + public function getContentType() { + + return 'text/x-vcard'; + + } + + /** + * Returns an ETag for this object + * + * @return string + */ + public function getETag() { + + if (isset($this->cardData['etag'])) { + return $this->cardData['etag']; + } else { + return '"' . md5($this->get()) . '"'; + } + + } + + /** + * Returns the last modification date as a unix timestamp + * + * @return time + */ + public function getLastModified() { + + return isset($this->cardData['lastmodified'])?$this->cardData['lastmodified']:null; + + } + + /** + * Returns the size of this object in bytes + * + * @return int + */ + public function getSize() { + + if (array_key_exists('size', $this->cardData)) { + return $this->cardData['size']; + } else { + return strlen($this->get()); + } + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->addressBookInfo['principaluri']; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->addressBookInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->addressBookInfo['principaluri'], + 'protected' => true, + ), + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} + diff --git a/3rdparty/Sabre/CardDAV/IAddressBook.php b/3rdparty/Sabre/CardDAV/IAddressBook.php new file mode 100755 index 00000000000..2bc275bcf74 --- /dev/null +++ b/3rdparty/Sabre/CardDAV/IAddressBook.php @@ -0,0 +1,18 @@ +subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); + $server->subscribeEvent('updateProperties', array($this, 'updateProperties')); + $server->subscribeEvent('report', array($this,'report')); + $server->subscribeEvent('onHTMLActionsPanel', array($this,'htmlActionsPanel')); + $server->subscribeEvent('onBrowserPostAction', array($this,'browserPostAction')); + + /* Namespaces */ + $server->xmlNamespaces[self::NS_CARDDAV] = 'card'; + + /* Mapping Interfaces to {DAV:}resourcetype values */ + $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook'; + $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory'; + + /* Adding properties that may never be changed */ + $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data'; + $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size'; + $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}addressbook-home-set'; + $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-collation-set'; + + $server->propertyMap['{http://calendarserver.org/ns/}me-card'] = 'Sabre_DAV_Property_Href'; + + $this->server = $server; + + } + + /** + * Returns a list of supported features. + * + * This is used in the DAV: header in the OPTIONS and PROPFIND requests. + * + * @return array + */ + public function getFeatures() { + + return array('addressbook'); + + } + + /** + * Returns a list of reports this plugin supports. + * + * This will be used in the {DAV:}supported-report-set property. + * Note that you still need to subscribe to the 'report' event to actually + * implement them + * + * @param string $uri + * @return array + */ + public function getSupportedReportSet($uri) { + + $node = $this->server->tree->getNodeForPath($uri); + if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) { + return array( + '{' . self::NS_CARDDAV . '}addressbook-multiget', + '{' . self::NS_CARDDAV . '}addressbook-query', + ); + } + return array(); + + } + + + /** + * Adds all CardDAV-specific properties + * + * @param string $path + * @param Sabre_DAV_INode $node + * @param array $requestedProperties + * @param array $returnedProperties + * @return void + */ + public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) { + + if ($node instanceof Sabre_DAVACL_IPrincipal) { + + // calendar-home-set property + $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set'; + if (in_array($addHome,$requestedProperties)) { + $principalId = $node->getName(); + $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/'; + unset($requestedProperties[array_search($addHome, $requestedProperties)]); + $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath); + } + + $directories = '{' . self::NS_CARDDAV . '}directory-gateway'; + if ($this->directories && in_array($directories, $requestedProperties)) { + unset($requestedProperties[array_search($directories, $requestedProperties)]); + $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories); + } + + } + + if ($node instanceof Sabre_CardDAV_ICard) { + + // The address-data property is not supposed to be a 'real' + // property, but in large chunks of the spec it does act as such. + // Therefore we simply expose it as a property. + $addressDataProp = '{' . self::NS_CARDDAV . '}address-data'; + if (in_array($addressDataProp, $requestedProperties)) { + unset($requestedProperties[$addressDataProp]); + $val = $node->get(); + if (is_resource($val)) + $val = stream_get_contents($val); + + // Taking out \r to not screw up the xml output + $returnedProperties[200][$addressDataProp] = str_replace("\r","", $val); + + } + } + + if ($node instanceof Sabre_CardDAV_UserAddressBooks) { + + $meCardProp = '{http://calendarserver.org/ns/}me-card'; + if (in_array($meCardProp, $requestedProperties)) { + + $props = $this->server->getProperties($node->getOwner(), array('{http://sabredav.org/ns}vcard-url')); + if (isset($props['{http://sabredav.org/ns}vcard-url'])) { + + $returnedProperties[200][$meCardProp] = new Sabre_DAV_Property_Href( + $props['{http://sabredav.org/ns}vcard-url'] + ); + $pos = array_search($meCardProp, $requestedProperties); + unset($requestedProperties[$pos]); + + } + + } + + } + + } + + /** + * This event is triggered when a PROPPATCH method is executed + * + * @param array $mutations + * @param array $result + * @param Sabre_DAV_INode $node + * @return void + */ + public function updateProperties(&$mutations, &$result, $node) { + + if (!$node instanceof Sabre_CardDAV_UserAddressBooks) { + return true; + } + + $meCard = '{http://calendarserver.org/ns/}me-card'; + + // The only property we care about + if (!isset($mutations[$meCard])) + return true; + + $value = $mutations[$meCard]; + unset($mutations[$meCard]); + + if ($value instanceof Sabre_DAV_Property_IHref) { + $value = $value->getHref(); + $value = $this->server->calculateUri($value); + } elseif (!is_null($value)) { + $result[400][$meCard] = null; + return false; + } + + $innerResult = $this->server->updateProperties( + $node->getOwner(), + array( + '{http://sabredav.org/ns}vcard-url' => $value, + ) + ); + + $closureResult = false; + foreach($innerResult as $status => $props) { + if (is_array($props) && array_key_exists('{http://sabredav.org/ns}vcard-url', $props)) { + $result[$status][$meCard] = null; + $closureResult = ($status>=200 && $status<300); + } + + } + + return $result; + + } + + /** + * This functions handles REPORT requests specific to CardDAV + * + * @param string $reportName + * @param DOMNode $dom + * @return bool + */ + public function report($reportName,$dom) { + + switch($reportName) { + case '{'.self::NS_CARDDAV.'}addressbook-multiget' : + $this->addressbookMultiGetReport($dom); + return false; + case '{'.self::NS_CARDDAV.'}addressbook-query' : + $this->addressBookQueryReport($dom); + return false; + default : + return; + + } + + + } + + /** + * This function handles the addressbook-multiget REPORT. + * + * This report is used by the client to fetch the content of a series + * of urls. Effectively avoiding a lot of redundant requests. + * + * @param DOMNode $dom + * @return void + */ + public function addressbookMultiGetReport($dom) { + + $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); + + $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); + $propertyList = array(); + + foreach($hrefElems as $elem) { + + $uri = $this->server->calculateUri($elem->nodeValue); + list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties); + + } + + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); + + } + + /** + * This function handles the addressbook-query REPORT + * + * This report is used by the client to filter an addressbook based on a + * complex query. + * + * @param DOMNode $dom + * @return void + */ + protected function addressbookQueryReport($dom) { + + $query = new Sabre_CardDAV_AddressBookQueryParser($dom); + $query->parse(); + + $depth = $this->server->getHTTPDepth(0); + + if ($depth==0) { + $candidateNodes = array( + $this->server->tree->getNodeForPath($this->server->getRequestUri()) + ); + } else { + $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); + } + + $validNodes = array(); + foreach($candidateNodes as $node) { + + if (!$node instanceof Sabre_CardDAV_ICard) + continue; + + $blob = $node->get(); + if (is_resource($blob)) { + $blob = stream_get_contents($blob); + } + + if (!$this->validateFilters($blob, $query->filters, $query->test)) { + continue; + } + + $validNodes[] = $node; + + if ($query->limit && $query->limit <= count($validNodes)) { + // We hit the maximum number of items, we can stop now. + break; + } + + } + + $result = array(); + foreach($validNodes as $validNode) { + + if ($depth==0) { + $href = $this->server->getRequestUri(); + } else { + $href = $this->server->getRequestUri() . '/' . $validNode->getName(); + } + + list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); + + } + + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); + + } + + /** + * Validates if a vcard makes it throught a list of filters. + * + * @param string $vcardData + * @param array $filters + * @param string $test anyof or allof (which means OR or AND) + * @return bool + */ + public function validateFilters($vcardData, array $filters, $test) { + + $vcard = Sabre_VObject_Reader::read($vcardData); + + foreach($filters as $filter) { + + $isDefined = isset($vcard->{$filter['name']}); + if ($filter['is-not-defined']) { + if ($isDefined) { + $success = false; + } else { + $success = true; + } + } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { + + // We only need to check for existence + $success = $isDefined; + + } else { + + $vProperties = $vcard->select($filter['name']); + + $results = array(); + if ($filter['param-filters']) { + $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); + } + if ($filter['text-matches']) { + $texts = array(); + foreach($vProperties as $vProperty) + $texts[] = $vProperty->value; + + $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); + } + + if (count($results)===1) { + $success = $results[0]; + } else { + if ($filter['test'] === 'anyof') { + $success = $results[0] || $results[1]; + } else { + $success = $results[0] && $results[1]; + } + } + + } // else + + // There are two conditions where we can already determine whether + // or not this filter succeeds. + if ($test==='anyof' && $success) { + return true; + } + if ($test==='allof' && !$success) { + return false; + } + + } // foreach + + // If we got all the way here, it means we haven't been able to + // determine early if the test failed or not. + // + // This implies for 'anyof' that the test failed, and for 'allof' that + // we succeeded. Sounds weird, but makes sense. + return $test==='allof'; + + } + + /** + * Validates if a param-filter can be applied to a specific property. + * + * @todo currently we're only validating the first parameter of the passed + * property. Any subsequence parameters with the same name are + * ignored. + * @param array $vProperties + * @param array $filters + * @param string $test + * @return bool + */ + protected function validateParamFilters(array $vProperties, array $filters, $test) { + + foreach($filters as $filter) { + + $isDefined = false; + foreach($vProperties as $vProperty) { + $isDefined = isset($vProperty[$filter['name']]); + if ($isDefined) break; + } + + if ($filter['is-not-defined']) { + if ($isDefined) { + $success = false; + } else { + $success = true; + } + + // If there's no text-match, we can just check for existence + } elseif (!$filter['text-match'] || !$isDefined) { + + $success = $isDefined; + + } else { + + $success = false; + foreach($vProperties as $vProperty) { + // If we got all the way here, we'll need to validate the + // text-match filter. + $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); + if ($success) break; + } + if ($filter['text-match']['negate-condition']) { + $success = !$success; + } + + } // else + + // There are two conditions where we can already determine whether + // or not this filter succeeds. + if ($test==='anyof' && $success) { + return true; + } + if ($test==='allof' && !$success) { + return false; + } + + } + + // If we got all the way here, it means we haven't been able to + // determine early if the test failed or not. + // + // This implies for 'anyof' that the test failed, and for 'allof' that + // we succeeded. Sounds weird, but makes sense. + return $test==='allof'; + + } + + /** + * Validates if a text-filter can be applied to a specific property. + * + * @param array $texts + * @param array $filters + * @param string $test + * @return bool + */ + protected function validateTextMatches(array $texts, array $filters, $test) { + + foreach($filters as $filter) { + + $success = false; + foreach($texts as $haystack) { + $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); + + // Breaking on the first match + if ($success) break; + } + if ($filter['negate-condition']) { + $success = !$success; + } + + if ($success && $test==='anyof') + return true; + + if (!$success && $test=='allof') + return false; + + + } + + // If we got all the way here, it means we haven't been able to + // determine early if the test failed or not. + // + // This implies for 'anyof' that the test failed, and for 'allof' that + // we succeeded. Sounds weird, but makes sense. + return $test==='allof'; + + } + + /** + * This method is used to generate HTML output for the + * Sabre_DAV_Browser_Plugin. This allows us to generate an interface users + * can use to create new calendars. + * + * @param Sabre_DAV_INode $node + * @param string $output + * @return bool + */ + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { + + if (!$node instanceof Sabre_CardDAV_UserAddressBooks) + return; + + $output.= '
    +

    Create new address book

    + +
    +
    + +
    + '; + + return false; + + } + + /** + * This method allows us to intercept the 'mkcalendar' sabreAction. This + * action enables the user to create new calendars from the browser plugin. + * + * @param string $uri + * @param string $action + * @param array $postVars + * @return bool + */ + public function browserPostAction($uri, $action, array $postVars) { + + if ($action!=='mkaddressbook') + return; + + $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:carddav}addressbook'); + $properties = array(); + if (isset($postVars['{DAV:}displayname'])) { + $properties['{DAV:}displayname'] = $postVars['{DAV:}displayname']; + } + $this->server->createCollection($uri . '/' . $postVars['name'],$resourceType,$properties); + return false; + + } + +} diff --git a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php b/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php new file mode 100755 index 00000000000..36d9306e7aa --- /dev/null +++ b/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php @@ -0,0 +1,69 @@ + 'text/vcard', 'version' => '3.0'), + array('contentType' => 'text/vcard', 'version' => '4.0'), + ); + } + + $this->supportedData = $supportedData; + + } + + /** + * Serializes the property in a DOMDocument + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $node) { + + $doc = $node->ownerDocument; + + $prefix = + isset($server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV]) ? + $server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV] : + 'card'; + + foreach($this->supportedData as $supported) { + + $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix . ':address-data-type'); + $caldata->setAttribute('content-type',$supported['contentType']); + $caldata->setAttribute('version',$supported['version']); + $node->appendChild($caldata); + + } + + } + +} diff --git a/3rdparty/Sabre/CardDAV/UserAddressBooks.php b/3rdparty/Sabre/CardDAV/UserAddressBooks.php new file mode 100755 index 00000000000..3f11fb11238 --- /dev/null +++ b/3rdparty/Sabre/CardDAV/UserAddressBooks.php @@ -0,0 +1,257 @@ +carddavBackend = $carddavBackend; + $this->principalUri = $principalUri; + + } + + /** + * Returns the name of this object + * + * @return string + */ + public function getName() { + + list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); + return $name; + + } + + /** + * Updates the name of this object + * + * @param string $name + * @return void + */ + public function setName($name) { + + throw new Sabre_DAV_Exception_MethodNotAllowed(); + + } + + /** + * Deletes this object + * + * @return void + */ + public function delete() { + + throw new Sabre_DAV_Exception_MethodNotAllowed(); + + } + + /** + * Returns the last modification date + * + * @return int + */ + public function getLastModified() { + + return null; + + } + + /** + * Creates a new file under this object. + * + * This is currently not allowed + * + * @param string $filename + * @param resource $data + * @return void + */ + public function createFile($filename, $data=null) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); + + } + + /** + * Creates a new directory under this object. + * + * This is currently not allowed. + * + * @param string $filename + * @return void + */ + public function createDirectory($filename) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); + + } + + /** + * Returns a single calendar, by name + * + * @param string $name + * @todo needs optimizing + * @return Sabre_CardDAV_AddressBook + */ + public function getChild($name) { + + foreach($this->getChildren() as $child) { + if ($name==$child->getName()) + return $child; + + } + throw new Sabre_DAV_Exception_NotFound('Addressbook with name \'' . $name . '\' could not be found'); + + } + + /** + * Returns a list of addressbooks + * + * @return array + */ + public function getChildren() { + + $addressbooks = $this->carddavBackend->getAddressbooksForUser($this->principalUri); + $objs = array(); + foreach($addressbooks as $addressbook) { + $objs[] = new Sabre_CardDAV_AddressBook($this->carddavBackend, $addressbook); + } + return $objs; + + } + + /** + * Creates a new addressbook + * + * @param string $name + * @param array $resourceType + * @param array $properties + * @return void + */ + public function createExtendedCollection($name, array $resourceType, array $properties) { + + if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { + throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); + } + $this->carddavBackend->createAddressBook($this->principalUri, $name, $properties); + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->principalUri; + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalUri, + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->principalUri, + 'protected' => true, + ), + + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} diff --git a/3rdparty/Sabre/CardDAV/Version.php b/3rdparty/Sabre/CardDAV/Version.php new file mode 100755 index 00000000000..811b929e397 --- /dev/null +++ b/3rdparty/Sabre/CardDAV/Version.php @@ -0,0 +1,26 @@ +currentUser; + } + + + /** + * Authenticates the user based on the current request. + * + * If authentication is successful, true must be returned. + * If authentication fails, an exception must be thrown. + * + * @param Sabre_DAV_Server $server + * @param string $realm + * @throws Sabre_DAV_Exception_NotAuthenticated + * @return bool + */ + public function authenticate(Sabre_DAV_Server $server, $realm) { + + $auth = new Sabre_HTTP_BasicAuth(); + $auth->setHTTPRequest($server->httpRequest); + $auth->setHTTPResponse($server->httpResponse); + $auth->setRealm($realm); + $userpass = $auth->getUserPass(); + if (!$userpass) { + $auth->requireLogin(); + throw new Sabre_DAV_Exception_NotAuthenticated('No basic authentication headers were found'); + } + + // Authenticates the user + if (!$this->validateUserPass($userpass[0],$userpass[1])) { + $auth->requireLogin(); + throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); + } + $this->currentUser = $userpass[0]; + return true; + } + + +} + diff --git a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php b/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php new file mode 100755 index 00000000000..9833928b976 --- /dev/null +++ b/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php @@ -0,0 +1,98 @@ +setHTTPRequest($server->httpRequest); + $digest->setHTTPResponse($server->httpResponse); + + $digest->setRealm($realm); + $digest->init(); + + $username = $digest->getUsername(); + + // No username was given + if (!$username) { + $digest->requireLogin(); + throw new Sabre_DAV_Exception_NotAuthenticated('No digest authentication headers were found'); + } + + $hash = $this->getDigestHash($realm, $username); + // If this was false, the user account didn't exist + if ($hash===false || is_null($hash)) { + $digest->requireLogin(); + throw new Sabre_DAV_Exception_NotAuthenticated('The supplied username was not on file'); + } + if (!is_string($hash)) { + throw new Sabre_DAV_Exception('The returned value from getDigestHash must be a string or null'); + } + + // If this was false, the password or part of the hash was incorrect. + if (!$digest->validateA1($hash)) { + $digest->requireLogin(); + throw new Sabre_DAV_Exception_NotAuthenticated('Incorrect username'); + } + + $this->currentUser = $username; + return true; + + } + + /** + * Returns the currently logged in username. + * + * @return string|null + */ + public function getCurrentUser() { + + return $this->currentUser; + + } + +} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php b/3rdparty/Sabre/DAV/Auth/Backend/Apache.php new file mode 100755 index 00000000000..d4294ea4d86 --- /dev/null +++ b/3rdparty/Sabre/DAV/Auth/Backend/Apache.php @@ -0,0 +1,62 @@ +httpRequest->getRawServerValue('REMOTE_USER'); + if (is_null($remoteUser)) { + throw new Sabre_DAV_Exception('We did not receive the $_SERVER[REMOTE_USER] property. This means that apache might have been misconfigured'); + } + + $this->remoteUser = $remoteUser; + return true; + + } + + /** + * Returns information about the currently logged in user. + * + * If nobody is currently logged in, this method should return null. + * + * @return array|null + */ + public function getCurrentUser() { + + return $this->remoteUser; + + } + +} + diff --git a/3rdparty/Sabre/DAV/Auth/Backend/File.php b/3rdparty/Sabre/DAV/Auth/Backend/File.php new file mode 100755 index 00000000000..de308d64a67 --- /dev/null +++ b/3rdparty/Sabre/DAV/Auth/Backend/File.php @@ -0,0 +1,75 @@ +loadFile($filename); + + } + + /** + * Loads an htdigest-formatted file. This method can be called multiple times if + * more than 1 file is used. + * + * @param string $filename + * @return void + */ + public function loadFile($filename) { + + foreach(file($filename,FILE_IGNORE_NEW_LINES) as $line) { + + if (substr_count($line, ":") !== 2) + throw new Sabre_DAV_Exception('Malformed htdigest file. Every line should contain 2 colons'); + + list($username,$realm,$A1) = explode(':',$line); + + if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) + throw new Sabre_DAV_Exception('Malformed htdigest file. Invalid md5 hash'); + + $this->users[$realm . ':' . $username] = $A1; + + } + + } + + /** + * Returns a users' information + * + * @param string $realm + * @param string $username + * @return string + */ + public function getDigestHash($realm, $username) { + + return isset($this->users[$realm . ':' . $username])?$this->users[$realm . ':' . $username]:false; + + } + +} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php b/3rdparty/Sabre/DAV/Auth/Backend/PDO.php new file mode 100755 index 00000000000..eac18a23fbb --- /dev/null +++ b/3rdparty/Sabre/DAV/Auth/Backend/PDO.php @@ -0,0 +1,65 @@ +pdo = $pdo; + $this->tableName = $tableName; + + } + + /** + * Returns the digest hash for a user. + * + * @param string $realm + * @param string $username + * @return string|null + */ + public function getDigestHash($realm,$username) { + + $stmt = $this->pdo->prepare('SELECT username, digesta1 FROM '.$this->tableName.' WHERE username = ?'); + $stmt->execute(array($username)); + $result = $stmt->fetchAll(); + + if (!count($result)) return; + + return $result[0]['digesta1']; + + } + +} diff --git a/3rdparty/Sabre/DAV/Auth/IBackend.php b/3rdparty/Sabre/DAV/Auth/IBackend.php new file mode 100755 index 00000000000..5be5d1bc93d --- /dev/null +++ b/3rdparty/Sabre/DAV/Auth/IBackend.php @@ -0,0 +1,36 @@ +authBackend = $authBackend; + $this->realm = $realm; + + } + + /** + * Initializes the plugin. This function is automatically called by the server + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),10); + + } + + /** + * Returns a plugin name. + * + * Using this name other plugins will be able to access other plugins + * using Sabre_DAV_Server::getPlugin + * + * @return string + */ + public function getPluginName() { + + return 'auth'; + + } + + /** + * Returns the current users' principal uri. + * + * If nobody is logged in, this will return null. + * + * @return string|null + */ + public function getCurrentUser() { + + $userInfo = $this->authBackend->getCurrentUser(); + if (!$userInfo) return null; + + return $userInfo; + + } + + /** + * This method is called before any HTTP method and forces users to be authenticated + * + * @param string $method + * @param string $uri + * @throws Sabre_DAV_Exception_NotAuthenticated + * @return bool + */ + public function beforeMethod($method, $uri) { + + $this->authBackend->authenticate($this->server,$this->realm); + + } + +} diff --git a/3rdparty/Sabre/DAV/Browser/GuessContentType.php b/3rdparty/Sabre/DAV/Browser/GuessContentType.php new file mode 100755 index 00000000000..b6c00d461cb --- /dev/null +++ b/3rdparty/Sabre/DAV/Browser/GuessContentType.php @@ -0,0 +1,97 @@ + 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + + // groupware + 'ics' => 'text/calendar', + 'vcf' => 'text/x-vcard', + + // text + 'txt' => 'text/plain', + + ); + + /** + * Initializes the plugin + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + // Using a relatively low priority (200) to allow other extensions + // to set the content-type first. + $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties'),200); + + } + + /** + * Handler for teh afterGetProperties event + * + * @param string $path + * @param array $properties + * @return void + */ + public function afterGetProperties($path, &$properties) { + + if (array_key_exists('{DAV:}getcontenttype', $properties[404])) { + + list(, $fileName) = Sabre_DAV_URLUtil::splitPath($path); + $contentType = $this->getContentType($fileName); + + if ($contentType) { + $properties[200]['{DAV:}getcontenttype'] = $contentType; + unset($properties[404]['{DAV:}getcontenttype']); + } + + } + + } + + /** + * Simple method to return the contenttype + * + * @param string $fileName + * @return string + */ + protected function getContentType($fileName) { + + // Just grabbing the extension + $extension = strtolower(substr($fileName,strrpos($fileName,'.')+1)); + if (isset($this->extensionMap[$extension])) + return $this->extensionMap[$extension]; + + } + +} diff --git a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php b/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php new file mode 100755 index 00000000000..15884887641 --- /dev/null +++ b/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php @@ -0,0 +1,55 @@ +server = $server; + $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); + } + + /** + * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request + * + * @param string $method + * @param string $uri + * @return bool + */ + public function httpGetInterceptor($method, $uri) { + + if ($method!='GET') return true; + + $node = $this->server->tree->getNodeForPath($uri); + if ($node instanceof Sabre_DAV_IFile) return; + + $this->server->invokeMethod('PROPFIND',$uri); + return false; + + } + +} diff --git a/3rdparty/Sabre/DAV/Browser/Plugin.php b/3rdparty/Sabre/DAV/Browser/Plugin.php new file mode 100755 index 00000000000..09bbdd2ae02 --- /dev/null +++ b/3rdparty/Sabre/DAV/Browser/Plugin.php @@ -0,0 +1,489 @@ + 'icons/file', + 'Sabre_DAV_ICollection' => 'icons/collection', + 'Sabre_DAVACL_IPrincipal' => 'icons/principal', + 'Sabre_CalDAV_ICalendar' => 'icons/calendar', + 'Sabre_CardDAV_IAddressBook' => 'icons/addressbook', + 'Sabre_CardDAV_ICard' => 'icons/card', + ); + + /** + * The file extension used for all icons + * + * @var string + */ + public $iconExtension = '.png'; + + /** + * reference to server class + * + * @var Sabre_DAV_Server + */ + protected $server; + + /** + * enablePost turns on the 'actions' panel, which allows people to create + * folders and upload files straight from a browser. + * + * @var bool + */ + protected $enablePost = true; + + /** + * By default the browser plugin will generate a favicon and other images. + * To turn this off, set this property to false. + * + * @var bool + */ + protected $enableAssets = true; + + /** + * Creates the object. + * + * By default it will allow file creation and uploads. + * Specify the first argument as false to disable this + * + * @param bool $enablePost + * @param bool $enableAssets + */ + public function __construct($enablePost=true, $enableAssets = true) { + + $this->enablePost = $enablePost; + $this->enableAssets = $enableAssets; + + } + + /** + * Initializes the plugin and subscribes to events + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); + $this->server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel'),200); + if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler')); + } + + /** + * This method intercepts GET requests to collections and returns the html + * + * @param string $method + * @param string $uri + * @return bool + */ + public function httpGetInterceptor($method, $uri) { + + if ($method !== 'GET') return true; + + // We're not using straight-up $_GET, because we want everything to be + // unit testable. + $getVars = array(); + parse_str($this->server->httpRequest->getQueryString(), $getVars); + + if (isset($getVars['sabreAction']) && $getVars['sabreAction'] === 'asset' && isset($getVars['assetName'])) { + $this->serveAsset($getVars['assetName']); + return false; + } + + try { + $node = $this->server->tree->getNodeForPath($uri); + } catch (Sabre_DAV_Exception_NotFound $e) { + // We're simply stopping when the file isn't found to not interfere + // with other plugins. + return; + } + if ($node instanceof Sabre_DAV_IFile) + return; + + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8'); + + $this->server->httpResponse->sendBody( + $this->generateDirectoryIndex($uri) + ); + + return false; + + } + + /** + * Handles POST requests for tree operations. + * + * @param string $method + * @param string $uri + * @return bool + */ + public function httpPOSTHandler($method, $uri) { + + if ($method!='POST') return; + $contentType = $this->server->httpRequest->getHeader('Content-Type'); + list($contentType) = explode(';', $contentType); + if ($contentType !== 'application/x-www-form-urlencoded' && + $contentType !== 'multipart/form-data') { + return; + } + $postVars = $this->server->httpRequest->getPostVars(); + + if (!isset($postVars['sabreAction'])) + return; + + if ($this->server->broadcastEvent('onBrowserPostAction', array($uri, $postVars['sabreAction'], $postVars))) { + + switch($postVars['sabreAction']) { + + case 'mkcol' : + if (isset($postVars['name']) && trim($postVars['name'])) { + // Using basename() because we won't allow slashes + list(, $folderName) = Sabre_DAV_URLUtil::splitPath(trim($postVars['name'])); + $this->server->createDirectory($uri . '/' . $folderName); + } + break; + case 'put' : + if ($_FILES) $file = current($_FILES); + else break; + + list(, $newName) = Sabre_DAV_URLUtil::splitPath(trim($file['name'])); + if (isset($postVars['name']) && trim($postVars['name'])) + $newName = trim($postVars['name']); + + // Making sure we only have a 'basename' component + list(, $newName) = Sabre_DAV_URLUtil::splitPath($newName); + + if (is_uploaded_file($file['tmp_name'])) { + $this->server->createFile($uri . '/' . $newName, fopen($file['tmp_name'],'r')); + } + break; + + } + + } + $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri()); + $this->server->httpResponse->sendStatus(302); + return false; + + } + + /** + * Escapes a string for html. + * + * @param string $value + * @return string + */ + public function escapeHTML($value) { + + return htmlspecialchars($value,ENT_QUOTES,'UTF-8'); + + } + + /** + * Generates the html directory index for a given url + * + * @param string $path + * @return string + */ + public function generateDirectoryIndex($path) { + + $version = ''; + if (Sabre_DAV_Server::$exposeVersion) { + $version = Sabre_DAV_Version::VERSION ."-". Sabre_DAV_Version::STABILITY; + } + + $html = " + + Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . $version . " + + "; + + if ($this->enableAssets) { + $html.=''; + } + + $html .= " + +

    Index for " . $this->escapeHTML($path) . "/

    + + + "; + + $files = $this->server->getPropertiesForPath($path,array( + '{DAV:}displayname', + '{DAV:}resourcetype', + '{DAV:}getcontenttype', + '{DAV:}getcontentlength', + '{DAV:}getlastmodified', + ),1); + + $parent = $this->server->tree->getNodeForPath($path); + + + if ($path) { + + list($parentUri) = Sabre_DAV_URLUtil::splitPath($path); + $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri() . $parentUri); + + $icon = $this->enableAssets?'Parent':''; + $html.= " + + + + + + "; + + } + + foreach($files as $file) { + + // This is the current directory, we can skip it + if (rtrim($file['href'],'/')==$path) continue; + + list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']); + + $type = null; + + + if (isset($file[200]['{DAV:}resourcetype'])) { + $type = $file[200]['{DAV:}resourcetype']->getValue(); + + // resourcetype can have multiple values + if (!is_array($type)) $type = array($type); + + foreach($type as $k=>$v) { + + // Some name mapping is preferred + switch($v) { + case '{DAV:}collection' : + $type[$k] = 'Collection'; + break; + case '{DAV:}principal' : + $type[$k] = 'Principal'; + break; + case '{urn:ietf:params:xml:ns:carddav}addressbook' : + $type[$k] = 'Addressbook'; + break; + case '{urn:ietf:params:xml:ns:caldav}calendar' : + $type[$k] = 'Calendar'; + break; + case '{urn:ietf:params:xml:ns:caldav}schedule-inbox' : + $type[$k] = 'Schedule Inbox'; + break; + case '{urn:ietf:params:xml:ns:caldav}schedule-outbox' : + $type[$k] = 'Schedule Outbox'; + break; + case '{http://calendarserver.org/ns/}calendar-proxy-read' : + $type[$k] = 'Proxy-Read'; + break; + case '{http://calendarserver.org/ns/}calendar-proxy-write' : + $type[$k] = 'Proxy-Write'; + break; + } + + } + $type = implode(', ', $type); + } + + // If no resourcetype was found, we attempt to use + // the contenttype property + if (!$type && isset($file[200]['{DAV:}getcontenttype'])) { + $type = $file[200]['{DAV:}getcontenttype']; + } + if (!$type) $type = 'Unknown'; + + $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:''; + $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):''; + + $fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/')); + + $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name; + + $displayName = $this->escapeHTML($displayName); + $type = $this->escapeHTML($type); + + $icon = ''; + + if ($this->enableAssets) { + $node = $parent->getChild($name); + foreach(array_reverse($this->iconMap) as $class=>$iconName) { + + if ($node instanceof $class) { + $icon = ''; + break; + } + + + } + + } + + $html.= " + + + + + + "; + + } + + $html.= ""; + + $output = ''; + + if ($this->enablePost) { + $this->server->broadcastEvent('onHTMLActionsPanel',array($parent, &$output)); + } + + $html.=$output; + + $html.= "
    NameTypeSizeLast modified

    $icon..[parent]
    $icon{$displayName}{$type}{$size}{$lastmodified}

    +
    Generated by SabreDAV " . $version . " (c)2007-2012 http://code.google.com/p/sabredav/
    + + "; + + return $html; + + } + + /** + * This method is used to generate the 'actions panel' output for + * collections. + * + * This specifically generates the interfaces for creating new files, and + * creating new directories. + * + * @param Sabre_DAV_INode $node + * @param mixed $output + * @return void + */ + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { + + if (!$node instanceof Sabre_DAV_ICollection) + return; + + // We also know fairly certain that if an object is a non-extended + // SimpleCollection, we won't need to show the panel either. + if (get_class($node)==='Sabre_DAV_SimpleCollection') + return; + + $output.= '
    +

    Create new folder

    + + Name:
    + +
    +
    +

    Upload file

    + + Name (optional):
    + File:
    + +
    + '; + + } + + /** + * This method takes a path/name of an asset and turns it into url + * suiteable for http access. + * + * @param string $assetName + * @return string + */ + protected function getAssetUrl($assetName) { + + return $this->server->getBaseUri() . '?sabreAction=asset&assetName=' . urlencode($assetName); + + } + + /** + * This method returns a local pathname to an asset. + * + * @param string $assetName + * @return string + */ + protected function getLocalAssetPath($assetName) { + + // Making sure people aren't trying to escape from the base path. + $assetSplit = explode('/', $assetName); + if (in_array('..',$assetSplit)) { + throw new Sabre_DAV_Exception('Incorrect asset path'); + } + $path = __DIR__ . '/assets/' . $assetName; + return $path; + + } + + /** + * This method reads an asset from disk and generates a full http response. + * + * @param string $assetName + * @return void + */ + protected function serveAsset($assetName) { + + $assetPath = $this->getLocalAssetPath($assetName); + if (!file_exists($assetPath)) { + throw new Sabre_DAV_Exception_NotFound('Could not find an asset with this name'); + } + // Rudimentary mime type detection + switch(strtolower(substr($assetPath,strpos($assetPath,'.')+1))) { + + case 'ico' : + $mime = 'image/vnd.microsoft.icon'; + break; + + case 'png' : + $mime = 'image/png'; + break; + + default: + $mime = 'application/octet-stream'; + break; + + } + + $this->server->httpResponse->setHeader('Content-Type', $mime); + $this->server->httpResponse->setHeader('Content-Length', filesize($assetPath)); + $this->server->httpResponse->setHeader('Cache-Control', 'public, max-age=1209600'); + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->sendBody(fopen($assetPath,'r')); + + } + +} diff --git a/3rdparty/Sabre/DAV/Browser/assets/favicon.ico b/3rdparty/Sabre/DAV/Browser/assets/favicon.ico new file mode 100755 index 0000000000000000000000000000000000000000..2b2c10a22cc7a57c4dc5d7156f184448f2bee92b GIT binary patch literal 4286 zcmc&&O-NKx6uz%14NNBzA}E}JHil3^6a|4&P_&6!RGSD}1rgCAC@`9dTC_@vqNoT8 z0%;dQR0K_{iUM;bf#3*%o1h^C2N7@IH_nmc?Va~t5U6~f`_BE&`Of`&_n~tUev3uN zziw!)bL*XR-2hy!51_yCgT8fb3s`VC=e=KcI5&)PGGQlpSAh?}1mK&Pg8c>z0Y`y$ zAT_6qJ%yV?|0!S$5WO@z3+`QD17OyXL4PyiM}RavtA7Tu7p)pn^p7Ks@m6m7)A}X$ z4Y+@;NrHYq_;V@RoZ|;69MPx!46Ftg*Tc~711C+J`JMuUfYwNBzXPB9sZm3WK9272 z&x|>@f_EO{b3cubqjOyc~J3I$d_lHIpN}q z!{kjX{c{12XF=~Z$w$kazXHB!b53>u!rx}_$e&dD`xNgv+MR&p2yN1xb0>&9t@28Z zV&5u#j_D=P9mI#){2s8@eGGj(?>gooo<%RT14>`VSZ&_l6GlGnan=^bemD56rRN{? zSAqZD$i;oS9SF6#f5I`#^C&hW@13s_lc3LUl(PWmHcop2{vr^kO`kP(*4!m=3Hn3e#Oc!a2;iDn+FbXzcOHEQ zbXZ)u93cj1WA=KS+M>jZ=oYyXq}1?ZdsjsX0A zkJXCvi~cfO@2ffd7r^;>=SsL-3U%l5HRoEZ#0r%`7%&% ziLTXJqU*JeXt3H5`AS#h(dpfl+`Ox|)*~QS%h&VO!d#)!>r3U5_YsDi2fY6Sd&vw% literal 0 HcmV?d00001 diff --git a/3rdparty/Sabre/DAV/Browser/assets/icons/addressbook.png b/3rdparty/Sabre/DAV/Browser/assets/icons/addressbook.png new file mode 100755 index 0000000000000000000000000000000000000000..c9acc84172dad59708b6b298b310b8d29eeeb671 GIT binary patch literal 7232 zcmeHMXH=70vktu%m8u{iNEJu|p@k-dEbh;oQp! z004N*&5Ug6PsrAvofQCJ0J8kPi!O*#jGZWUL@!DZii8CiV2GYrpt(N^hqc9`Fu^B& z$Li3XlkoOV6epx598L6BMs3+BQ~d+z-T;7(J~aS^_Qg_wo>&~7pbMI-s0IP?7+sK~ z8WMsGKw!P`W~WG4yHi&7=u^IEEeuFsk5h*Vrvvz7DJUS--;Y3sQ*}YxxN!P<>ophz z+%}>3>Vm!{<%F~bB8Vg`5T>l6tfGX5sH+0iRFzfLRMb^qia-?zL=z0r0INcjpqg-q z8XN`%e*b~=IDtAOj2GP2$mDxCx}*#8rceUlU~o`SkaCc!GLeJ>L$$QDzz`L%ii#55 zLWvwqprEKq1hUi?#5W8hEE!G02T<@t0&oixr=z>6WJ@7j?2K@s&Aduv@jf_Eq zv3^*8EP+A>LzSW6o%VDlZ1Fg63i*c{f&86iI^SR_DuC_+0h6|E{^l9rO{5UX-o$`^ z_WYsV_TL%OJb;3R(c^9r`oovLEA)1 zN5s+d$KcTvEQUfv6TQ5!SY-@$JAofL!3_c_-b51Fnn=cPu}SA}i)5e<1`YqV)ot+` z>jr+5Z_+o>55Gk<+z&;->4K&f4Xf4 z*@?Opg@UK}VRyv%Go$a__mho-f4Ygk@O1vF+EFt7eA{D5{^b9!NI%8a+1W>M#5WER zMEbcxQ_Klo#O-7AcN@F`hGa~opfIFAkJbOyBk+{qpKERDlW4o4eu8d|CSvGq|Ls8h z12~2BGjMyXpCge(pGp7dYwVB0|0n%X(x2Mxf_>}29Rr14jc@PhgNi;Q!9RxNw=(VM z?f=Sho2~x}@($2{gX|#V*UNwD`ZY&8EdHfy2N}O!{!7=dIoe_IFI_vx`1SH%x_-^k z4vYUp7w2EsEG&V3w+f&Lv``pA3oHbg@?#%M;1t1p-E2-|c|#H-_R1@JzcNBq&XcTyD{j<6UEo zI0B^10yQ<)ne~ii-I(2&&uI#3*c>cE#4F`4kjf9Yf_ZrA9}M*e%!^mAR}E$zo9Zu3 zORdt;YtL*^N_oifn?F+u*|JG0gxkI3G?lUOvJIf`xLe&LM~@;G2ok9*GlYr@Go9q^ zEz`#}@G`i`7&#X(r(J-?mH-)D<>Cgao26JlhL$0DkE{zbmf-K(&|l=DD*83q#uQGU zBfS~GLtVKIm&%cnvH3DXpH6YX+nd@SWMv({*9pmf$($M!medu{2S+`*XCh6t-wjlCNsFC~wA ztcbPif81a*Yr3ti?%Lg-nYeKf;M-OF)`;J@?PY=n6fA4v!4Y!-RK&GE!e|%E#rOE^ zoFOK;>>L^svjrm2h{sHx(ZWK2#aNC-Iyotq$HA~D8yWs;GH{Czl&W$vSX9co>CY_Jx^p$*HJ(W=11 z2PK+Q^PIpqE{Q$`e^qZ}9+2ghQRIQ~E)V}@K_6kS`C%KoxHO#-#55!NTr9BH z$Gf;zV1y&|YokQx-X0?N;CZI65bn4U4me(v9v zt~$4NQ0?3rdSimd1&!>(WtET&)ww0Fc3t+>j11iq;<6g?d`;6m(?o-v--hwhsT@)D z0tIfwG=F`%g`|b}Fj5F8rtn%b=Q*N4c476cdco@zbJ{%maeVAa3Aft*j9lATg{8YasCtKb*)A6 z&p)mOy?*~>Rz>8ALTwmBci{43pegY-Rz z@eqaDI>U++PdYkRyrs|SG9%{4tSuE@XNM|3erf14y>^dbo%`=<#-XIL;5_gIA^7h8{BBuh8QFCLWCMz zjybw8t#D>`diqPK?x2S16YVFy=Uha*f^b!zgR4JJ1ZT}vGx=G3Onb-tVMfdR7D0dD z`glZQZoz|4cc%WQut~kEYa)eZXSH#>_lm0s76*KCRHhC+4HUTh7P+wZx$aU#-1PwD zSw(J?U7Ia5Q(8A&im4#q-#hZkl`FX)bHqF}g8`PDLh%P9%#Y3|7lfHZ&tmX5;&hWT z<5fx_3!1T4E*<_n0Pc)>)%JSuOcLRfI-%tzZ;gP!lL*7d())_#@^@3z?2K^hXQMez zmDt>^G}ZL42){nsmzQ~bTugJ`1R|Rsv0yNHf_;8B=k-ptG#j-&17x9xZl-tKyA+#6 ztpovzDJU_K53r$#T&zg?0a^a6-O5L(t?|buEi^7SuU@r^ia5%0=)partDxHpgbYVJ zf7*m%AIoR4_ci_L>MqZ+*&Gus1R1Cu%z!(p(e54?)BHFeZReqE|p;9|xOx#=mi9BR2G+bFNE z-l%Yn{d&pegCmMktsLdiG9F(%KkR?98FB?ye>(quR3lC}e?WDi>cbomAm@FBzd$g^ zV;Gwwu)@-|QaU>tzvM-TZ+$#1$T~4m^(w?f*!&T{%)ZSN@d_#2fI@5Rm8uEfOL0E93XfHpv@9<(lpR4mCW=Wvos2vP=RffHC{UD;WbfFVr5`q+#U0o}O{-IJS~eAv(asK`d^)1aHQ ziy$S$GkI8i4v*0tgFSBcLh-pWdJsuP?pNabJmX@Z_2OKk=(*Z@o+mKR5yN;JSh0YO z;_LHf?tcg;o|L=R`eA^auo>D~-ub>gnZ&aogPZNsR-M?G+g#spUS#6M*q%}`oxWOC zeSONjTSg*?%f^N&jiG)pQcJJ-=+ayFwkTSC&8&4Qaq3x))DfvNqQv#nS&JAl^B7b(Tia2WaO$md0D6JDpTV=dCihh zQ4IexnVGqpv4g8h+U=%}z6rv`flBeFYR&i{J@Lk9WM+$=Dcj=aFB+24EdQMu1Z35i3S>ORB({g=d7Sfc(FkLfW`1UO z{)U`pu+|%A1{9(x2s#>kQGEY6mjQOyW35MuUrjoDTz&Cr=j$yJ%f!y>222$-wGR#^ zPN>LNhJplQ3fd3rD)m~H=?JTcNmm6(GWiC#@iqmIk{%gyHD^6lw7tt zhMhcptW>Ps#OeK11)H|fL)fJ|=F`I?@r=te)Adow=3hu^^>w4s zs9r~e!tV^N-`jWDP0kaCJGkt1WnrBrilEV4XHRx~iV?{UMKtsA@Ek2{pXlE0kR$8K zvUgsr*wQ{^erT2u61=e2S;I*CS-d4bT4LYe&2Z2R+NOWD&k|R#};cqIY8^5>EQfcq87f$;c)(zU)I@Er+1@JoG9p za9q{*!gAy(yOu~ku$Py95#Ec`?GJ;Omy3r6Q~g@+Je)1x%Tl~Q%D9&QWWh;Vh-wC- zOV=yUyC*dJXWMyT-U3!~it`e2?`E=SeW8nCPUFMoJ(mdqi$ZMzi+PbsS?Ln`$rt&C z22GC)MK|$t@NY4UO}@4o{^JomDd#w}qr&tsN2Ce$^FHtM``!2b+`s4fUDtck$-!DgP+AZK z0*Tlh*ze5wM{NA~`9L5p$hHm%5Qz5?(ba?IVQ+`VQ$k@l0>vMI(L=*HQ6P{Jh8~8) zhX6E)KM+VH8$;Q3O;8AtU<`HFwMW>8SpY%A12I&KFqB+kSui;S0W(Y0B7;3gb2=TCYf>=vNBJfmV7>&pw-N3~8 zQzB``P$*{}@?$x;FlS<55G~>-1v%mm<2V+=>9{bsHVgr$ZpOg>migav{v1re|BMZb zq>?rlK)}NR5)cZIX%QR_?JaN);g%k>JK*m^!_hVaekS{qD1jV#1R|aW5NH%UB_IF* zU<6>3i<67C=ahtiqv7^*GL4}eiw(38+FD4Yt2P3S&_ipZG!WWo1Y*-8h!Fvg#!~?t zjY8e<><`ymfbgx+mWd>yi6e;^1yCWb(KsrB5*-mjG=gu~$(h;8+8q5zGlKsOb%TZQ zpGy3R$&5t%E7L|%&?Fo=&=^YBA^-unND>Wd!Y*in*y9KQgi}Tw=LxT%tVlOA+`IvF zJSj4QBM%Zlp+a0jaS=g8av&!t5Enxv1OFuS2kWNLzYE(C8xiRr4B-Eewz(P2ae;po zYC^=^_85;xCr|hjlCTPp6P0W$PX1baQ$O{AY9F41TsJfXwMh zR8I4mLhO%;Pg5k5nOR-Tdcx6XN4R2$6lk6VHpVUe3;E-_E^l z;WvaTDoU-bF1J9GmD?cd>W@L*>GEeVKAk$;TWsH{xI5X?bzYQL47CPO7l5 z5ZvG24+e41nenL!Cz(oqPcyHbc%VVUvkR@m&uhl=QQqwp{9VZNc>ELdR;+XGIVS8i z7X#ASnX~?4lH%(Av>N}mv_pJ5_ObB!%i%mNHT41lHFHmWO%BsNnV~Y)XJ=OOf-3fk zwwSuw#$6q~oE2CBR_p;MG4d3O3TZC3b=)f z?%4ef>b~PcF(TJb?iLkfuMHWDe+eKSFisLGms@6*-%SzSU4m|ZI*9vfV$35Z?P9s_ z5}2=Ib}^yc^_~Bd8Rpj|zjJ$K=iY!+uo)i|VX^x~iHZpVyDZP7x*X2twh$DKJKp)( z2kw6GgE8L7esT)Qb>Tr( z9~+tndeS6(A`%>gHQC0hnDpG4a`j{Aduz4YDCCG^iN3zz)g)Fyfx|L90rp1bdXl%Y zyUK~Ei6NRKl;(cL^HNGscg=^^sLE%FyI~!%3h=7B zzszfnFp9c81oKP0C;anLqlfT^WPY1Z@7{s4JZJc5don3}Xh*wKc9qr01boh0X+-zr z-qf9*1w-|Y*FK@7JEW($S3f3=?#nlTGX>o zt(ig!wA>)%ps~lJw{NHHdL&-|VuBEU;_^bKN){=e-{_*9Qhv9FU;F#;R|PkE4)WVM z=HwJY51A>IesjE?+ILM(w!LRQOy5=DdDTD#_rgkCirx#5w|MSzRP~eG*YVei^U7Xc z@2{#@#=_rszahJG@g*g&G=ccRN0CQLUk1ly`R!v#T*v|A`7e}>QcL5Ds}Y5&?%#%{ zzTCZX>D}3tp_2ZU=(^l05g}L9Q|&iO`OUnzx40nvcAq(>PhSw~;ph5%l=1mEf#$g7 z@?r@~+^U}K&dhgLQ=A8Rcl#fy6*uz<=qY-=drm~sPhpAAyl(2XCGD-PLIw-wlM1PL zW}AeEFkz_4g;nyns7_l7;f!T0?t)?Ttnql>%J@p-XEwfP{r$*-6e+(pXH{FgGKt!o zDC*O6Zc(6eCLuU4zDA7u{L-6OLap6}QbDP{FmVwZWURR%d zA)jN{@_V&v=4G!I=!boXA}=H9HQX za=Ol`$kPr_kk=(;)$e(AbsZcL%<9CZ9xHXVJ(>DdYTOfc9wxuSKQ2y+Kz5ef;}}j= zm-RY!>Anw#Akxz&Xy5Mh+ZLT25<=s7lW`A0Df-2gvUYqeJ)%I0`IQ!l>D`Y^RCb^8 zynUl9z@@s{OY88>K3(Hz880-S-r9N#Nt77PFL(qtN)?V&kT3EcErwIw^NP{ zeNb4ET>U~W2{+9xQO-KaOq-TCxJcOEhB$M}C+RoSz8aPCSmmr9^>zRkDVLAUY<7|o@!c4td_gCN@+g! zCSG5xp{c)j!CKiPdoR)~7CrtTtp=nuH4MO}^Hv#&f_JF8fr(3ko`nr6DHXwim#9i- zcH?gJNB-vYRtT%6nZ*Phy@^U*31-w)(-{I|MfFTP&tt$|LzN7FwOz^9R|@3QHI-5G zTG!6AgaQo(YUuzM#{h)@4JzPIgn!;bQ1U2WFyl8(ZqYWEu|Lq3YR_~Zwlau0bM zVQ((GR&hm0E&l8dR*NMD^K#jJ+qp&Elk1>PBPOb#0?ebqQ4ulFIg;sj=3v3uvCm*T9iJ>!a>etUgsb!o&U zspnei)pt2djm+ zC|Tti+{zZKG{1J%A>Zgn6zH_Lif%tEkaeT7L! zR3$sXM`KHcZb3!$O!dLd!eK^6Mt8FI><G75RR_~_31AY4R>1)BBS#x|MpEfUkf*zmlzFecJsHpfVWoCLB zyw@?Gt6=OnP7ynk$d&&31>XnubtAEnk{~MexewOfWvE@IZh|FmWMZPnEB3jjvC-Gh zAPT@@o4o`FK^7-@8Z)wkX=wutKbHozw4qn=U0q$@7~t_;^UD|H^OlWg2f*WT&tJV_ zk|-2!nbR2=-rMDFl4F#U7}e1lJmkcFBVND25%a<>(FzG+E!|S9v=aFFR#24it$UAjtSmRU4DWYZp&MOpC4>2 VG`ly3;d~;1Y%Cr2-!R7}{u}gUbfEwM literal 0 HcmV?d00001 diff --git a/3rdparty/Sabre/DAV/Browser/assets/icons/card.png b/3rdparty/Sabre/DAV/Browser/assets/icons/card.png new file mode 100755 index 0000000000000000000000000000000000000000..2ce954866d853edb737a7e281de221f7846846f6 GIT binary patch literal 5695 zcmeHLdpMN&7ay0fZjDGHnIU_zPvqiXLJR^Cf~{zk;|Xg)J1@|U9t5%pOaNj{q6Y#nCn|vq-~j?D zD!diI@|=%S+`T|A7iSESPSqnU+URkp44yXxg0qmazu zo<=T67lthmOmU260&daU-HFkmL{k#n(n1o;!SDd607!sws9`h~hGP!r<6?O0#n%Wp zjBf&ln!}fp@^W#7+0vN+%uvrj&p?-mG)BRUP_3L%N#^ii5M*Ew2sWFo$42SVnPh~%si`RfX@D>=(B)a^ zvZ81pful=fZCr#{!oUG6B9p=ZDRdfa5t9%|j{wc#aGoCa5u8L^#%4q?!}!P~A_52l zr~nOQA@ue15rXzSCh!z;FvwbVqp?1+%;OuuAuxC@NCcB_^O+|jm=4le!F0yodoHW_ z{(>Q$7$DJ*7k81+WnbQ|i2P((APFI8!FT7^X({@0!Wd5=&q%(Ol z>2H1Qs07MC={=aAwETiCb)djN;ZvN}EdGfu$-k~y0F8IIV)HIh z5{E|(ArJ{WC!DoA=P{UeStb?<6;XwS#%;;LNbQ}{CM7#|?9Xh32Dh%x3TtD+4p}NX z=P33;*+id>O0iGPc83m}%^N~*wua<4LyK_8p+k!J`?_)c}(WuGwGA@!ezR_oo+Od{B|q6241IjlJgdO zt0-DJLWQ6S$lE}Psp!!rN*<=Kx7=v*sanVQU?~tKKQ9K)+6f(AnY>P8K1pf#TqeBS z$Vqb#QNlAhwEXRph1E7nj+({eIjq7oeeFw^ARD9$ScuTq;*aYf_cHWln_$v*hrBQ& zVybQRkK{?ER}xT2L#||ZYfIr%*xgm%ohRO9jr5sc06l^D+Jk(!J-KhFTSUGjL^WK!sA+18ml0HpUiCAi%da1ixGAcTjB}ST<6|c^O zb;Vjdzop!GveBdU$c$xEG{o0xpU>7~^yrB?6!Iu*93$O?E8aIC^GhRcLjuKH(doGC z>g>#i`DLb~d%7dmo&#@oN8I$V@l#0CH&zpB(caUa5C@Z_AA>t;`qo}S#BKDns84A& zktlJp&Cn}0>mFqbanu~f=u7SW=ts7#i9_@eilO9@bm=aYe?khhFtg%k-MKB2QxH5&9dJ%BoUAv9<>+K z&!i+MxZT|9@WNE%=1ECpD+IjSo$Fm`lAXsSzc$_`Q8D7beUrKS=9H#9tA5cz@-zSJ ztyNdD&YeeuJ|~@lF^h(OGlz>j(wK~pb2<{61@xBK&W$9|T{>SKSO2bb(`g&OtP%DA zSDX9ZwR_qkoml4}`3K`XTB<&#>#7D6*Wi)|UD<%YW&@pE`LJijg{Ef5S5@gJ>|$)n zj%rk$h8I0@tT!%BTo{C!<@=lp`1OV<&F`siSjOE0BNma|_VK=(xxE|Ls0yV+7B-=O z=m_3H7&6yJKijn16Ir=>-HiidZ=^#X(rR`nK>FoG zN~@eDM8L5!cP+`l7kRHz1{K!D7eQik+D6=!^V?NCwRY zd4*hGrygYw%hs9nJLmK_ z&D@&!ISrcJ+5EvCQkavY^)y$uLcCzGQXyPa;);)+Z%Jp=Bz8hax`~|In?Enk3BF@? z&%35i)iK4Q_;pj@Wr^2gt08j@=Z9+iE4#Uqz4DfzNv<;}_ReO{+l-83CtIBIPdTy=p?FxkVsl{i?s8V`{<&J} zd&Sef7bsM?L{moBE_j?(U<-m*@mDS{9d0Ww#M?RUh}QgLv-llgMDdZ)(OIJZMiEXAELrv z`K@ze{)cl57I`gKme=kVBbx&L#O06>H(N9R#EEb$-IT@vZ7O7i3cHSe)Sxw-sPw@l~2F-b$rpmHb^+G_g^smmN*w zLHndv&MEb0CKi{MkFs>@YPc5ma<1QH>m3Dc%7ndO2G8%|j+5UUAI9V)btp4?bEBy2 z8n(6fn3%Cp_vy5vLD9^&Ej}v)gcG2br#O4hDyNySR+ySvq&LeydAJ*jABP)&$qY^P zW^2yc2^uAkCea|`C9#I5`xL!XU5M9nr!PFUcqO@;g4J)(rE4uS4W-RH!KrD>nonw?_3 z-{*F+?e3#yLgQT_RW;EA`%Bcm@0wRkKe2TLxc=m+MvcR^Hai_#>zD$46R(reH$M=t z>)F<6JuzkG3uWEEzaGrDt?frTyKHh4IrgT}e6RdZPsT&%9hpZIj@^s&IrVr-6P=$U&LPIV iv*os~CbdYl&#K_=OkBmrhgdFt(si=ij;pWxEzMhwDg6VRB9Bbk!O z6tW@c#N~iA9v>u-KoWsq0uoKBtI5n{}YsCay6 zXecgpHIB45La^gu2Pk;h~+gfLUcWpMrcU>L`Qr@4?^ zsuNNYCM1NckxX+eVll;tKr|we+=&D#flMVD8xV+80%6)C(2U8TGWakg9duh6)1MX80*Pk(rsS>Cv||GyLCBr&ySORpJLGTA=V} zrm3P(10fE}94j(n!hTS2pb%>@c&Zw7f|xLflo3Ln7|V56h-ho4e_#8jQ-s& zzd$I28_fSNvx09LcmJct?A`0Q3wm*e z`r?VnFDmKiCBuXFJooSP4*}5gRtywBz3qeGUmH}Mtd5LTuaQb6O%3@sYx9blBsI;A zlExZ^^pW9bCUwadsyU_q`ZA={G*Tl`6spRN&H3$BZ*Qcc;iN?*V?=h*$S;1fRzOvg zjx40UKgPN3tm+bUKvGRcm|>Yy13P6EO366rn9RIDhtr4DCd@2ZL505eHF3AQ{I=N7 z_jjkWkMSlR7@ryWaG*i!S3!YTDG*XJ@b9UP)|cl+qwZ`%t<(=+x(`xU&|`0nk3JZ^ znm1clS#tZfLY}W5a~(Z*$qio`fl$hywQpZacC%KC^Qx;3SD2J7Z`+$cow$>C+IqvA z?RR-)3IsXds1@arpAx(cVtXzr)_BcVd~V-bUKY>5^sNxQ(tKZ<tM9$5tdWz%ej0ez^ya?f6Uo&{%mXC{m5-D|#M})nH&YH-de-MQ_7o1- z#CD#)h-GilV$|^-wK4g~F|==SXVAR;kpJOJ1QJh|oFtLRE%fX| z6QYi#L~SE1SFVxVR-KodqG8#ke`e#DwxLZ(TjPcNUV+ccwwC;%P~eLCW!nG}$^T5* z2KCN+25ld-C9`res#RIF2P5tNTFFQKZl)nOJ3ud(wWUs zigV_31!`Y>wXYA;a?fF$(=%0GqwWNR=hK#(^eg1=iA+9BvdZsrMKSZFgBQm?$NQu` z8ZI~ectr(JHJI%V2a*>8RF)v5JGOae_N$Wm${=X$hi-;9sN)kvM_4=Pfs=| zS6fzbZGnxWj`*s@zJp#mRncNO44E8)p~G)x#}$pp#DF0V_ifP^|3taUb;iljLK-u= zA6bT$8xsfkC2wEwO#~I!zKmC8__u1;#63TLz6lka$q6`+BpOakz5ZZrZ}=A#73X%3 z({QtIxVNXrh(9j^5Q#4!7NNWO(CB>_QSo7(eHhPOeUC z?V^-SvGAl$U%2WnSuJ;3uuJhX*QK-%=kK-0b(|&s4!GIP?Z1h-aVs>vOUAkGm^gR36sr&_zj%NG!0qfsPSSWYtzWaqIns?Yya)Zez_}3HkrU=7y$!KPW zZqo*AUyHJ*^w{93gBM1h74AJPqoQZOtK4%?yY{_CD1T+9OuhO?(MDGYTIw*KlH3>b zk{(_!kE{DF^KfdIM`vPMhm!umMB}U?x0K|j^mm>bN1vDvM4ldQnvU{wMbGop6+;X3O=sODx{wXdGn!#Iowd2S3j=3v%!vAF1s^TonKOpMr4QroDy zquS4he|@yd1iv=v5>ENHRZ|4FXT>M&JyMF^WMy~ zw<@-N9+-ID5_^>URu8zEs0$dnY|E(MuOEe5*(a%}q7^4R-GMnWm~Y3pugtL=B#07U zXtoU}A4b&&Fjh&IkTl%00j+p_z%KoqL-6H zsy0St$fopeoNbs^0c&p6~Uw>GXW; zOnr}u;fk}!A*9*X0m+VuA=cNgd}=IGkJO6S`nCFi_>?27XD9XAi>;K9$g&uxo*Iv% zN0vCW6uK=7Ymg@KEN`Tq0*&i*<@zl0-FwdV`f-&ABBYP9l zmiYvvoml12_ApZyNX5#l7|GAe=qHVnpNUhum)mVcXL~&dyBYC$&+{kjvMrxjRlfHa z=*~;8`n4bAQ>(4E_l(})VnJ}E-H#ZyGF=R`%OK2VpUn?#rMG@{Z-l*1a~S z1#>P&^t~(6`?%86zGjT^@;pwC}Q1RrXH8pScuyuG^&BCf5knD@5o zK&{USOy%2DN>RroTCx-MxT4oq7D$qmE~dBEt;$#{8h6o>mjZQNW$3K>`0h!3+Z^?0 zq#?|y0K3Zesv@7I_q+ol(sUCW*PZ(!&TCuIQtx%>IL6+g8JE!i^75e35Vq1nvVQz++X-2Na-jNuQTP-uom}bmOGfQTu9TlY;TkVum z;*bjI!YPtVa*0h_yQ|zQicoe*?XuSpyE>ioJZC-6thN62f8YDQ|NH&__e{Kp`${d% zxtag~Xt}yLd7@9U@`qCc01P;#b~*rHYxrzm#Mf;VgChv%45-EkfBHh`XNCAh=B`mkqWXc&RKp2cb zpgc?{k}>2g!Wb?CeOG=a5x}t!M8G20D+xhgHxJNJEQLWDkz&aqTP*=;Hbm-Dstw)7 z0(29LKzoT4BvU~unY;v~EM-{PFsyCB&lkZ~6J$!cAq-Ea6`vW=5sMItAQA?N6cG_Y zjIbh#r92XaPN$Q|R1%eHiAGq;6e0wYTZ&{RN{Dd`Cs@Xj@+Al#B~@ZV!Qya)MIfN_ z;KXtui6@^IipVA@M6%Dup%#+lkc31bl1b9B7}7VH|2yZ)U@m7eRuV21jxB)8A;Cg8 z3>G0Wl!G!3juMXRVfetoUI>JY1xzLf3&lKC9+%HSU@ju&h(khPn8=04xX@gN8(I=B zgg{PcCX0YtOt&OcEU8pBh0Gw^Feo&0GKE1Vk9h<#xf}*Z3PXrks`Tu$YhLiC@zJ=6 zLcZ;4A%8P01=$ghlq-&q3HVHs(oS?{JZo$;k;Wu_gQ{fV{!@uBnCykf*G$TyFockZ z$0Eorxo`*+E<^~n0~w{D8^nb{w2Tn?#xY)CBDY^Qc7x>{VYm#H2Zo5HpjQ|q3+0P= zXb=yIb@J5*PS=!iUbbxqY3$^8Q#3I?(=#zGZ2%*j5aOr=U zl}%_2`>w`Gl!+>Xh!`BN^VfjmqX}hWi}_Nxav|fp_Ww7$;*9ce(!pQ__#dSQzo+6W zOaEaV5B=g4qEg1cp{E<|Eu_ijf(|Cz6D&e|k`!$|{n#~4XyclLIQt@A;t&MgelRfJ zV_Z@5U{4t0DmK-^OaPeDuKi z(&CWpjmOsQtr2w2>c76os!MO>Zd~@+fphg(f}aGx)P_KmV|7e|d`h-{(CbSd9%vhF zD-g`C@IGm~^*x?y6f)b$$f(kL+o!)U$40xV@ob+MB!+$Q;zep%A2)_S`lfgGV>2B9 z2hQ>-i5k`pru^}+Y(wx;#cNYXHhY%IDy=k10QI-Puy3raN~UJp(EI4je@<`VZ1?HVUK1>j=z9~ zl{0=f)Ri^teW7EQA8LJxp6vPl;CvP5(@r}mAB(9vX%?D)md|UCdeRjAi)V_}+@8Lp z<--RKwdQm!dA#D~+`h&nBG9rObL#GJ`OLCY*<82y(=%=Ca^Kva>j<>o>W_nTc9+v$ zsNwXY*CZaHb&-yW@e%gyZIQ z)%t;po`#$EpHyEF*Xd?z;`)+cyR-cdmmg~j?&S?J&*!SFN`tMJ>kYRSAD3;5aQ#Ii zR{NI2+Xp~teVKTnKK^9hrkBZ>1kONW?f{S@C>#n|_`;ai=yQcbzlq zS~HTLQzFs0=pWLDpVNzG7v0@QCT}%0UKDCq8QM1b+p+FOU4xc{)j9aq!g%3Ri@MHd z3bpF1Bb03<&FQmrcKOn=%ih)$<$>b7F#jcPcR2cSf=#=#u@$u{ih+?cf|O@bZNnd7 zgKA!(%1y%tjCajQ(0yx{R}nH%;C6GMm|1x2rGl zWlUuHy>q<6=1a1)o@~uoR0lQK{6UTpm3ma}uX76XE8A|^kq#>M#}dueH?m4DTuN4r zx5~gRX5)G^25RslhBCNg*)i`y`%H2nt(LsUp>ijM#;*G4VZT~;Af@(#cA-jy_jK*I zUOQv_b7x@Q&<^*cspF=MEX1k`>{O8WH66uqwwAFHxtI6d1*D>Wy$EXVlTxk4Wqu8f z7pSbP89Cbr-Hi*kUw)Ki{CfEcgCxP`7w;Z!dA%oSTc)KECZ(XTSuFb{z@tEIWSp8j6-6W8K(M@5_M zzM(ap>AgjFUdfp&hob@i^-&!S%)^__m?ce)TcZPr$q<4Xd?BHHSI3IyO0DU()TXl(gK1eqCMlT5UAa%-vKs*e z{1f4!PyJ0*MUPbL)dU&7_9Lq@1gY)9cQZ`ZT7hdl{S1!vUE5%}_BJ6sJyyrpsY-CI z*LF*lK$;-lW$ky-w+=Ms&LPicKhRG>`;bXD&CR(v|9MK|Ky|y%;EDyN%xC)aYr1&`JU!`) zU`3-!RzOL*K6r~#TZ=CUG47?UtS$+c&%6n=q;a(zkC;{Ty<{g*)hWBOG^q9KmSxpt ze|j9eKR3^y1z4}zR2x?ALSLU0aFj~G5oFA%A#gxM$>ZYQhTOKRZqbjE>~73kxI^Tg zm}+D?;NE)t8bh(^J};-Md&W6t`*ob+{rStcW``Q%lQLXv%9Q_RU7g*X@*Fm7{~MA6 BY2g3> literal 0 HcmV?d00001 diff --git a/3rdparty/Sabre/DAV/Browser/assets/icons/parent.png b/3rdparty/Sabre/DAV/Browser/assets/icons/parent.png new file mode 100755 index 0000000000000000000000000000000000000000..156fa64fd50f15d9e838326d42d68feba2c23c3b GIT binary patch literal 3474 zcmb7H2{=@1A3sx*ElZmr6{pFPFk2dCvP~gNlqE}xoS8YsL^ES%F!9N9n-C#MNxEne zBBg~(j5Sk9R1{fSrMg$$D9Z93RJZPTzwddzInT^F?|J|K-|zSS{_p#Lo{8V=yg^Ap zLjeE)C3`z-SL9BZ`pU@w01BKVoeu!$Cbqkm(93BfmBHPOgP2@8j1%qVAyEKeW+~!9 zi~v{&(qR^xV~!oHsK$b9ra9JgjT6C%w;uLq+lBFAw=idSMpyuY!o*ryD42<;2*7Sw z2!W#AfgAxxEzMhwDg6VRB9Bbk!O z6tW@c#N~iA9v>u-KoWsq0uoKBtI5n{}YsCay6 zXecgpHIB45La^gu2Pk;h~+gfLUcWpMrcU>L`Qr@4?^ zsuNNYCM1NckxX+eVll;tKr|we+=&D#flMVD8xV+80%6)C(2U8TGWakg9duh6)1MX80*Pk(rsS>Cv||GyLCBr&ySORpJLGTA=V} zrm3P(10fE}94j(n!hTS2pb%>@c&Zw7f|xLflo3Ln7|V56h-ho4e_#8jQ-s& zzd$I28_fSNvx09LcmJct?A`0Q3wm*e z`r?VnFDmKiCBuXFJooSP4*}5gRtywBz3qeGUmH}Mtd5LTuaQb6O%3@sYx9blBsI;A zlExZ^^pW9bCUwadsyU_q`ZA={G*Tl`6spRN&H3$BZ*Qcc;iN?*V?=h*$S;1fRzOvg zjx40UKgPN3tm+bUKvGRcm|>Yy13P6EO366rn9RIDhtr4DCd@2ZL505eHF3AQ{I=N7 z_jjkWkMSlR7@ryWaG*i!S3!YTDG*XJ@b9UP)|cl+qwZ`%t<(=+x(`xU&|`0nk3JZ^ znm1clS#tZfLY}W5a~(Z*$qio`fl$hywQpZacC%KC^Qx;3SD2J7Z`+$cow$>C+IqvA z?RR-)3IsXds1@arpAx(cVtXzr)_BcVd~V-bUKY>5^sNxQ(tKZ<tM9$5tdWz%ej0ez^ya?f6Uo&{%mXC{m5-D|#M})nH&YH-de-MQ_7o1- z#CD#)h-GilV$|^-wK4g~F|==SXVAR;kpJOJ1QJh|oFtLRE%fX| z6QYi#L~SE1SFVxVR-KodqG8#ke`e#DwxLZ(TjPcNUV+ccwwC;%P~eLCW!nG}$^T5* z2KCN+25ld-C9`res#RIF2P5tNTFFQKZl)nOJ3ud(wWUs zigV_31!`Y>wXYA;a?fF$(=%0GqwWNR=hK#(^eg1=iA+9BvdZsrMKSZFgBQm?$NQu` z8ZI~ectr(JHJI%V2a*>8RF)v5JGOae_N$Wm${=X$hi-;9sN)kvM_4=Pfs=| zS6fzbZGnxWj`*s@zJp#mRncNO44E8)p~G)x#}$pp#DF0V_ifP^|3taUb;iljLK-u= zA6bT$8xsfkC2wEwO#~I!zKmC8__u1;#63TLz6lka$q6`+BpOakz5ZZrZ}=A#73X%3 z({QtIxVNXrh(9j^5Q#4!7NNWO(CB>_QSo7(eHhPOeUC z?V^-SvGAl$U%2WnSuJ;3uuJhX*QK-%=kK-0b(|&s4!GIP?Z1h-aVs>vOUAkGm^gR36sr&_zj%NG!0qfsPSSWYtzWaqIns?Yya)Zez_}3HkrU=7y$!KPW zZqo*AUyHJ*^w{93gBM1h74AJPqoQZOtK4%?yY{_CD1T+9OuhO?(MDGYTIw*KlH3>b zk{(_!kE{DF^KfdIM`vPMhm!umMB}U?x0K|j^mm>bN1vDvM4ldQnvU{wMbGop6+;X3O=sODx{wXdGn!#Iowd2S3j=3v%!vAF1s^TonKOpMr4QroDy zquS4he|@yd1iv=v5>ENHRZ|4FXT>M&JyMF^WMy~ zw<@-N9+-ID5_^>URu8zEs0$dnY|E(MuOEe5*(a%}q7^4R-GMnWm~Y3pugtL=B#07U zXtoU}A4b&&Fjh&IkTl%00j+p_z%KoqL-6H zsy0St$fopeoNbs^0c&p6~Uw>GXW; zOnr}u;fk}!A*9*X0m+VuA=cNgd}=IGkJO6S`nCFi_>?27XD9XAi>;K9$g&uxo*Iv% zN0vCW6uK=7Ymg@KEN`Tq0*&i*<@zl0-FwdV`f-&ABBYP9l zmiYvvoml12_ApZyNX5#l7|GAe=qHVnpNUhum)mVcXL~&dyBYC$&+{kjvMrxjRlfHa z=*~;8`n4bAQ>(4E_l(})VnJ}E-H#ZyGF=R`%OK2VpUn?#rMG@{Z-l*1a~S z1#>P&^t~(6`?%86zGjT^@;pwC}Q1RrXH8pScuyuG^&BCf5knD@5o zK&{USOy%2DN>RroTCx-MxT4oq7D$qmE~dBEt;$#{8h6o>mjZQNW$3K>`0h!3+Z^?0 zq#?|y0K3Zesv@7I_q+ol(sUCW*PZ(!&TCuIQtx%>IL6+g8JE!i^75``Y6gr#$Vf>RpCKLvN z^z@Wgh%9j~V?{(G(ZN9^8k~#+r8YQ0GFRda0Ax=A7o;UY2qpnyvN-P8;j`zl7#7_f zyL?eFA(-m}C9?c7cu;u8(g<2c63vy4_4Lpn3rG@xWC#H|IEN zMI=Xi%=;hKLjyzR(HW#L>f-m|B$7Ke5ka^lJU%Tg4VUJCgLzE6y{oG$oUVFczU!rZ_2oL0;H z&5t^eUu9VPeU&*d$vSj%P9WQSobC=a=D*AN7q~%aTI07QFjZNbuuwkYoe>#hX zKy(DA!3+ij;pmVof$5w`lvE@U=J7*dK1<4`ghMIG7&4tkn%b&NoMN5AMy8}Gkc;vsT7Ri^K?+A#O%>REy`Xn}4zK=*gQyluhl5<5v{5cF*c5FVjVNvKj zUjYKrc^{6|f9ri%NcyL>VUkHCYp744htOcUr0u5;#NU7;yib8gKzV~|BzLPc$t6mCu;ISHTOg@8{`1v`W!_A;zE{UtDEr zWmQzGgfqu3{F+s9ezhnZa2)Z9uFly_+2XbaSRA()h1LeQ%&&Ta2PA<^aue(oO@qP85~&ePYGTyx|%5fgoi~uQi^> z^R~lr#QqcJ9`=+ib7xnz%$~dZ(#8E~<6(XZPiMH$_!Ml?JJ6rtbw!X2C~!EOMyL41 z-v0ivmTOnq+Am#F4`QP_Mhe0h8NZ5|?KO3W-!!Cjs8aOMy5sXFJX8AT#T`)B&>#fW zxbD<`wpV0`12&Y+{k{Meex?3e$;QU!mcJ4v$8TxiUPS|M4XSc}dtiW{(Zr;vuD!$36|9bDk{df1+vF6yo{oS3n4FqdohLjw_`5~{?3hM@%4|Xg-TL<{!O54QXQz7JRVWFg}t9!8~JKOWQ zXT$280Ugww0mhTe$9;WZJdLKd-;~kNxBIDXL_kvgLD9N(f|+G{RN;<4&mB8hEZn+a z+3YxvY)Whl6NGL$-)81KwT}IPb3++5b4S$3MoP7|K-3wHW^b(cq+{x2V4&ZIg?(=#W?0>RtB8i22g=Mf#Bi7Z;Qg%I8uy z*SJIR4Cq4fut#HiS#`znyk{DP`QOH`zcljnPSW~OyLiaeYxg{rZNc>=*5$S#6 z$DhrKGs_ges@%z*nI(Rk)O@Yryvm;X-SyNTRcbufHvzWR=#hhc1O460))F6`PN|DY z3N-G<8bnv+8mVk<3D`e5IeDrxy2})>S8_tJLtXkDs_SdLBZDEVnwznb8v)mu!!o08 z7^@cU@7;4z%`E)kNXGcUL9#`|B&23EE;ehpb-DTai0G=h~gE@oaLKP&CrKmLvQXGSLUx*u87evamzB<=YVdFE$c6=%+IIj zb(*XE*lGwo=q*;Z1ER)M`pb3R5s5^UVf$+Om}t;B)R!2drR3M%)xq=tY%(cF401Bm znz2|^8m9-u7y=s&RCQ@I)%Zd4l*@;n%^BA+O8oYV; zmSUuz`b>|k@p)ISH#d9PaR=L0-KLNK{u<^UE@8}_72?Kkaasu|BFt3t;CyiGfmo|8 z(kAw1)_s##8y6c|6xVLbRqmhnZ1@VU&hK0arg4ab{>^E|*JUl1MFe%lJw=>GLdz5O zqOLY_RmOhP?FW+24ZmO?*^Hr+W!1tihruhm?RS;tp3u`h`8t|>`Ww6Qg=sQYTaFybZ9Z5Y@)k-y*mr@hLWqYfqA;VU2Q zHBNnUR%_UBz^IQtcD4Ra(_LZl;oJ^`p5m8BPp(6#hwq6xvtIJ3L8A|>e|^?8zem00 zJ}v)`(cV4{T4cWWn<_^C={vqR@1<>k^WGgle2cM~Z}`oF!WYridplU=KYwT0mV}rO zX5u#U!P=-pW9^}4eV(a$l|!cJ(pT5KcRxu8R2%DxtGdD2wM$d{a=lZP&BEZyfE7_c zor&e>lw>hoN`E&ponu-*TOm7XrJC1)R{9#Rb!W65F4!5Ar}WPIboMORSS924n9T=H zFK9bUq3sFy!&sxys8c8RRp1}>PijmWx~i8JZkQKto%Ps~doqk#*?Q^i*trmf%RqJU z;#=VlXJ@*Ot@Tm7cQh70`TUgTilj9ygRTDMD_Wna-`nRr)Vk*kX+&p+_hoCb$go`z z(mGzZL{lr@+q}G%)%W7iTIF2Zt6P@o>RvYSKjuC`!I)?+XJl_PxHBh4;f`g!!E>A4VP5$SQ5CLF_=0&A@lnwhleUz`(>k&GBZWCDT3kgv cn$validSetting = $settings[$validSetting]; + } + } + + $this->propertyMap['{DAV:}resourcetype'] = 'Sabre_DAV_Property_ResourceType'; + + } + + /** + * Does a PROPFIND request + * + * The list of requested properties must be specified as an array, in clark + * notation. + * + * The returned array will contain a list of filenames as keys, and + * properties as values. + * + * The properties array will contain the list of properties. Only properties + * that are actually returned from the server (without error) will be + * returned, anything else is discarded. + * + * 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. + * + * @param string $url + * @param array $properties + * @param int $depth + * @return array + */ + public function propFind($url, array $properties, $depth = 0) { + + $body = '' . "\n"; + $body.= '' . "\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"; + $body.= ''; + + $response = $this->request('PROPFIND', $url, $body, array( + 'Depth' => $depth, + 'Content-Type' => 'application/xml' + )); + + $result = $this->parseMultiStatus($response['body']); + + // If depth was 0, we only return the top item + if ($depth===0) { + reset($result); + $result = current($result); + return $result[200]; + } + + $newResult = array(); + foreach($result as $href => $statusList) { + + $newResult[$href] = $statusList[200]; + + } + + return $newResult; + + } + + /** + * Updates a list of properties on the server + * + * The list of properties must have clark-notation properties for the keys, + * and the actual (string) value for the value. If the value is null, an + * attempt is made to delete the property. + * + * @todo Must be building the request using the DOM, and does not yet + * support complex properties. + * @param string $url + * @param array $properties + * @return void + */ + public function propPatch($url, array $properties) { + + $body = '' . "\n"; + $body.= '' . "\n"; + + foreach($properties as $propName => $propValue) { + + list( + $namespace, + $elementName + ) = Sabre_DAV_XMLUtil::parseClarkNotation($propName); + + if ($propValue === null) { + + $body.="\n"; + + if ($namespace === 'DAV:') { + $body.=' ' . "\n"; + } else { + $body.=" \n"; + } + + $body.="\n"; + + } else { + + $body.="\n"; + if ($namespace === 'DAV:') { + $body.=' '; + } else { + $body.=" "; + } + // Shitty.. i know + $body.=htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); + if ($namespace === 'DAV:') { + $body.='' . "\n"; + } else { + $body.="\n"; + } + $body.="\n"; + + } + + } + + $body.= ''; + + $this->request('PROPPATCH', $url, $body, array( + 'Content-Type' => 'application/xml' + )); + + } + + /** + * Performs an HTTP options request + * + * This method returns all the features from the 'DAV:' header as an array. + * If there was no DAV header, or no contents this method will return an + * empty array. + * + * @return array + */ + public function options() { + + $result = $this->request('OPTIONS'); + if (!isset($result['headers']['dav'])) { + return array(); + } + + $features = explode(',', $result['headers']['dav']); + foreach($features as &$v) { + $v = trim($v); + } + return $features; + + } + + /** + * Performs an actual HTTP request, and returns the result. + * + * If the specified url is relative, it will be expanded based on the base + * url. + * + * The returned array contains 3 keys: + * * body - the response body + * * httpCode - a HTTP code (200, 404, etc) + * * headers - a list of response http headers. The header names have + * been lowercased. + * + * @param string $method + * @param string $url + * @param string $body + * @param array $headers + * @return array + */ + public function request($method, $url = '', $body = null, $headers = array()) { + + $url = $this->getAbsoluteUrl($url); + + $curlSettings = array( + CURLOPT_RETURNTRANSFER => true, + // Return headers as part of the response + CURLOPT_HEADER => true, + CURLOPT_POSTFIELDS => $body, + // Automatically follow redirects + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 5, + ); + + switch ($method) { + case 'PUT': + $curlSettings[CURLOPT_PUT] = true; + break; + case 'HEAD' : + + // do not read body with HEAD requests (this is neccessary because cURL does not ignore the body with HEAD + // requests when the Content-Length header is given - which in turn is perfectly valid according to HTTP + // specs...) cURL does unfortunately return an error in this case ("transfer closed transfer closed with + // ... bytes remaining to read") this can be circumvented by explicitly telling cURL to ignore the + // response body + $curlSettings[CURLOPT_NOBODY] = true; + $curlSettings[CURLOPT_CUSTOMREQUEST] = 'HEAD'; + break; + + default: + $curlSettings[CURLOPT_CUSTOMREQUEST] = $method; + break; + + } + + // Adding HTTP headers + $nHeaders = array(); + foreach($headers as $key=>$value) { + + $nHeaders[] = $key . ': ' . $value; + + } + $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; + + if ($this->proxy) { + $curlSettings[CURLOPT_PROXY] = $this->proxy; + } + + if ($this->userName) { + $curlSettings[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC | CURLAUTH_DIGEST; + $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; + } + + list( + $response, + $curlInfo, + $curlErrNo, + $curlError + ) = $this->curlRequest($url, $curlSettings); + + $headerBlob = substr($response, 0, $curlInfo['header_size']); + $response = substr($response, $curlInfo['header_size']); + + // In the case of 100 Continue, or redirects we'll have multiple lists + // of headers for each separate HTTP response. We can easily split this + // because they are separated by \r\n\r\n + $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); + + // We only care about the last set of headers + $headerBlob = $headerBlob[count($headerBlob)-1]; + + // Splitting headers + $headerBlob = explode("\r\n", $headerBlob); + + $headers = array(); + foreach($headerBlob as $header) { + $parts = explode(':', $header, 2); + if (count($parts)==2) { + $headers[strtolower(trim($parts[0]))] = trim($parts[1]); + } + } + + $response = array( + 'body' => $response, + 'statusCode' => $curlInfo['http_code'], + 'headers' => $headers + ); + + if ($curlErrNo) { + throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); + } + + if ($response['statusCode']>=400) { + switch ($response['statusCode']) { + case 404: + throw new Sabre_DAV_Exception_NotFound('Resource ' . $url . ' not found.'); + break; + + default: + throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); + } + } + + return $response; + + } + + /** + * Wrapper for all curl functions. + * + * The only reason this was split out in a separate method, is so it + * becomes easier to unittest. + * + * @param string $url + * @param array $settings + * @return array + */ + protected function curlRequest($url, $settings) { + + $curl = curl_init($url); + curl_setopt_array($curl, $settings); + + return array( + curl_exec($curl), + curl_getinfo($curl), + curl_errno($curl), + curl_error($curl) + ); + + } + + /** + * Returns the full url based on the given url (which may be relative). All + * urls are expanded based on the base url as given by the server. + * + * @param string $url + * @return string + */ + protected function getAbsoluteUrl($url) { + + // If the url starts with http:// or https://, the url is already absolute. + if (preg_match('/^http(s?):\/\//', $url)) { + return $url; + } + + // If the url starts with a slash, we must calculate the url based off + // the root of the base url. + if (strpos($url,'/') === 0) { + $parts = parse_url($this->baseUri); + return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port'])?':' . $parts['port']:'') . $url; + } + + // Otherwise... + return $this->baseUri . $url; + + } + + /** + * Parses a WebDAV multistatus response body + * + * This method returns an array with the following structure + * + * array( + * 'url/to/resource' => array( + * '200' => array( + * '{DAV:}property1' => 'value1', + * '{DAV:}property2' => 'value2', + * ), + * '404' => array( + * '{DAV:}property1' => null, + * '{DAV:}property2' => null, + * ), + * ) + * 'url/to/resource2' => array( + * .. etc .. + * ) + * ) + * + * + * @param string $body xml body + * @return array + */ + public function parseMultiStatus($body) { + + $body = Sabre_DAV_XMLUtil::convertDAVNamespace($body); + + $responseXML = simplexml_load_string($body, null, LIBXML_NOBLANKS | LIBXML_NOCDATA); + if ($responseXML===false) { + throw new InvalidArgumentException('The passed data is not valid XML'); + } + + $responseXML->registerXPathNamespace('d', 'urn:DAV'); + + $propResult = array(); + + foreach($responseXML->xpath('d:response') as $response) { + $response->registerXPathNamespace('d', 'urn:DAV'); + $href = $response->xpath('d:href'); + $href = (string)$href[0]; + + $properties = array(); + + foreach($response->xpath('d:propstat') as $propStat) { + + $propStat->registerXPathNamespace('d', 'urn:DAV'); + $status = $propStat->xpath('d:status'); + list($httpVersion, $statusCode, $message) = explode(' ', (string)$status[0],3); + + $properties[$statusCode] = Sabre_DAV_XMLUtil::parseProperties(dom_import_simplexml($propStat), $this->propertyMap); + + } + + $propResult[$href] = $properties; + + } + + return $propResult; + + } + +} diff --git a/3rdparty/Sabre/DAV/Collection.php b/3rdparty/Sabre/DAV/Collection.php new file mode 100755 index 00000000000..776c22531b2 --- /dev/null +++ b/3rdparty/Sabre/DAV/Collection.php @@ -0,0 +1,106 @@ +getChildren() as $child) { + + if ($child->getName()==$name) return $child; + + } + throw new Sabre_DAV_Exception_NotFound('File not found: ' . $name); + + } + + /** + * Checks is a child-node exists. + * + * It is generally a good idea to try and override this. Usually it can be optimized. + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + try { + + $this->getChild($name); + return true; + + } catch(Sabre_DAV_Exception_NotFound $e) { + + return false; + + } + + } + + /** + * Creates a new file in the directory + * + * Data will either be supplied as a stream resource, or in certain cases + * as a string. Keep in mind that you may have to support either. + * + * After succesful creation of the file, you may choose to return the ETag + * of the new file here. + * + * The returned ETag must be surrounded by double-quotes (The quotes should + * be part of the actual string). + * + * If you cannot accurately determine the ETag, you should not return it. + * If you don't store the file exactly as-is (you're transforming it + * somehow) you should also not return an ETag. + * + * This means that if a subsequent GET to this new file does not exactly + * return the same contents of what was submitted here, you are strongly + * recommended to omit the ETag. + * + * @param string $name Name of the file + * @param resource|string $data Initial payload + * @return null|string + */ + public function createFile($name, $data = null) { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); + + } + + /** + * Creates a new subdirectory + * + * @param string $name + * @throws Sabre_DAV_Exception_Forbidden + * @return void + */ + public function createDirectory($name) { + + throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); + + } + + +} + diff --git a/3rdparty/Sabre/DAV/Directory.php b/3rdparty/Sabre/DAV/Directory.php new file mode 100755 index 00000000000..6db8febc02e --- /dev/null +++ b/3rdparty/Sabre/DAV/Directory.php @@ -0,0 +1,17 @@ +lock) { + $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock'); + $errorNode->appendChild($error); + if (!is_object($this->lock)) var_dump($this->lock); + $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/FileNotFound.php b/3rdparty/Sabre/DAV/Exception/FileNotFound.php new file mode 100755 index 00000000000..d76e400c93b --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/FileNotFound.php @@ -0,0 +1,19 @@ +ownerDocument->createElementNS('DAV:','d:valid-resourcetype'); + $errorNode->appendChild($error); + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php b/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php new file mode 100755 index 00000000000..80ab7aff65a --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php @@ -0,0 +1,39 @@ +message = 'The locktoken supplied does not match any locks on this entity'; + + } + + /** + * This method allows the exception to include additional information into the WebDAV error response + * + * @param Sabre_DAV_Server $server + * @param DOMElement $errorNode + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { + + $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-matches-request-uri'); + $errorNode->appendChild($error); + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/Locked.php b/3rdparty/Sabre/DAV/Exception/Locked.php new file mode 100755 index 00000000000..976365ac1f8 --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/Locked.php @@ -0,0 +1,67 @@ +lock = $lock; + + } + + /** + * Returns the HTTP statuscode for this exception + * + * @return int + */ + public function getHTTPCode() { + + return 423; + + } + + /** + * This method allows the exception to include additional information into the WebDAV error response + * + * @param Sabre_DAV_Server $server + * @param DOMElement $errorNode + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { + + if ($this->lock) { + $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-submitted'); + $errorNode->appendChild($error); + if (!is_object($this->lock)) var_dump($this->lock); + $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); + } + + } + +} + diff --git a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php b/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php new file mode 100755 index 00000000000..31875751505 --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php @@ -0,0 +1,45 @@ +getAllowedMethods($server->getRequestUri()); + + return array( + 'Allow' => strtoupper(implode(', ',$methods)), + ); + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php b/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php new file mode 100755 index 00000000000..87ca624429f --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php @@ -0,0 +1,28 @@ +header = $header; + + } + + /** + * Returns the HTTP statuscode for this exception + * + * @return int + */ + public function getHTTPCode() { + + return 412; + + } + + /** + * This method allows the exception to include additional information into the WebDAV error response + * + * @param Sabre_DAV_Server $server + * @param DOMElement $errorNode + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { + + if ($this->header) { + $prop = $errorNode->ownerDocument->createElement('s:header'); + $prop->nodeValue = $this->header; + $errorNode->appendChild($prop); + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php b/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php new file mode 100755 index 00000000000..e86800f3038 --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php @@ -0,0 +1,30 @@ +ownerDocument->createElementNS('DAV:','d:supported-report'); + $errorNode->appendChild($error); + + } + +} diff --git a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php b/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php new file mode 100755 index 00000000000..29ee3654a7e --- /dev/null +++ b/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php @@ -0,0 +1,29 @@ +path . '/' . $name; + file_put_contents($newPath,$data); + + } + + /** + * Creates a new subdirectory + * + * @param string $name + * @return void + */ + public function createDirectory($name) { + + $newPath = $this->path . '/' . $name; + mkdir($newPath); + + } + + /** + * Returns a specific child node, referenced by its name + * + * @param string $name + * @throws Sabre_DAV_Exception_NotFound + * @return Sabre_DAV_INode + */ + public function getChild($name) { + + $path = $this->path . '/' . $name; + + if (!file_exists($path)) throw new Sabre_DAV_Exception_NotFound('File with name ' . $path . ' could not be located'); + + if (is_dir($path)) { + + return new Sabre_DAV_FS_Directory($path); + + } else { + + return new Sabre_DAV_FS_File($path); + + } + + } + + /** + * Returns an array with all the child nodes + * + * @return Sabre_DAV_INode[] + */ + public function getChildren() { + + $nodes = array(); + foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); + return $nodes; + + } + + /** + * Checks if a child exists. + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + $path = $this->path . '/' . $name; + return file_exists($path); + + } + + /** + * Deletes all files in this directory, and then itself + * + * @return void + */ + public function delete() { + + foreach($this->getChildren() as $child) $child->delete(); + rmdir($this->path); + + } + + /** + * Returns available diskspace information + * + * @return array + */ + public function getQuotaInfo() { + + return array( + disk_total_space($this->path)-disk_free_space($this->path), + disk_free_space($this->path) + ); + + } + +} + diff --git a/3rdparty/Sabre/DAV/FS/File.php b/3rdparty/Sabre/DAV/FS/File.php new file mode 100755 index 00000000000..6a8039fe303 --- /dev/null +++ b/3rdparty/Sabre/DAV/FS/File.php @@ -0,0 +1,89 @@ +path,$data); + + } + + /** + * Returns the data + * + * @return string + */ + public function get() { + + return fopen($this->path,'r'); + + } + + /** + * Delete the current file + * + * @return void + */ + public function delete() { + + unlink($this->path); + + } + + /** + * Returns the size of the node, in bytes + * + * @return int + */ + public function getSize() { + + return filesize($this->path); + + } + + /** + * Returns the ETag for a file + * + * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. + * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. + * + * Return null if the ETag can not effectively be determined + * + * @return mixed + */ + public function getETag() { + + return null; + + } + + /** + * Returns the mime-type for a file + * + * If null is returned, we'll assume application/octet-stream + * + * @return mixed + */ + public function getContentType() { + + return null; + + } + +} + diff --git a/3rdparty/Sabre/DAV/FS/Node.php b/3rdparty/Sabre/DAV/FS/Node.php new file mode 100755 index 00000000000..1283e9d0fdc --- /dev/null +++ b/3rdparty/Sabre/DAV/FS/Node.php @@ -0,0 +1,80 @@ +path = $path; + + } + + + + /** + * Returns the name of the node + * + * @return string + */ + public function getName() { + + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); + return $name; + + } + + /** + * Renames the node + * + * @param string $name The new name + * @return void + */ + public function setName($name) { + + list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); + list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); + + $newPath = $parentPath . '/' . $newName; + rename($this->path,$newPath); + + $this->path = $newPath; + + } + + + + /** + * Returns the last modification time, as a unix timestamp + * + * @return int + */ + public function getLastModified() { + + return filemtime($this->path); + + } + +} + diff --git a/3rdparty/Sabre/DAV/FSExt/Directory.php b/3rdparty/Sabre/DAV/FSExt/Directory.php new file mode 100755 index 00000000000..540057183b3 --- /dev/null +++ b/3rdparty/Sabre/DAV/FSExt/Directory.php @@ -0,0 +1,154 @@ +path . '/' . $name; + file_put_contents($newPath,$data); + + return '"' . md5_file($newPath) . '"'; + + } + + /** + * Creates a new subdirectory + * + * @param string $name + * @return void + */ + public function createDirectory($name) { + + // We're not allowing dots + if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + $newPath = $this->path . '/' . $name; + mkdir($newPath); + + } + + /** + * Returns a specific child node, referenced by its name + * + * @param string $name + * @throws Sabre_DAV_Exception_NotFound + * @return Sabre_DAV_INode + */ + public function getChild($name) { + + $path = $this->path . '/' . $name; + + if (!file_exists($path)) throw new Sabre_DAV_Exception_NotFound('File could not be located'); + if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + + if (is_dir($path)) { + + return new Sabre_DAV_FSExt_Directory($path); + + } else { + + return new Sabre_DAV_FSExt_File($path); + + } + + } + + /** + * Checks if a child exists. + * + * @param string $name + * @return bool + */ + public function childExists($name) { + + if ($name=='.' || $name=='..') + throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + + $path = $this->path . '/' . $name; + return file_exists($path); + + } + + /** + * Returns an array with all the child nodes + * + * @return Sabre_DAV_INode[] + */ + public function getChildren() { + + $nodes = array(); + foreach(scandir($this->path) as $node) if($node!='.' && $node!='..' && $node!='.sabredav') $nodes[] = $this->getChild($node); + return $nodes; + + } + + /** + * Deletes all files in this directory, and then itself + * + * @return bool + */ + public function delete() { + + // Deleting all children + foreach($this->getChildren() as $child) $child->delete(); + + // Removing resource info, if its still around + if (file_exists($this->path . '/.sabredav')) unlink($this->path . '/.sabredav'); + + // Removing the directory itself + rmdir($this->path); + + return parent::delete(); + + } + + /** + * Returns available diskspace information + * + * @return array + */ + public function getQuotaInfo() { + + return array( + disk_total_space($this->path)-disk_free_space($this->path), + disk_free_space($this->path) + ); + + } + +} + diff --git a/3rdparty/Sabre/DAV/FSExt/File.php b/3rdparty/Sabre/DAV/FSExt/File.php new file mode 100755 index 00000000000..b93ce5aee21 --- /dev/null +++ b/3rdparty/Sabre/DAV/FSExt/File.php @@ -0,0 +1,93 @@ +path,$data); + return '"' . md5_file($this->path) . '"'; + + } + + /** + * Returns the data + * + * @return string + */ + public function get() { + + return fopen($this->path,'r'); + + } + + /** + * Delete the current file + * + * @return bool + */ + public function delete() { + + unlink($this->path); + return parent::delete(); + + } + + /** + * Returns the ETag for a file + * + * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. + * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. + * + * Return null if the ETag can not effectively be determined + * + * @return string|null + */ + public function getETag() { + + return '"' . md5_file($this->path). '"'; + + } + + /** + * Returns the mime-type for a file + * + * If null is returned, we'll assume application/octet-stream + * + * @return string|null + */ + public function getContentType() { + + return null; + + } + + /** + * Returns the size of the file, in bytes + * + * @return int + */ + public function getSize() { + + return filesize($this->path); + + } + +} + diff --git a/3rdparty/Sabre/DAV/FSExt/Node.php b/3rdparty/Sabre/DAV/FSExt/Node.php new file mode 100755 index 00000000000..68ca06beb7e --- /dev/null +++ b/3rdparty/Sabre/DAV/FSExt/Node.php @@ -0,0 +1,212 @@ +getResourceData(); + + foreach($properties as $propertyName=>$propertyValue) { + + // If it was null, we need to delete the property + if (is_null($propertyValue)) { + if (isset($resourceData['properties'][$propertyName])) { + unset($resourceData['properties'][$propertyName]); + } + } else { + $resourceData['properties'][$propertyName] = $propertyValue; + } + + } + + $this->putResourceData($resourceData); + return true; + } + + /** + * Returns a list of properties for this nodes.; + * + * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author + * If the array is empty, all properties should be returned + * + * @param array $properties + * @return array + */ + function getProperties($properties) { + + $resourceData = $this->getResourceData(); + + // if the array was empty, we need to return everything + if (!$properties) return $resourceData['properties']; + + $props = array(); + foreach($properties as $property) { + if (isset($resourceData['properties'][$property])) $props[$property] = $resourceData['properties'][$property]; + } + + return $props; + + } + + /** + * Returns the path to the resource file + * + * @return string + */ + protected function getResourceInfoPath() { + + list($parentDir) = Sabre_DAV_URLUtil::splitPath($this->path); + return $parentDir . '/.sabredav'; + + } + + /** + * Returns all the stored resource information + * + * @return array + */ + protected function getResourceData() { + + $path = $this->getResourceInfoPath(); + if (!file_exists($path)) return array('properties' => array()); + + // opening up the file, and creating a shared lock + $handle = fopen($path,'r'); + flock($handle,LOCK_SH); + $data = ''; + + // Reading data until the eof + while(!feof($handle)) { + $data.=fread($handle,8192); + } + + // We're all good + fclose($handle); + + // Unserializing and checking if the resource file contains data for this file + $data = unserialize($data); + if (!isset($data[$this->getName()])) { + return array('properties' => array()); + } + + $data = $data[$this->getName()]; + if (!isset($data['properties'])) $data['properties'] = array(); + return $data; + + } + + /** + * Updates the resource information + * + * @param array $newData + * @return void + */ + protected function putResourceData(array $newData) { + + $path = $this->getResourceInfoPath(); + + // opening up the file, and creating a shared lock + $handle = fopen($path,'a+'); + flock($handle,LOCK_EX); + $data = ''; + + rewind($handle); + + // Reading data until the eof + while(!feof($handle)) { + $data.=fread($handle,8192); + } + + // Unserializing and checking if the resource file contains data for this file + $data = unserialize($data); + $data[$this->getName()] = $newData; + ftruncate($handle,0); + rewind($handle); + + fwrite($handle,serialize($data)); + fclose($handle); + + } + + /** + * Renames the node + * + * @param string $name The new name + * @return void + */ + public function setName($name) { + + list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); + list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); + $newPath = $parentPath . '/' . $newName; + + // We're deleting the existing resourcedata, and recreating it + // for the new path. + $resourceData = $this->getResourceData(); + $this->deleteResourceData(); + + rename($this->path,$newPath); + $this->path = $newPath; + $this->putResourceData($resourceData); + + + } + + /** + * @return bool + */ + public function deleteResourceData() { + + // When we're deleting this node, we also need to delete any resource information + $path = $this->getResourceInfoPath(); + if (!file_exists($path)) return true; + + // opening up the file, and creating a shared lock + $handle = fopen($path,'a+'); + flock($handle,LOCK_EX); + $data = ''; + + rewind($handle); + + // Reading data until the eof + while(!feof($handle)) { + $data.=fread($handle,8192); + } + + // Unserializing and checking if the resource file contains data for this file + $data = unserialize($data); + if (isset($data[$this->getName()])) unset($data[$this->getName()]); + ftruncate($handle,0); + rewind($handle); + fwrite($handle,serialize($data)); + fclose($handle); + + return true; + } + + public function delete() { + + return $this->deleteResourceData(); + + } + +} + diff --git a/3rdparty/Sabre/DAV/File.php b/3rdparty/Sabre/DAV/File.php new file mode 100755 index 00000000000..3126bd8d364 --- /dev/null +++ b/3rdparty/Sabre/DAV/File.php @@ -0,0 +1,85 @@ + array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param array $mutations + * @return bool|array + */ + function updateProperties($mutations); + + /** + * Returns a list of properties for this nodes. + * + * The properties list is a list of propertynames the client requested, + * encoded in clark-notation {xmlnamespace}tagname + * + * If the array is empty, it means 'all properties' were requested. + * + * @param array $properties + * @return void + */ + function getProperties($properties); + +} + diff --git a/3rdparty/Sabre/DAV/IQuota.php b/3rdparty/Sabre/DAV/IQuota.php new file mode 100755 index 00000000000..3fe4c4eced4 --- /dev/null +++ b/3rdparty/Sabre/DAV/IQuota.php @@ -0,0 +1,27 @@ +dataDir = $dataDir; + + } + + protected function getFileNameForUri($uri) { + + return $this->dataDir . '/sabredav_' . md5($uri) . '.locks'; + + } + + + /** + * Returns a list of Sabre_DAV_Locks_LockInfo objects + * + * This method should return all the locks for a particular uri, including + * locks that might be set on a parent uri. + * + * If returnChildLocks is set to true, this method should also look for + * any locks in the subtree of the uri for locks. + * + * @param string $uri + * @param bool $returnChildLocks + * @return array + */ + public function getLocks($uri, $returnChildLocks) { + + $lockList = array(); + $currentPath = ''; + + foreach(explode('/',$uri) as $uriPart) { + + // weird algorithm that can probably be improved, but we're traversing the path top down + if ($currentPath) $currentPath.='/'; + $currentPath.=$uriPart; + + $uriLocks = $this->getData($currentPath); + + foreach($uriLocks as $uriLock) { + + // Unless we're on the leaf of the uri-tree we should ignore locks with depth 0 + if($uri==$currentPath || $uriLock->depth!=0) { + $uriLock->uri = $currentPath; + $lockList[] = $uriLock; + } + + } + + } + + // Checking if we can remove any of these locks + foreach($lockList as $k=>$lock) { + if (time() > $lock->timeout + $lock->created) unset($lockList[$k]); + } + return $lockList; + + } + + /** + * Locks a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + // We're making the lock timeout 30 minutes + $lockInfo->timeout = 1800; + $lockInfo->created = time(); + + $locks = $this->getLocks($uri,false); + foreach($locks as $k=>$lock) { + if ($lock->token == $lockInfo->token) unset($locks[$k]); + } + $locks[] = $lockInfo; + $this->putData($uri,$locks); + return true; + + } + + /** + * Removes a lock from a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + $locks = $this->getLocks($uri,false); + foreach($locks as $k=>$lock) { + + if ($lock->token == $lockInfo->token) { + + unset($locks[$k]); + $this->putData($uri,$locks); + return true; + + } + } + return false; + + } + + /** + * Returns the stored data for a uri + * + * @param string $uri + * @return array + */ + protected function getData($uri) { + + $path = $this->getFilenameForUri($uri); + if (!file_exists($path)) return array(); + + // opening up the file, and creating a shared lock + $handle = fopen($path,'r'); + flock($handle,LOCK_SH); + $data = ''; + + // Reading data until the eof + while(!feof($handle)) { + $data.=fread($handle,8192); + } + + // We're all good + fclose($handle); + + // Unserializing and checking if the resource file contains data for this file + $data = unserialize($data); + if (!$data) return array(); + return $data; + + } + + /** + * Updates the lock information + * + * @param string $uri + * @param array $newData + * @return void + */ + protected function putData($uri,array $newData) { + + $path = $this->getFileNameForUri($uri); + + // opening up the file, and creating a shared lock + $handle = fopen($path,'a+'); + flock($handle,LOCK_EX); + ftruncate($handle,0); + rewind($handle); + + fwrite($handle,serialize($newData)); + fclose($handle); + + } + +} + diff --git a/3rdparty/Sabre/DAV/Locks/Backend/File.php b/3rdparty/Sabre/DAV/Locks/Backend/File.php new file mode 100755 index 00000000000..c33f963514b --- /dev/null +++ b/3rdparty/Sabre/DAV/Locks/Backend/File.php @@ -0,0 +1,181 @@ +locksFile = $locksFile; + + } + + /** + * Returns a list of Sabre_DAV_Locks_LockInfo objects + * + * This method should return all the locks for a particular uri, including + * locks that might be set on a parent uri. + * + * If returnChildLocks is set to true, this method should also look for + * any locks in the subtree of the uri for locks. + * + * @param string $uri + * @param bool $returnChildLocks + * @return array + */ + public function getLocks($uri, $returnChildLocks) { + + $newLocks = array(); + + $locks = $this->getData(); + + foreach($locks as $lock) { + + if ($lock->uri === $uri || + //deep locks on parents + ($lock->depth!=0 && strpos($uri, $lock->uri . '/')===0) || + + // locks on children + ($returnChildLocks && (strpos($lock->uri, $uri . '/')===0)) ) { + + $newLocks[] = $lock; + + } + + } + + // Checking if we can remove any of these locks + foreach($newLocks as $k=>$lock) { + if (time() > $lock->timeout + $lock->created) unset($newLocks[$k]); + } + return $newLocks; + + } + + /** + * Locks a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) { + + // We're making the lock timeout 30 minutes + $lockInfo->timeout = 1800; + $lockInfo->created = time(); + $lockInfo->uri = $uri; + + $locks = $this->getData(); + + foreach($locks as $k=>$lock) { + if ( + ($lock->token == $lockInfo->token) || + (time() > $lock->timeout + $lock->created) + ) { + unset($locks[$k]); + } + } + $locks[] = $lockInfo; + $this->putData($locks); + return true; + + } + + /** + * Removes a lock from a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) { + + $locks = $this->getData(); + foreach($locks as $k=>$lock) { + + if ($lock->token == $lockInfo->token) { + + unset($locks[$k]); + $this->putData($locks); + return true; + + } + } + return false; + + } + + /** + * Loads the lockdata from the filesystem. + * + * @return array + */ + protected function getData() { + + if (!file_exists($this->locksFile)) return array(); + + // opening up the file, and creating a shared lock + $handle = fopen($this->locksFile,'r'); + flock($handle,LOCK_SH); + + // Reading data until the eof + $data = stream_get_contents($handle); + + // We're all good + fclose($handle); + + // Unserializing and checking if the resource file contains data for this file + $data = unserialize($data); + if (!$data) return array(); + return $data; + + } + + /** + * Saves the lockdata + * + * @param array $newData + * @return void + */ + protected function putData(array $newData) { + + // opening up the file, and creating an exclusive lock + $handle = fopen($this->locksFile,'a+'); + flock($handle,LOCK_EX); + + // We can only truncate and rewind once the lock is acquired. + ftruncate($handle,0); + rewind($handle); + + fwrite($handle,serialize($newData)); + fclose($handle); + + } + +} + diff --git a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php b/3rdparty/Sabre/DAV/Locks/Backend/PDO.php new file mode 100755 index 00000000000..acce80638ec --- /dev/null +++ b/3rdparty/Sabre/DAV/Locks/Backend/PDO.php @@ -0,0 +1,165 @@ +pdo = $pdo; + $this->tableName = $tableName; + + } + + /** + * Returns a list of Sabre_DAV_Locks_LockInfo objects + * + * This method should return all the locks for a particular uri, including + * locks that might be set on a parent uri. + * + * If returnChildLocks is set to true, this method should also look for + * any locks in the subtree of the uri for locks. + * + * @param string $uri + * @param bool $returnChildLocks + * @return array + */ + public function getLocks($uri, $returnChildLocks) { + + // NOTE: the following 10 lines or so could be easily replaced by + // pure sql. MySQL's non-standard string concatenation prevents us + // from doing this though. + $query = 'SELECT owner, token, timeout, created, scope, depth, uri FROM '.$this->tableName.' WHERE ((created + timeout) > CAST(? AS UNSIGNED INTEGER)) AND ((uri = ?)'; + $params = array(time(),$uri); + + // We need to check locks for every part in the uri. + $uriParts = explode('/',$uri); + + // We already covered the last part of the uri + array_pop($uriParts); + + $currentPath=''; + + foreach($uriParts as $part) { + + if ($currentPath) $currentPath.='/'; + $currentPath.=$part; + + $query.=' OR (depth!=0 AND uri = ?)'; + $params[] = $currentPath; + + } + + if ($returnChildLocks) { + + $query.=' OR (uri LIKE ?)'; + $params[] = $uri . '/%'; + + } + $query.=')'; + + $stmt = $this->pdo->prepare($query); + $stmt->execute($params); + $result = $stmt->fetchAll(); + + $lockList = array(); + foreach($result as $row) { + + $lockInfo = new Sabre_DAV_Locks_LockInfo(); + $lockInfo->owner = $row['owner']; + $lockInfo->token = $row['token']; + $lockInfo->timeout = $row['timeout']; + $lockInfo->created = $row['created']; + $lockInfo->scope = $row['scope']; + $lockInfo->depth = $row['depth']; + $lockInfo->uri = $row['uri']; + $lockList[] = $lockInfo; + + } + + return $lockList; + + } + + /** + * Locks a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + // We're making the lock timeout 30 minutes + $lockInfo->timeout = 30*60; + $lockInfo->created = time(); + $lockInfo->uri = $uri; + + $locks = $this->getLocks($uri,false); + $exists = false; + foreach($locks as $lock) { + if ($lock->token == $lockInfo->token) $exists = true; + } + + if ($exists) { + $stmt = $this->pdo->prepare('UPDATE '.$this->tableName.' SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE token = ?'); + $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); + } else { + $stmt = $this->pdo->prepare('INSERT INTO '.$this->tableName.' (owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?)'); + $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); + } + + return true; + + } + + + + /** + * Removes a lock from a uri + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + $stmt = $this->pdo->prepare('DELETE FROM '.$this->tableName.' WHERE uri = ? AND token = ?'); + $stmt->execute(array($uri,$lockInfo->token)); + + return $stmt->rowCount()===1; + + } + +} + diff --git a/3rdparty/Sabre/DAV/Locks/LockInfo.php b/3rdparty/Sabre/DAV/Locks/LockInfo.php new file mode 100755 index 00000000000..9df014a4281 --- /dev/null +++ b/3rdparty/Sabre/DAV/Locks/LockInfo.php @@ -0,0 +1,81 @@ +addPlugin($lockPlugin); + * + * @package Sabre + * @subpackage DAV + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License + */ +class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { + + /** + * locksBackend + * + * @var Sabre_DAV_Locks_Backend_Abstract + */ + private $locksBackend; + + /** + * server + * + * @var Sabre_DAV_Server + */ + private $server; + + /** + * __construct + * + * @param Sabre_DAV_Locks_Backend_Abstract $locksBackend + */ + public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) { + + $this->locksBackend = $locksBackend; + + } + + /** + * Initializes the plugin + * + * This method is automatically called by the Server class after addPlugin. + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); + $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),50); + $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties')); + + } + + /** + * Returns a plugin name. + * + * Using this name other plugins will be able to access other plugins + * using Sabre_DAV_Server::getPlugin + * + * @return string + */ + public function getPluginName() { + + return 'locks'; + + } + + /** + * This method is called by the Server if the user used an HTTP method + * the server didn't recognize. + * + * This plugin intercepts the LOCK and UNLOCK methods. + * + * @param string $method + * @param string $uri + * @return bool + */ + public function unknownMethod($method, $uri) { + + switch($method) { + + case 'LOCK' : $this->httpLock($uri); return false; + case 'UNLOCK' : $this->httpUnlock($uri); return false; + + } + + } + + /** + * This method is called after most properties have been found + * it allows us to add in any Lock-related properties + * + * @param string $path + * @param array $newProperties + * @return bool + */ + public function afterGetProperties($path, &$newProperties) { + + foreach($newProperties[404] as $propName=>$discard) { + + switch($propName) { + + case '{DAV:}supportedlock' : + $val = false; + if ($this->locksBackend) $val = true; + $newProperties[200][$propName] = new Sabre_DAV_Property_SupportedLock($val); + unset($newProperties[404][$propName]); + break; + + case '{DAV:}lockdiscovery' : + $newProperties[200][$propName] = new Sabre_DAV_Property_LockDiscovery($this->getLocks($path)); + unset($newProperties[404][$propName]); + break; + + } + + + } + return true; + + } + + + /** + * This method is called before the logic for any HTTP method is + * handled. + * + * This plugin uses that feature to intercept access to locked resources. + * + * @param string $method + * @param string $uri + * @return bool + */ + public function beforeMethod($method, $uri) { + + switch($method) { + + case 'DELETE' : + $lastLock = null; + if (!$this->validateLock($uri,$lastLock, true)) + throw new Sabre_DAV_Exception_Locked($lastLock); + break; + case 'MKCOL' : + case 'PROPPATCH' : + case 'PUT' : + $lastLock = null; + if (!$this->validateLock($uri,$lastLock)) + throw new Sabre_DAV_Exception_Locked($lastLock); + break; + case 'MOVE' : + $lastLock = null; + if (!$this->validateLock(array( + $uri, + $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), + ),$lastLock, true)) + throw new Sabre_DAV_Exception_Locked($lastLock); + break; + case 'COPY' : + $lastLock = null; + if (!$this->validateLock( + $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), + $lastLock, true)) + throw new Sabre_DAV_Exception_Locked($lastLock); + break; + } + + return true; + + } + + /** + * Use this method to tell the server this plugin defines additional + * HTTP methods. + * + * This method is passed a uri. It should only return HTTP methods that are + * available for the specified uri. + * + * @param string $uri + * @return array + */ + public function getHTTPMethods($uri) { + + if ($this->locksBackend) + return array('LOCK','UNLOCK'); + + return array(); + + } + + /** + * Returns a list of features for the HTTP OPTIONS Dav: header. + * + * In this case this is only the number 2. The 2 in the Dav: header + * indicates the server supports locks. + * + * @return array + */ + public function getFeatures() { + + return array(2); + + } + + /** + * Returns all lock information on a particular uri + * + * This function should return an array with Sabre_DAV_Locks_LockInfo objects. If there are no locks on a file, return an empty array. + * + * Additionally there is also the possibility of locks on parent nodes, so we'll need to traverse every part of the tree + * If the $returnChildLocks argument is set to true, we'll also traverse all the children of the object + * for any possible locks and return those as well. + * + * @param string $uri + * @param bool $returnChildLocks + * @return array + */ + public function getLocks($uri, $returnChildLocks = false) { + + $lockList = array(); + + if ($this->locksBackend) + $lockList = array_merge($lockList,$this->locksBackend->getLocks($uri, $returnChildLocks)); + + return $lockList; + + } + + /** + * Locks an uri + * + * The WebDAV lock request can be operated to either create a new lock on a file, or to refresh an existing lock + * If a new lock is created, a full XML body should be supplied, containing information about the lock such as the type + * of lock (shared or exclusive) and the owner of the lock + * + * If a lock is to be refreshed, no body should be supplied and there should be a valid If header containing the lock + * + * Additionally, a lock can be requested for a non-existent file. In these case we're obligated to create an empty file as per RFC4918:S7.3 + * + * @param string $uri + * @return void + */ + protected function httpLock($uri) { + + $lastLock = null; + if (!$this->validateLock($uri,$lastLock)) { + + // If the existing lock was an exclusive lock, we need to fail + if (!$lastLock || $lastLock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE) { + //var_dump($lastLock); + throw new Sabre_DAV_Exception_ConflictingLock($lastLock); + } + + } + + if ($body = $this->server->httpRequest->getBody(true)) { + // This is a new lock request + $lockInfo = $this->parseLockRequest($body); + $lockInfo->depth = $this->server->getHTTPDepth(); + $lockInfo->uri = $uri; + if($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) throw new Sabre_DAV_Exception_ConflictingLock($lastLock); + + } elseif ($lastLock) { + + // This must have been a lock refresh + $lockInfo = $lastLock; + + // The resource could have been locked through another uri. + if ($uri!=$lockInfo->uri) $uri = $lockInfo->uri; + + } else { + + // There was neither a lock refresh nor a new lock request + throw new Sabre_DAV_Exception_BadRequest('An xml body is required for lock requests'); + + } + + if ($timeout = $this->getTimeoutHeader()) $lockInfo->timeout = $timeout; + + $newFile = false; + + // If we got this far.. we should go check if this node actually exists. If this is not the case, we need to create it first + try { + $this->server->tree->getNodeForPath($uri); + + // We need to call the beforeWriteContent event for RFC3744 + $this->server->broadcastEvent('beforeWriteContent',array($uri)); + + } catch (Sabre_DAV_Exception_NotFound $e) { + + // It didn't, lets create it + $this->server->createFile($uri,fopen('php://memory','r')); + $newFile = true; + + } + + $this->lockNode($uri,$lockInfo); + + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Lock-Token','token . '>'); + $this->server->httpResponse->sendStatus($newFile?201:200); + $this->server->httpResponse->sendBody($this->generateLockResponse($lockInfo)); + + } + + /** + * Unlocks a uri + * + * This WebDAV method allows you to remove a lock from a node. The client should provide a valid locktoken through the Lock-token http header + * The server should return 204 (No content) on success + * + * @param string $uri + * @return void + */ + protected function httpUnlock($uri) { + + $lockToken = $this->server->httpRequest->getHeader('Lock-Token'); + + // If the locktoken header is not supplied, we need to throw a bad request exception + if (!$lockToken) throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); + + $locks = $this->getLocks($uri); + + // Windows sometimes forgets to include < and > in the Lock-Token + // header + if ($lockToken[0]!=='<') $lockToken = '<' . $lockToken . '>'; + + foreach($locks as $lock) { + + if ('token . '>' == $lockToken) { + + $this->unlockNode($uri,$lock); + $this->server->httpResponse->setHeader('Content-Length','0'); + $this->server->httpResponse->sendStatus(204); + return; + + } + + } + + // If we got here, it means the locktoken was invalid + throw new Sabre_DAV_Exception_LockTokenMatchesRequestUri(); + + } + + /** + * Locks a uri + * + * All the locking information is supplied in the lockInfo object. The object has a suggested timeout, but this can be safely ignored + * It is important that if the existing timeout is ignored, the property is overwritten, as this needs to be sent back to the client + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function lockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + if (!$this->server->broadcastEvent('beforeLock',array($uri,$lockInfo))) return; + + if ($this->locksBackend) return $this->locksBackend->lock($uri,$lockInfo); + throw new Sabre_DAV_Exception_MethodNotAllowed('Locking support is not enabled for this resource. No Locking backend was found so if you didn\'t expect this error, please check your configuration.'); + + } + + /** + * Unlocks a uri + * + * This method removes a lock from a uri. It is assumed all the supplied information is correct and verified + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return bool + */ + public function unlockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + + if (!$this->server->broadcastEvent('beforeUnlock',array($uri,$lockInfo))) return; + if ($this->locksBackend) return $this->locksBackend->unlock($uri,$lockInfo); + + } + + + /** + * Returns the contents of the HTTP Timeout header. + * + * The method formats the header into an integer. + * + * @return int + */ + public function getTimeoutHeader() { + + $header = $this->server->httpRequest->getHeader('Timeout'); + + if ($header) { + + if (stripos($header,'second-')===0) $header = (int)(substr($header,7)); + else if (strtolower($header)=='infinite') $header=Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; + else throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); + + } else { + + $header = 0; + + } + + return $header; + + } + + /** + * Generates the response for successful LOCK requests + * + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * @return string + */ + protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) { + + $dom = new DOMDocument('1.0','utf-8'); + $dom->formatOutput = true; + + $prop = $dom->createElementNS('DAV:','d:prop'); + $dom->appendChild($prop); + + $lockDiscovery = $dom->createElementNS('DAV:','d:lockdiscovery'); + $prop->appendChild($lockDiscovery); + + $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo),true); + $lockObj->serialize($this->server,$lockDiscovery); + + return $dom->saveXML(); + + } + + /** + * validateLock should be called when a write operation is about to happen + * It will check if the requested url is locked, and see if the correct lock tokens are passed + * + * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri + * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) + * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees. + * @return bool + */ + protected function validateLock($urls = null,&$lastLock = null, $checkChildLocks = false) { + + if (is_null($urls)) { + $urls = array($this->server->getRequestUri()); + } elseif (is_string($urls)) { + $urls = array($urls); + } elseif (!is_array($urls)) { + throw new Sabre_DAV_Exception('The urls parameter should either be null, a string or an array'); + } + + $conditions = $this->getIfConditions(); + + // We're going to loop through the urls and make sure all lock conditions are satisfied + foreach($urls as $url) { + + $locks = $this->getLocks($url, $checkChildLocks); + + // If there were no conditions, but there were locks, we fail + if (!$conditions && $locks) { + reset($locks); + $lastLock = current($locks); + return false; + } + + // If there were no locks or conditions, we go to the next url + if (!$locks && !$conditions) continue; + + foreach($conditions as $condition) { + + if (!$condition['uri']) { + $conditionUri = $this->server->getRequestUri(); + } else { + $conditionUri = $this->server->calculateUri($condition['uri']); + } + + // If the condition has a url, and it isn't part of the affected url at all, check the next condition + if ($conditionUri && strpos($url,$conditionUri)!==0) continue; + + // The tokens array contians arrays with 2 elements. 0=true/false for normal/not condition, 1=locktoken + // At least 1 condition has to be satisfied + foreach($condition['tokens'] as $conditionToken) { + + $etagValid = true; + $lockValid = true; + + // key 2 can contain an etag + if ($conditionToken[2]) { + + $uri = $conditionUri?$conditionUri:$this->server->getRequestUri(); + $node = $this->server->tree->getNodeForPath($uri); + $etagValid = $node->getETag()==$conditionToken[2]; + + } + + // key 1 can contain a lock token + if ($conditionToken[1]) { + + $lockValid = false; + // Match all the locks + foreach($locks as $lockIndex=>$lock) { + + $lockToken = 'opaquelocktoken:' . $lock->token; + + // Checking NOT + if (!$conditionToken[0] && $lockToken != $conditionToken[1]) { + + // Condition valid, onto the next + $lockValid = true; + break; + } + if ($conditionToken[0] && $lockToken == $conditionToken[1]) { + + $lastLock = $lock; + // Condition valid and lock matched + unset($locks[$lockIndex]); + $lockValid = true; + break; + + } + + } + + } + + // If, after checking both etags and locks they are stil valid, + // we can continue with the next condition. + if ($etagValid && $lockValid) continue 2; + } + // No conditions matched, so we fail + throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match','If'); + } + + // Conditions were met, we'll also need to check if all the locks are gone + if (count($locks)) { + + reset($locks); + + // There's still locks, we fail + $lastLock = current($locks); + return false; + + } + + + } + + // We got here, this means every condition was satisfied + return true; + + } + + /** + * This method is created to extract information from the WebDAV HTTP 'If:' header + * + * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information + * The function will return an array, containing structs with the following keys + * + * * uri - the uri the condition applies to. If this is returned as an + * empty string, this implies it's referring to the request url. + * * tokens - The lock token. another 2 dimensional array containing 2 elements (0 = true/false.. If this is a negative condition its set to false, 1 = the actual token) + * * etag - an etag, if supplied + * + * @return array + */ + public function getIfConditions() { + + $header = $this->server->httpRequest->getHeader('If'); + if (!$header) return array(); + + $matches = array(); + + $regex = '/(?:\<(?P.*?)\>\s)?\((?PNot\s)?(?:\<(?P[^\>]*)\>)?(?:\s?)(?:\[(?P[^\]]*)\])?\)/im'; + preg_match_all($regex,$header,$matches,PREG_SET_ORDER); + + $conditions = array(); + + foreach($matches as $match) { + + $condition = array( + 'uri' => $match['uri'], + 'tokens' => array( + array($match['not']?0:1,$match['token'],isset($match['etag'])?$match['etag']:'') + ), + ); + + if (!$condition['uri'] && count($conditions)) $conditions[count($conditions)-1]['tokens'][] = array( + $match['not']?0:1, + $match['token'], + isset($match['etag'])?$match['etag']:'' + ); + else { + $conditions[] = $condition; + } + + } + + return $conditions; + + } + + /** + * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object + * + * @param string $body + * @return Sabre_DAV_Locks_LockInfo + */ + protected function parseLockRequest($body) { + + $xml = simplexml_load_string($body,null,LIBXML_NOWARNING); + $xml->registerXPathNamespace('d','DAV:'); + $lockInfo = new Sabre_DAV_Locks_LockInfo(); + + $children = $xml->children("DAV:"); + $lockInfo->owner = (string)$children->owner; + + $lockInfo->token = Sabre_DAV_UUIDUtil::getUUID(); + $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive'))>0?Sabre_DAV_Locks_LockInfo::EXCLUSIVE:Sabre_DAV_Locks_LockInfo::SHARED; + + return $lockInfo; + + } + + +} diff --git a/3rdparty/Sabre/DAV/Mount/Plugin.php b/3rdparty/Sabre/DAV/Mount/Plugin.php new file mode 100755 index 00000000000..b37a90ae993 --- /dev/null +++ b/3rdparty/Sabre/DAV/Mount/Plugin.php @@ -0,0 +1,80 @@ +server = $server; + $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); + + } + + /** + * 'beforeMethod' event handles. This event handles intercepts GET requests ending + * with ?mount + * + * @param string $method + * @param string $uri + * @return bool + */ + public function beforeMethod($method, $uri) { + + if ($method!='GET') return; + if ($this->server->httpRequest->getQueryString()!='mount') return; + + $currentUri = $this->server->httpRequest->getAbsoluteUri(); + + // Stripping off everything after the ? + list($currentUri) = explode('?',$currentUri); + + $this->davMount($currentUri); + + // Returning false to break the event chain + return false; + + } + + /** + * Generates the davmount response + * + * @param string $uri absolute uri + * @return void + */ + public function davMount($uri) { + + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->setHeader('Content-Type','application/davmount+xml'); + ob_start(); + echo '', "\n"; + echo "\n"; + echo " ", htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "\n"; + echo ""; + $this->server->httpResponse->sendBody(ob_get_clean()); + + } + + +} diff --git a/3rdparty/Sabre/DAV/Node.php b/3rdparty/Sabre/DAV/Node.php new file mode 100755 index 00000000000..070b7176afd --- /dev/null +++ b/3rdparty/Sabre/DAV/Node.php @@ -0,0 +1,55 @@ +rootNode = $rootNode; + + } + + /** + * Returns the INode object for the requested path + * + * @param string $path + * @return Sabre_DAV_INode + */ + public function getNodeForPath($path) { + + $path = trim($path,'/'); + if (isset($this->cache[$path])) return $this->cache[$path]; + + //if (!$path || $path=='.') return $this->rootNode; + $currentNode = $this->rootNode; + + // We're splitting up the path variable into folder/subfolder components and traverse to the correct node.. + foreach(explode('/',$path) as $pathPart) { + + // If this part of the path is just a dot, it actually means we can skip it + if ($pathPart=='.' || $pathPart=='') continue; + + if (!($currentNode instanceof Sabre_DAV_ICollection)) + throw new Sabre_DAV_Exception_NotFound('Could not find node at path: ' . $path); + + $currentNode = $currentNode->getChild($pathPart); + + } + + $this->cache[$path] = $currentNode; + return $currentNode; + + } + + /** + * This function allows you to check if a node exists. + * + * @param string $path + * @return bool + */ + public function nodeExists($path) { + + try { + + // The root always exists + if ($path==='') return true; + + list($parent, $base) = Sabre_DAV_URLUtil::splitPath($path); + + $parentNode = $this->getNodeForPath($parent); + if (!$parentNode instanceof Sabre_DAV_ICollection) return false; + return $parentNode->childExists($base); + + } catch (Sabre_DAV_Exception_NotFound $e) { + + return false; + + } + + } + + /** + * Returns a list of childnodes for a given path. + * + * @param string $path + * @return array + */ + public function getChildren($path) { + + $node = $this->getNodeForPath($path); + $children = $node->getChildren(); + foreach($children as $child) { + + $this->cache[trim($path,'/') . '/' . $child->getName()] = $child; + + } + return $children; + + } + + /** + * This method is called with every tree update + * + * Examples of tree updates are: + * * node deletions + * * node creations + * * copy + * * move + * * renaming nodes + * + * If Tree classes implement a form of caching, this will allow + * them to make sure caches will be expired. + * + * If a path is passed, it is assumed that the entire subtree is dirty + * + * @param string $path + * @return void + */ + public function markDirty($path) { + + // We don't care enough about sub-paths + // flushing the entire cache + $path = trim($path,'/'); + foreach($this->cache as $nodePath=>$node) { + if ($nodePath == $path || strpos($nodePath,$path.'/')===0) + unset($this->cache[$nodePath]); + + } + + } + +} + diff --git a/3rdparty/Sabre/DAV/Property.php b/3rdparty/Sabre/DAV/Property.php new file mode 100755 index 00000000000..1cfada3236c --- /dev/null +++ b/3rdparty/Sabre/DAV/Property.php @@ -0,0 +1,25 @@ +time = $time; + } elseif (is_int($time) || ctype_digit($time)) { + $this->time = new DateTime('@' . $time); + } else { + $this->time = new DateTime($time); + } + + // Setting timezone to UTC + $this->time->setTimezone(new DateTimeZone('UTC')); + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $prop + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { + + $doc = $prop->ownerDocument; + $prop->setAttribute('xmlns:b','urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); + $prop->setAttribute('b:dt','dateTime.rfc1123'); + $prop->nodeValue = Sabre_HTTP_Util::toHTTPDate($this->time); + + } + + /** + * getTime + * + * @return DateTime + */ + public function getTime() { + + return $this->time; + + } + +} + diff --git a/3rdparty/Sabre/DAV/Property/Href.php b/3rdparty/Sabre/DAV/Property/Href.php new file mode 100755 index 00000000000..dac564f24d7 --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/Href.php @@ -0,0 +1,91 @@ +href = $href; + $this->autoPrefix = $autoPrefix; + + } + + /** + * Returns the uri + * + * @return string + */ + public function getHref() { + + return $this->href; + + } + + /** + * Serializes this property. + * + * It will additionally prepend the href property with the server's base uri. + * + * @param Sabre_DAV_Server $server + * @param DOMElement $dom + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) { + + $prefix = $server->xmlNamespaces['DAV:']; + + $elem = $dom->ownerDocument->createElement($prefix . ':href'); + $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $this->href; + $dom->appendChild($elem); + + } + + /** + * Unserializes this property from a DOM Element + * + * This method returns an instance of this class. + * It will only decode {DAV:}href values. For non-compatible elements null will be returned. + * + * @param DOMElement $dom + * @return Sabre_DAV_Property_Href + */ + static function unserialize(DOMElement $dom) { + + if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)==='{DAV:}href') { + return new self($dom->firstChild->textContent,false); + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Property/HrefList.php b/3rdparty/Sabre/DAV/Property/HrefList.php new file mode 100755 index 00000000000..7a52272e885 --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/HrefList.php @@ -0,0 +1,96 @@ +hrefs = $hrefs; + $this->autoPrefix = $autoPrefix; + + } + + /** + * Returns the uris + * + * @return array + */ + public function getHrefs() { + + return $this->hrefs; + + } + + /** + * Serializes this property. + * + * It will additionally prepend the href property with the server's base uri. + * + * @param Sabre_DAV_Server $server + * @param DOMElement $dom + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { + + $prefix = $server->xmlNamespaces['DAV:']; + + foreach($this->hrefs as $href) { + $elem = $dom->ownerDocument->createElement($prefix . ':href'); + $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $href; + $dom->appendChild($elem); + } + + } + + /** + * Unserializes this property from a DOM Element + * + * This method returns an instance of this class. + * It will only decode {DAV:}href values. + * + * @param DOMElement $dom + * @return Sabre_DAV_Property_Href + */ + static function unserialize(DOMElement $dom) { + + $hrefs = array(); + foreach($dom->childNodes as $child) { + if (Sabre_DAV_XMLUtil::toClarkNotation($child)==='{DAV:}href') { + $hrefs[] = $child->textContent; + } + } + return new self($hrefs, false); + + } + +} diff --git a/3rdparty/Sabre/DAV/Property/IHref.php b/3rdparty/Sabre/DAV/Property/IHref.php new file mode 100755 index 00000000000..5c0409064cb --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/IHref.php @@ -0,0 +1,25 @@ +locks = $locks; + $this->revealLockToken = $revealLockToken; + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $prop + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { + + $doc = $prop->ownerDocument; + + foreach($this->locks as $lock) { + + $activeLock = $doc->createElementNS('DAV:','d:activelock'); + $prop->appendChild($activeLock); + + $lockScope = $doc->createElementNS('DAV:','d:lockscope'); + $activeLock->appendChild($lockScope); + + $lockScope->appendChild($doc->createElementNS('DAV:','d:' . ($lock->scope==Sabre_DAV_Locks_LockInfo::EXCLUSIVE?'exclusive':'shared'))); + + $lockType = $doc->createElementNS('DAV:','d:locktype'); + $activeLock->appendChild($lockType); + + $lockType->appendChild($doc->createElementNS('DAV:','d:write')); + + /* {DAV:}lockroot */ + if (!self::$hideLockRoot) { + $lockRoot = $doc->createElementNS('DAV:','d:lockroot'); + $activeLock->appendChild($lockRoot); + $href = $doc->createElementNS('DAV:','d:href'); + $href->appendChild($doc->createTextNode($server->getBaseUri() . $lock->uri)); + $lockRoot->appendChild($href); + } + + $activeLock->appendChild($doc->createElementNS('DAV:','d:depth',($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY?'infinity':$lock->depth))); + $activeLock->appendChild($doc->createElementNS('DAV:','d:timeout','Second-' . $lock->timeout)); + + if ($this->revealLockToken) { + $lockToken = $doc->createElementNS('DAV:','d:locktoken'); + $activeLock->appendChild($lockToken); + $lockToken->appendChild($doc->createElementNS('DAV:','d:href','opaquelocktoken:' . $lock->token)); + } + + $activeLock->appendChild($doc->createElementNS('DAV:','d:owner',$lock->owner)); + + } + + } + +} + diff --git a/3rdparty/Sabre/DAV/Property/ResourceType.php b/3rdparty/Sabre/DAV/Property/ResourceType.php new file mode 100755 index 00000000000..f6269611e54 --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/ResourceType.php @@ -0,0 +1,125 @@ +resourceType = array(); + elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) + $this->resourceType = array('{DAV:}collection'); + elseif (is_array($resourceType)) + $this->resourceType = $resourceType; + else + $this->resourceType = array($resourceType); + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $prop + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { + + $propName = null; + $rt = $this->resourceType; + + foreach($rt as $resourceType) { + if (preg_match('/^{([^}]*)}(.*)$/',$resourceType,$propName)) { + + if (isset($server->xmlNamespaces[$propName[1]])) { + $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]] . ':' . $propName[2])); + } else { + $prop->appendChild($prop->ownerDocument->createElementNS($propName[1],'custom:' . $propName[2])); + } + + } + } + + } + + /** + * Returns the values in clark-notation + * + * For example array('{DAV:}collection') + * + * @return array + */ + public function getValue() { + + return $this->resourceType; + + } + + /** + * Checks if the principal contains a certain value + * + * @param string $type + * @return bool + */ + public function is($type) { + + return in_array($type, $this->resourceType); + + } + + /** + * Adds a resourcetype value to this property + * + * @param string $type + * @return void + */ + public function add($type) { + + $this->resourceType[] = $type; + $this->resourceType = array_unique($this->resourceType); + + } + + /** + * Unserializes a DOM element into a ResourceType property. + * + * @param DOMElement $dom + * @return Sabre_DAV_Property_ResourceType + */ + static public function unserialize(DOMElement $dom) { + + $value = array(); + foreach($dom->childNodes as $child) { + + $value[] = Sabre_DAV_XMLUtil::toClarkNotation($child); + + } + + return new self($value); + + } + +} diff --git a/3rdparty/Sabre/DAV/Property/Response.php b/3rdparty/Sabre/DAV/Property/Response.php new file mode 100755 index 00000000000..88afbcfb26d --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/Response.php @@ -0,0 +1,155 @@ +href = $href; + $this->responseProperties = $responseProperties; + + } + + /** + * Returns the url + * + * @return string + */ + public function getHref() { + + return $this->href; + + } + + /** + * Returns the property list + * + * @return array + */ + public function getResponseProperties() { + + return $this->responseProperties; + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $dom + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) { + + $document = $dom->ownerDocument; + $properties = $this->responseProperties; + + $xresponse = $document->createElement('d:response'); + $dom->appendChild($xresponse); + + $uri = Sabre_DAV_URLUtil::encodePath($this->href); + + // Adding the baseurl to the beginning of the url + $uri = $server->getBaseUri() . $uri; + + $xresponse->appendChild($document->createElement('d:href',$uri)); + + // The properties variable is an array containing properties, grouped by + // HTTP status + foreach($properties as $httpStatus=>$propertyGroup) { + + // The 'href' is also in this array, and it's special cased. + // We will ignore it + if ($httpStatus=='href') continue; + + // If there are no properties in this group, we can also just carry on + if (!count($propertyGroup)) continue; + + $xpropstat = $document->createElement('d:propstat'); + $xresponse->appendChild($xpropstat); + + $xprop = $document->createElement('d:prop'); + $xpropstat->appendChild($xprop); + + $nsList = $server->xmlNamespaces; + + foreach($propertyGroup as $propertyName=>$propertyValue) { + + $propName = null; + preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); + + // special case for empty namespaces + if ($propName[1]=='') { + + $currentProperty = $document->createElement($propName[2]); + $xprop->appendChild($currentProperty); + $currentProperty->setAttribute('xmlns',''); + + } else { + + if (!isset($nsList[$propName[1]])) { + $nsList[$propName[1]] = 'x' . count($nsList); + } + + // If the namespace was defined in the top-level xml namespaces, it means + // there was already a namespace declaration, and we don't have to worry about it. + if (isset($server->xmlNamespaces[$propName[1]])) { + $currentProperty = $document->createElement($nsList[$propName[1]] . ':' . $propName[2]); + } else { + $currentProperty = $document->createElementNS($propName[1],$nsList[$propName[1]].':' . $propName[2]); + } + $xprop->appendChild($currentProperty); + + } + + if (is_scalar($propertyValue)) { + $text = $document->createTextNode($propertyValue); + $currentProperty->appendChild($text); + } elseif ($propertyValue instanceof Sabre_DAV_Property) { + $propertyValue->serialize($server,$currentProperty); + } elseif (!is_null($propertyValue)) { + throw new Sabre_DAV_Exception('Unknown property value type: ' . gettype($propertyValue) . ' for property: ' . $propertyName); + } + + } + + $xpropstat->appendChild($document->createElement('d:status',$server->httpResponse->getStatusMessage($httpStatus))); + + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Property/ResponseList.php b/3rdparty/Sabre/DAV/Property/ResponseList.php new file mode 100755 index 00000000000..cae923afbf9 --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/ResponseList.php @@ -0,0 +1,57 @@ +responses = $responses; + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $dom + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { + + foreach($this->responses as $response) { + $response->serialize($server, $dom); + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Property/SupportedLock.php b/3rdparty/Sabre/DAV/Property/SupportedLock.php new file mode 100755 index 00000000000..4e3aaf23a1a --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/SupportedLock.php @@ -0,0 +1,76 @@ +supportsLocks = $supportsLocks; + + } + + /** + * serialize + * + * @param Sabre_DAV_Server $server + * @param DOMElement $prop + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { + + $doc = $prop->ownerDocument; + + if (!$this->supportsLocks) return null; + + $lockEntry1 = $doc->createElementNS('DAV:','d:lockentry'); + $lockEntry2 = $doc->createElementNS('DAV:','d:lockentry'); + + $prop->appendChild($lockEntry1); + $prop->appendChild($lockEntry2); + + $lockScope1 = $doc->createElementNS('DAV:','d:lockscope'); + $lockScope2 = $doc->createElementNS('DAV:','d:lockscope'); + $lockType1 = $doc->createElementNS('DAV:','d:locktype'); + $lockType2 = $doc->createElementNS('DAV:','d:locktype'); + + $lockEntry1->appendChild($lockScope1); + $lockEntry1->appendChild($lockType1); + $lockEntry2->appendChild($lockScope2); + $lockEntry2->appendChild($lockType2); + + $lockScope1->appendChild($doc->createElementNS('DAV:','d:exclusive')); + $lockScope2->appendChild($doc->createElementNS('DAV:','d:shared')); + + $lockType1->appendChild($doc->createElementNS('DAV:','d:write')); + $lockType2->appendChild($doc->createElementNS('DAV:','d:write')); + + //$frag->appendXML(''); + //$frag->appendXML(''); + + } + +} + diff --git a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php b/3rdparty/Sabre/DAV/Property/SupportedReportSet.php new file mode 100755 index 00000000000..e62699f3b5a --- /dev/null +++ b/3rdparty/Sabre/DAV/Property/SupportedReportSet.php @@ -0,0 +1,109 @@ +addReport($reports); + + } + + /** + * Adds a report to this property + * + * The report must be a string in clark-notation. + * Multiple reports can be specified as an array. + * + * @param mixed $report + * @return void + */ + public function addReport($report) { + + if (!is_array($report)) $report = array($report); + + foreach($report as $r) { + + if (!preg_match('/^{([^}]*)}(.*)$/',$r)) + throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); + + $this->reports[] = $r; + + } + + } + + /** + * Returns the list of supported reports + * + * @return array + */ + public function getValue() { + + return $this->reports; + + } + + /** + * Serializes the node + * + * @param Sabre_DAV_Server $server + * @param DOMElement $prop + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { + + foreach($this->reports as $reportName) { + + $supportedReport = $prop->ownerDocument->createElement('d:supported-report'); + $prop->appendChild($supportedReport); + + $report = $prop->ownerDocument->createElement('d:report'); + $supportedReport->appendChild($report); + + preg_match('/^{([^}]*)}(.*)$/',$reportName,$matches); + + list(, $namespace, $element) = $matches; + + $prefix = isset($server->xmlNamespaces[$namespace])?$server->xmlNamespaces[$namespace]:null; + + if ($prefix) { + $report->appendChild($prop->ownerDocument->createElement($prefix . ':' . $element)); + } else { + $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:' . $element)); + } + + } + + } + +} diff --git a/3rdparty/Sabre/DAV/Server.php b/3rdparty/Sabre/DAV/Server.php new file mode 100755 index 00000000000..4284c127b6e --- /dev/null +++ b/3rdparty/Sabre/DAV/Server.php @@ -0,0 +1,1999 @@ + 'd', + 'http://sabredav.org/ns' => 's', + ); + + /** + * The propertymap can be used to map properties from + * requests to property classes. + * + * @var array + */ + public $propertyMap = array( + '{DAV:}resourcetype' => 'Sabre_DAV_Property_ResourceType', + ); + + public $protectedProperties = array( + // RFC4918 + '{DAV:}getcontentlength', + '{DAV:}getetag', + '{DAV:}getlastmodified', + '{DAV:}lockdiscovery', + '{DAV:}resourcetype', + '{DAV:}supportedlock', + + // RFC4331 + '{DAV:}quota-available-bytes', + '{DAV:}quota-used-bytes', + + // RFC3744 + '{DAV:}supported-privilege-set', + '{DAV:}current-user-privilege-set', + '{DAV:}acl', + '{DAV:}acl-restrictions', + '{DAV:}inherited-acl-set', + + ); + + /** + * This is a flag that allow or not showing file, line and code + * of the exception in the returned XML + * + * @var bool + */ + public $debugExceptions = false; + + /** + * This property allows you to automatically add the 'resourcetype' value + * based on a node's classname or interface. + * + * The preset ensures that {DAV:}collection is automaticlly added for nodes + * implementing Sabre_DAV_ICollection. + * + * @var array + */ + public $resourceTypeMapping = array( + 'Sabre_DAV_ICollection' => '{DAV:}collection', + ); + + /** + * If this setting is turned off, SabreDAV's version number will be hidden + * from various places. + * + * Some people feel this is a good security measure. + * + * @var bool + */ + static public $exposeVersion = true; + + /** + * Sets up the server + * + * If a Sabre_DAV_Tree object is passed as an argument, it will + * use it as the directory tree. If a Sabre_DAV_INode is passed, it + * will create a Sabre_DAV_ObjectTree and use the node as the root. + * + * If nothing is passed, a Sabre_DAV_SimpleCollection is created in + * a Sabre_DAV_ObjectTree. + * + * If an array is passed, we automatically create a root node, and use + * the nodes in the array as top-level children. + * + * @param Sabre_DAV_Tree|Sabre_DAV_INode|null $treeOrNode The tree object + */ + public function __construct($treeOrNode = null) { + + if ($treeOrNode instanceof Sabre_DAV_Tree) { + $this->tree = $treeOrNode; + } elseif ($treeOrNode instanceof Sabre_DAV_INode) { + $this->tree = new Sabre_DAV_ObjectTree($treeOrNode); + } elseif (is_array($treeOrNode)) { + + // If it's an array, a list of nodes was passed, and we need to + // create the root node. + foreach($treeOrNode as $node) { + if (!($node instanceof Sabre_DAV_INode)) { + throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode'); + } + } + + $root = new Sabre_DAV_SimpleCollection('root', $treeOrNode); + $this->tree = new Sabre_DAV_ObjectTree($root); + + } elseif (is_null($treeOrNode)) { + $root = new Sabre_DAV_SimpleCollection('root'); + $this->tree = new Sabre_DAV_ObjectTree($root); + } else { + throw new Sabre_DAV_Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre_DAV_Tree, Sabre_DAV_INode, an array or null'); + } + $this->httpResponse = new Sabre_HTTP_Response(); + $this->httpRequest = new Sabre_HTTP_Request(); + + } + + /** + * Starts the DAV Server + * + * @return void + */ + public function exec() { + + try { + + $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri()); + + } catch (Exception $e) { + + $DOM = new DOMDocument('1.0','utf-8'); + $DOM->formatOutput = true; + + $error = $DOM->createElementNS('DAV:','d:error'); + $error->setAttribute('xmlns:s',self::NS_SABREDAV); + $DOM->appendChild($error); + + $error->appendChild($DOM->createElement('s:exception',get_class($e))); + $error->appendChild($DOM->createElement('s:message',$e->getMessage())); + if ($this->debugExceptions) { + $error->appendChild($DOM->createElement('s:file',$e->getFile())); + $error->appendChild($DOM->createElement('s:line',$e->getLine())); + $error->appendChild($DOM->createElement('s:code',$e->getCode())); + $error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString())); + + } + if (self::$exposeVersion) { + $error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION)); + } + + if($e instanceof Sabre_DAV_Exception) { + + $httpCode = $e->getHTTPCode(); + $e->serialize($this,$error); + $headers = $e->getHTTPHeaders($this); + + } else { + + $httpCode = 500; + $headers = array(); + + } + $headers['Content-Type'] = 'application/xml; charset=utf-8'; + + $this->httpResponse->sendStatus($httpCode); + $this->httpResponse->setHeaders($headers); + $this->httpResponse->sendBody($DOM->saveXML()); + + } + + } + + /** + * Sets the base server uri + * + * @param string $uri + * @return void + */ + public function setBaseUri($uri) { + + // If the baseUri does not end with a slash, we must add it + if ($uri[strlen($uri)-1]!=='/') + $uri.='/'; + + $this->baseUri = $uri; + + } + + /** + * Returns the base responding uri + * + * @return string + */ + public function getBaseUri() { + + if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri(); + return $this->baseUri; + + } + + /** + * This method attempts to detect the base uri. + * Only the PATH_INFO variable is considered. + * + * If this variable is not set, the root (/) is assumed. + * + * @return string + */ + public function guessBaseUri() { + + $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO'); + $uri = $this->httpRequest->getRawServerValue('REQUEST_URI'); + + // If PATH_INFO is found, we can assume it's accurate. + if (!empty($pathInfo)) { + + // We need to make sure we ignore the QUERY_STRING part + if ($pos = strpos($uri,'?')) + $uri = substr($uri,0,$pos); + + // PATH_INFO is only set for urls, such as: /example.php/path + // in that case PATH_INFO contains '/path'. + // Note that REQUEST_URI is percent encoded, while PATH_INFO is + // not, Therefore they are only comparable if we first decode + // REQUEST_INFO as well. + $decodedUri = Sabre_DAV_URLUtil::decodePath($uri); + + // A simple sanity check: + if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) { + $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo)); + return rtrim($baseUri,'/') . '/'; + } + + throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.'); + + } + + // The last fallback is that we're just going to assume the server root. + return '/'; + + } + + /** + * Adds a plugin to the server + * + * For more information, console the documentation of Sabre_DAV_ServerPlugin + * + * @param Sabre_DAV_ServerPlugin $plugin + * @return void + */ + public function addPlugin(Sabre_DAV_ServerPlugin $plugin) { + + $this->plugins[$plugin->getPluginName()] = $plugin; + $plugin->initialize($this); + + } + + /** + * Returns an initialized plugin by it's name. + * + * This function returns null if the plugin was not found. + * + * @param string $name + * @return Sabre_DAV_ServerPlugin + */ + public function getPlugin($name) { + + if (isset($this->plugins[$name])) + return $this->plugins[$name]; + + // This is a fallback and deprecated. + foreach($this->plugins as $plugin) { + if (get_class($plugin)===$name) return $plugin; + } + + return null; + + } + + /** + * Returns all plugins + * + * @return array + */ + public function getPlugins() { + + return $this->plugins; + + } + + + /** + * Subscribe to an event. + * + * When the event is triggered, we'll call all the specified callbacks. + * It is possible to control the order of the callbacks through the + * priority argument. + * + * This is for example used to make sure that the authentication plugin + * is triggered before anything else. If it's not needed to change this + * number, it is recommended to ommit. + * + * @param string $event + * @param callback $callback + * @param int $priority + * @return void + */ + public function subscribeEvent($event, $callback, $priority = 100) { + + if (!isset($this->eventSubscriptions[$event])) { + $this->eventSubscriptions[$event] = array(); + } + while(isset($this->eventSubscriptions[$event][$priority])) $priority++; + $this->eventSubscriptions[$event][$priority] = $callback; + ksort($this->eventSubscriptions[$event]); + + } + + /** + * Broadcasts an event + * + * This method will call all subscribers. If one of the subscribers returns false, the process stops. + * + * The arguments parameter will be sent to all subscribers + * + * @param string $eventName + * @param array $arguments + * @return bool + */ + public function broadcastEvent($eventName,$arguments = array()) { + + if (isset($this->eventSubscriptions[$eventName])) { + + foreach($this->eventSubscriptions[$eventName] as $subscriber) { + + $result = call_user_func_array($subscriber,$arguments); + if ($result===false) return false; + + } + + } + + return true; + + } + + /** + * Handles a http request, and execute a method based on its name + * + * @param string $method + * @param string $uri + * @return void + */ + public function invokeMethod($method, $uri) { + + $method = strtoupper($method); + + if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return; + + // Make sure this is a HTTP method we support + $internalMethods = array( + 'OPTIONS', + 'GET', + 'HEAD', + 'DELETE', + 'PROPFIND', + 'MKCOL', + 'PUT', + 'PROPPATCH', + 'COPY', + 'MOVE', + 'REPORT' + ); + + if (in_array($method,$internalMethods)) { + + call_user_func(array($this,'http' . $method), $uri); + + } else { + + if ($this->broadcastEvent('unknownMethod',array($method, $uri))) { + // Unsupported method + throw new Sabre_DAV_Exception_NotImplemented('There was no handler found for this "' . $method . '" method'); + } + + } + + } + + // {{{ HTTP Method implementations + + /** + * HTTP OPTIONS + * + * @param string $uri + * @return void + */ + protected function httpOptions($uri) { + + $methods = $this->getAllowedMethods($uri); + + $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods))); + $features = array('1','3', 'extended-mkcol'); + + foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); + + $this->httpResponse->setHeader('DAV',implode(', ',$features)); + $this->httpResponse->setHeader('MS-Author-Via','DAV'); + $this->httpResponse->setHeader('Accept-Ranges','bytes'); + if (self::$exposeVersion) { + $this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION); + } + $this->httpResponse->setHeader('Content-Length',0); + $this->httpResponse->sendStatus(200); + + } + + /** + * HTTP GET + * + * This method simply fetches the contents of a uri, like normal + * + * @param string $uri + * @return bool + */ + protected function httpGet($uri) { + + $node = $this->tree->getNodeForPath($uri,0); + + if (!$this->checkPreconditions(true)) return false; + + if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); + $body = $node->get(); + + // Converting string into stream, if needed. + if (is_string($body)) { + $stream = fopen('php://temp','r+'); + fwrite($stream,$body); + rewind($stream); + $body = $stream; + } + + /* + * TODO: getetag, getlastmodified, getsize should also be used using + * this method + */ + $httpHeaders = $this->getHTTPHeaders($uri); + + /* ContentType needs to get a default, because many webservers will otherwise + * default to text/html, and we don't want this for security reasons. + */ + if (!isset($httpHeaders['Content-Type'])) { + $httpHeaders['Content-Type'] = 'application/octet-stream'; + } + + + if (isset($httpHeaders['Content-Length'])) { + + $nodeSize = $httpHeaders['Content-Length']; + + // Need to unset Content-Length, because we'll handle that during figuring out the range + unset($httpHeaders['Content-Length']); + + } else { + $nodeSize = null; + } + + $this->httpResponse->setHeaders($httpHeaders); + + $range = $this->getHTTPRange(); + $ifRange = $this->httpRequest->getHeader('If-Range'); + $ignoreRangeHeader = false; + + // If ifRange is set, and range is specified, we first need to check + // the precondition. + if ($nodeSize && $range && $ifRange) { + + // if IfRange is parsable as a date we'll treat it as a DateTime + // otherwise, we must treat it as an etag. + try { + $ifRangeDate = new DateTime($ifRange); + + // It's a date. We must check if the entity is modified since + // the specified date. + if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true; + else { + $modified = new DateTime($httpHeaders['Last-Modified']); + if($modified > $ifRangeDate) $ignoreRangeHeader = true; + } + + } catch (Exception $e) { + + // It's an entity. We can do a simple comparison. + if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true; + elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true; + } + } + + // We're only going to support HTTP ranges if the backend provided a filesize + if (!$ignoreRangeHeader && $nodeSize && $range) { + + // Determining the exact byte offsets + if (!is_null($range[0])) { + + $start = $range[0]; + $end = $range[1]?$range[1]:$nodeSize-1; + if($start >= $nodeSize) + throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')'); + + if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); + if($end >= $nodeSize) $end = $nodeSize-1; + + } else { + + $start = $nodeSize-$range[1]; + $end = $nodeSize-1; + + if ($start<0) $start = 0; + + } + + // New read/write stream + $newStream = fopen('php://temp','r+'); + + stream_copy_to_stream($body, $newStream, $end-$start+1, $start); + rewind($newStream); + + $this->httpResponse->setHeader('Content-Length', $end-$start+1); + $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize); + $this->httpResponse->sendStatus(206); + $this->httpResponse->sendBody($newStream); + + + } else { + + if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize); + $this->httpResponse->sendStatus(200); + $this->httpResponse->sendBody($body); + + } + + } + + /** + * HTTP HEAD + * + * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body + * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again + * + * @param string $uri + * @return void + */ + protected function httpHead($uri) { + + $node = $this->tree->getNodeForPath($uri); + /* This information is only collection for File objects. + * Ideally we want to throw 405 Method Not Allowed for every + * non-file, but MS Office does not like this + */ + if ($node instanceof Sabre_DAV_IFile) { + $headers = $this->getHTTPHeaders($this->getRequestUri()); + if (!isset($headers['Content-Type'])) { + $headers['Content-Type'] = 'application/octet-stream'; + } + $this->httpResponse->setHeaders($headers); + } + $this->httpResponse->sendStatus(200); + + } + + /** + * HTTP Delete + * + * The HTTP delete method, deletes a given uri + * + * @param string $uri + * @return void + */ + protected function httpDelete($uri) { + + if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; + $this->tree->delete($uri); + $this->broadcastEvent('afterUnbind',array($uri)); + + $this->httpResponse->sendStatus(204); + $this->httpResponse->setHeader('Content-Length','0'); + + } + + + /** + * WebDAV PROPFIND + * + * This WebDAV method requests information about an uri resource, or a list of resources + * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value + * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory) + * + * The request body contains an XML data structure that has a list of properties the client understands + * The response body is also an xml document, containing information about every uri resource and the requested properties + * + * It has to return a HTTP 207 Multi-status status code + * + * @param string $uri + * @return void + */ + protected function httpPropfind($uri) { + + // $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input')); + $requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true)); + + $depth = $this->getHTTPDepth(1); + // The only two options for the depth of a propfind is 0 or 1 + if ($depth!=0) $depth = 1; + + $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth); + + // This is a multi-status response + $this->httpResponse->sendStatus(207); + $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + + // Normally this header is only needed for OPTIONS responses, however.. + // iCal seems to also depend on these being set for PROPFIND. Since + // this is not harmful, we'll add it. + $features = array('1','3', 'extended-mkcol'); + foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); + $this->httpResponse->setHeader('DAV',implode(', ',$features)); + + $data = $this->generateMultiStatus($newProperties); + $this->httpResponse->sendBody($data); + + } + + /** + * WebDAV PROPPATCH + * + * This method is called to update properties on a Node. The request is an XML body with all the mutations. + * In this XML body it is specified which properties should be set/updated and/or deleted + * + * @param string $uri + * @return void + */ + protected function httpPropPatch($uri) { + + $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true)); + + $result = $this->updateProperties($uri, $newProperties); + + $this->httpResponse->sendStatus(207); + $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + + $this->httpResponse->sendBody( + $this->generateMultiStatus(array($result)) + ); + + } + + /** + * HTTP PUT method + * + * This HTTP method updates a file, or creates a new one. + * + * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content + * + * @param string $uri + * @return bool + */ + protected function httpPut($uri) { + + $body = $this->httpRequest->getBody(); + + // Intercepting Content-Range + if ($this->httpRequest->getHeader('Content-Range')) { + /** + Content-Range is dangerous for PUT requests: PUT per definition + stores a full resource. draft-ietf-httpbis-p2-semantics-15 says + in section 7.6: + An origin server SHOULD reject any PUT request that contains a + Content-Range header field, since it might be misinterpreted as + partial content (or might be partial content that is being mistakenly + PUT as a full representation). Partial content updates are possible + by targeting a separately identified resource with state that + overlaps a portion of the larger resource, or by using a different + method that has been specifically defined for partial updates (for + example, the PATCH method defined in [RFC5789]). + This clarifies RFC2616 section 9.6: + The recipient of the entity MUST NOT ignore any Content-* + (e.g. Content-Range) headers that it does not understand or implement + and MUST return a 501 (Not Implemented) response in such cases. + OTOH is a PUT request with a Content-Range currently the only way to + continue an aborted upload request and is supported by curl, mod_dav, + Tomcat and others. Since some clients do use this feature which results + in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject + all PUT requests with a Content-Range for now. + */ + + throw new Sabre_DAV_Exception_NotImplemented('PUT with Content-Range is not allowed.'); + } + + // Intercepting the Finder problem + if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { + + /** + Many webservers will not cooperate well with Finder PUT requests, + because it uses 'Chunked' transfer encoding for the request body. + + The symptom of this problem is that Finder sends files to the + server, but they arrive as 0-length files in PHP. + + If we don't do anything, the user might think they are uploading + files successfully, but they end up empty on the server. Instead, + we throw back an error if we detect this. + + The reason Finder uses Chunked, is because it thinks the files + might change as it's being uploaded, and therefore the + Content-Length can vary. + + Instead it sends the X-Expected-Entity-Length header with the size + of the file at the very start of the request. If this header is set, + but we don't get a request body we will fail the request to + protect the end-user. + */ + + // Only reading first byte + $firstByte = fread($body,1); + if (strlen($firstByte)!==1) { + throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); + } + + // The body needs to stay intact, so we copy everything to a + // temporary stream. + + $newBody = fopen('php://temp','r+'); + fwrite($newBody,$firstByte); + stream_copy_to_stream($body, $newBody); + rewind($newBody); + + $body = $newBody; + + } + + if ($this->tree->nodeExists($uri)) { + + $node = $this->tree->getNodeForPath($uri); + + // Checking If-None-Match and related headers. + if (!$this->checkPreconditions()) return; + + // If the node is a collection, we'll deny it + if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); + if (!$this->broadcastEvent('beforeWriteContent',array($uri, $node, &$body))) return false; + + $etag = $node->put($body); + + $this->broadcastEvent('afterWriteContent',array($uri, $node)); + + $this->httpResponse->setHeader('Content-Length','0'); + if ($etag) $this->httpResponse->setHeader('ETag',$etag); + $this->httpResponse->sendStatus(204); + + } else { + + $etag = null; + // If we got here, the resource didn't exist yet. + if (!$this->createFile($this->getRequestUri(),$body,$etag)) { + // For one reason or another the file was not created. + return; + } + + $this->httpResponse->setHeader('Content-Length','0'); + if ($etag) $this->httpResponse->setHeader('ETag', $etag); + $this->httpResponse->sendStatus(201); + + } + + } + + + /** + * WebDAV MKCOL + * + * The MKCOL method is used to create a new collection (directory) on the server + * + * @param string $uri + * @return void + */ + protected function httpMkcol($uri) { + + $requestBody = $this->httpRequest->getBody(true); + + if ($requestBody) { + + $contentType = $this->httpRequest->getHeader('Content-Type'); + if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) { + + // We must throw 415 for unsupported mkcol bodies + throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type'); + + } + + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody); + if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') { + + // We must throw 415 for unsupported mkcol bodies + throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.'); + + } + + $properties = array(); + foreach($dom->firstChild->childNodes as $childNode) { + + if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue; + $properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap)); + + } + if (!isset($properties['{DAV:}resourcetype'])) + throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property'); + + $resourceType = $properties['{DAV:}resourcetype']->getValue(); + unset($properties['{DAV:}resourcetype']); + + } else { + + $properties = array(); + $resourceType = array('{DAV:}collection'); + + } + + $result = $this->createCollection($uri, $resourceType, $properties); + + if (is_array($result)) { + $this->httpResponse->sendStatus(207); + $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + + $this->httpResponse->sendBody( + $this->generateMultiStatus(array($result)) + ); + + } else { + $this->httpResponse->setHeader('Content-Length','0'); + $this->httpResponse->sendStatus(201); + } + + } + + /** + * WebDAV HTTP MOVE method + * + * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo + * + * @param string $uri + * @return void + */ + protected function httpMove($uri) { + + $moveInfo = $this->getCopyAndMoveInfo(); + + // If the destination is part of the source tree, we must fail + if ($moveInfo['destination']==$uri) + throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); + + if ($moveInfo['destinationExists']) { + + if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false; + $this->tree->delete($moveInfo['destination']); + $this->broadcastEvent('afterUnbind',array($moveInfo['destination'])); + + } + + if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false; + if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false; + $this->tree->move($uri,$moveInfo['destination']); + $this->broadcastEvent('afterUnbind',array($uri)); + $this->broadcastEvent('afterBind',array($moveInfo['destination'])); + + // If a resource was overwritten we should send a 204, otherwise a 201 + $this->httpResponse->setHeader('Content-Length','0'); + $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201); + + } + + /** + * WebDAV HTTP COPY method + * + * This method copies one uri to a different uri, and works much like the MOVE request + * A lot of the actual request processing is done in getCopyMoveInfo + * + * @param string $uri + * @return bool + */ + protected function httpCopy($uri) { + + $copyInfo = $this->getCopyAndMoveInfo(); + // If the destination is part of the source tree, we must fail + if ($copyInfo['destination']==$uri) + throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); + + if ($copyInfo['destinationExists']) { + if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false; + $this->tree->delete($copyInfo['destination']); + + } + if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false; + $this->tree->copy($uri,$copyInfo['destination']); + $this->broadcastEvent('afterBind',array($copyInfo['destination'])); + + // If a resource was overwritten we should send a 204, otherwise a 201 + $this->httpResponse->setHeader('Content-Length','0'); + $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201); + + } + + + + /** + * HTTP REPORT method implementation + * + * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253) + * It's used in a lot of extensions, so it made sense to implement it into the core. + * + * @param string $uri + * @return void + */ + protected function httpReport($uri) { + + $body = $this->httpRequest->getBody(true); + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); + + $reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild); + + if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) { + + // If broadcastEvent returned true, it means the report was not supported + throw new Sabre_DAV_Exception_ReportNotImplemented(); + + } + + } + + // }}} + // {{{ HTTP/WebDAV protocol helpers + + /** + * Returns an array with all the supported HTTP methods for a specific uri. + * + * @param string $uri + * @return array + */ + public function getAllowedMethods($uri) { + + $methods = array( + 'OPTIONS', + 'GET', + 'HEAD', + 'DELETE', + 'PROPFIND', + 'PUT', + 'PROPPATCH', + 'COPY', + 'MOVE', + 'REPORT' + ); + + // The MKCOL is only allowed on an unmapped uri + try { + $this->tree->getNodeForPath($uri); + } catch (Sabre_DAV_Exception_NotFound $e) { + $methods[] = 'MKCOL'; + } + + // We're also checking if any of the plugins register any new methods + foreach($this->plugins as $plugin) $methods = array_merge($methods, $plugin->getHTTPMethods($uri)); + array_unique($methods); + + return $methods; + + } + + /** + * Gets the uri for the request, keeping the base uri into consideration + * + * @return string + */ + public function getRequestUri() { + + return $this->calculateUri($this->httpRequest->getUri()); + + } + + /** + * Calculates the uri for a request, making sure that the base uri is stripped out + * + * @param string $uri + * @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri + * @return string + */ + public function calculateUri($uri) { + + if ($uri[0]!='/' && strpos($uri,'://')) { + + $uri = parse_url($uri,PHP_URL_PATH); + + } + + $uri = str_replace('//','/',$uri); + + if (strpos($uri,$this->getBaseUri())===0) { + + return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/'); + + // A special case, if the baseUri was accessed without a trailing + // slash, we'll accept it as well. + } elseif ($uri.'/' === $this->getBaseUri()) { + + return ''; + + } else { + + throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')'); + + } + + } + + /** + * Returns the HTTP depth header + * + * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object + * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existent + * + * @param mixed $default + * @return int + */ + public function getHTTPDepth($default = self::DEPTH_INFINITY) { + + // If its not set, we'll grab the default + $depth = $this->httpRequest->getHeader('Depth'); + + if (is_null($depth)) return $default; + + if ($depth == 'infinity') return self::DEPTH_INFINITY; + + + // If its an unknown value. we'll grab the default + if (!ctype_digit($depth)) return $default; + + return (int)$depth; + + } + + /** + * Returns the HTTP range header + * + * This method returns null if there is no well-formed HTTP range request + * header or array($start, $end). + * + * The first number is the offset of the first byte in the range. + * The second number is the offset of the last byte in the range. + * + * If the second offset is null, it should be treated as the offset of the last byte of the entity + * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity + * + * @return array|null + */ + public function getHTTPRange() { + + $range = $this->httpRequest->getHeader('range'); + if (is_null($range)) return null; + + // Matching "Range: bytes=1234-5678: both numbers are optional + + if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; + + if ($matches[1]==='' && $matches[2]==='') return null; + + return array( + $matches[1]!==''?$matches[1]:null, + $matches[2]!==''?$matches[2]:null, + ); + + } + + + /** + * Returns information about Copy and Move requests + * + * This function is created to help getting information about the source and the destination for the + * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions + * + * The returned value is an array with the following keys: + * * destination - Destination path + * * destinationExists - Whether or not the destination is an existing url (and should therefore be overwritten) + * + * @return array + */ + public function getCopyAndMoveInfo() { + + // Collecting the relevant HTTP headers + if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); + $destination = $this->calculateUri($this->httpRequest->getHeader('Destination')); + $overwrite = $this->httpRequest->getHeader('Overwrite'); + if (!$overwrite) $overwrite = 'T'; + if (strtoupper($overwrite)=='T') $overwrite = true; + elseif (strtoupper($overwrite)=='F') $overwrite = false; + // We need to throw a bad request exception, if the header was invalid + else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); + + list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination); + + try { + $destinationParent = $this->tree->getNodeForPath($destinationDir); + if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); + } catch (Sabre_DAV_Exception_NotFound $e) { + + // If the destination parent node is not found, we throw a 409 + throw new Sabre_DAV_Exception_Conflict('The destination node is not found'); + } + + try { + + $destinationNode = $this->tree->getNodeForPath($destination); + + // If this succeeded, it means the destination already exists + // we'll need to throw precondition failed in case overwrite is false + if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite'); + + } catch (Sabre_DAV_Exception_NotFound $e) { + + // Destination didn't exist, we're all good + $destinationNode = false; + + + + } + + // These are the three relevant properties we need to return + return array( + 'destination' => $destination, + 'destinationExists' => $destinationNode==true, + 'destinationNode' => $destinationNode, + ); + + } + + /** + * Returns a list of properties for a path + * + * This is a simplified version getPropertiesForPath. + * if you aren't interested in status codes, but you just + * want to have a flat list of properties. Use this method. + * + * @param string $path + * @param array $propertyNames + */ + public function getProperties($path, $propertyNames) { + + $result = $this->getPropertiesForPath($path,$propertyNames,0); + return $result[0][200]; + + } + + /** + * A kid-friendly way to fetch properties for a node's children. + * + * The returned array will be indexed by the path of the of child node. + * Only properties that are actually found will be returned. + * + * The parent node will not be returned. + * + * @param string $path + * @param array $propertyNames + * @return array + */ + public function getPropertiesForChildren($path, $propertyNames) { + + $result = array(); + foreach($this->getPropertiesForPath($path,$propertyNames,1) as $k=>$row) { + + // Skipping the parent path + if ($k === 0) continue; + + $result[$row['href']] = $row[200]; + + } + return $result; + + } + + /** + * Returns a list of HTTP headers for a particular resource + * + * The generated http headers are based on properties provided by the + * resource. The method basically provides a simple mapping between + * DAV property and HTTP header. + * + * The headers are intended to be used for HEAD and GET requests. + * + * @param string $path + * @return array + */ + public function getHTTPHeaders($path) { + + $propertyMap = array( + '{DAV:}getcontenttype' => 'Content-Type', + '{DAV:}getcontentlength' => 'Content-Length', + '{DAV:}getlastmodified' => 'Last-Modified', + '{DAV:}getetag' => 'ETag', + ); + + $properties = $this->getProperties($path,array_keys($propertyMap)); + + $headers = array(); + foreach($propertyMap as $property=>$header) { + if (!isset($properties[$property])) continue; + + if (is_scalar($properties[$property])) { + $headers[$header] = $properties[$property]; + + // GetLastModified gets special cased + } elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) { + $headers[$header] = Sabre_HTTP_Util::toHTTPDate($properties[$property]->getTime()); + } + + } + + return $headers; + + } + + /** + * Returns a list of properties for a given path + * + * The path that should be supplied should have the baseUrl stripped out + * The list of properties should be supplied in Clark notation. If the list is empty + * 'allprops' is assumed. + * + * If a depth of 1 is requested child elements will also be returned. + * + * @param string $path + * @param array $propertyNames + * @param int $depth + * @return array + */ + public function getPropertiesForPath($path, $propertyNames = array(), $depth = 0) { + + if ($depth!=0) $depth = 1; + + $returnPropertyList = array(); + + $parentNode = $this->tree->getNodeForPath($path); + $nodes = array( + $path => $parentNode + ); + if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) { + foreach($this->tree->getChildren($path) as $childNode) + $nodes[$path . '/' . $childNode->getName()] = $childNode; + } + + // If the propertyNames array is empty, it means all properties are requested. + // We shouldn't actually return everything we know though, and only return a + // sensible list. + $allProperties = count($propertyNames)==0; + + foreach($nodes as $myPath=>$node) { + + $currentPropertyNames = $propertyNames; + + $newProperties = array( + '200' => array(), + '404' => array(), + ); + + if ($allProperties) { + // Default list of propertyNames, when all properties were requested. + $currentPropertyNames = array( + '{DAV:}getlastmodified', + '{DAV:}getcontentlength', + '{DAV:}resourcetype', + '{DAV:}quota-used-bytes', + '{DAV:}quota-available-bytes', + '{DAV:}getetag', + '{DAV:}getcontenttype', + ); + } + + // If the resourceType was not part of the list, we manually add it + // and mark it for removal. We need to know the resourcetype in order + // to make certain decisions about the entry. + // WebDAV dictates we should add a / and the end of href's for collections + $removeRT = false; + if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) { + $currentPropertyNames[] = '{DAV:}resourcetype'; + $removeRT = true; + } + + $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties)); + // If this method explicitly returned false, we must ignore this + // node as it is inaccessible. + if ($result===false) continue; + + if (count($currentPropertyNames) > 0) { + + if ($node instanceof Sabre_DAV_IProperties) + $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); + + } + + + foreach($currentPropertyNames as $prop) { + + if (isset($newProperties[200][$prop])) continue; + + switch($prop) { + case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break; + case '{DAV:}getcontentlength' : + if ($node instanceof Sabre_DAV_IFile) { + $size = $node->getSize(); + if (!is_null($size)) { + $newProperties[200][$prop] = (int)$node->getSize(); + } + } + break; + case '{DAV:}quota-used-bytes' : + if ($node instanceof Sabre_DAV_IQuota) { + $quotaInfo = $node->getQuotaInfo(); + $newProperties[200][$prop] = $quotaInfo[0]; + } + break; + case '{DAV:}quota-available-bytes' : + if ($node instanceof Sabre_DAV_IQuota) { + $quotaInfo = $node->getQuotaInfo(); + $newProperties[200][$prop] = $quotaInfo[1]; + } + break; + case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break; + case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break; + case '{DAV:}supported-report-set' : + $reports = array(); + foreach($this->plugins as $plugin) { + $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath)); + } + $newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports); + break; + case '{DAV:}resourcetype' : + $newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType(); + foreach($this->resourceTypeMapping as $className => $resourceType) { + if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType); + } + break; + + } + + // If we were unable to find the property, we will list it as 404. + if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null; + + } + + $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties)); + + $newProperties['href'] = trim($myPath,'/'); + + // Its is a WebDAV recommendation to add a trailing slash to collectionnames. + // Apple's iCal also requires a trailing slash for principals (rfc 3744). + // Therefore we add a trailing / for any non-file. This might need adjustments + // if we find there are other edge cases. + if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/'; + + // If the resourcetype property was manually added to the requested property list, + // we will remove it again. + if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']); + + $returnPropertyList[] = $newProperties; + + } + + return $returnPropertyList; + + } + + /** + * This method is invoked by sub-systems creating a new file. + * + * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin). + * It was important to get this done through a centralized function, + * allowing plugins to intercept this using the beforeCreateFile event. + * + * This method will return true if the file was actually created + * + * @param string $uri + * @param resource $data + * @param string $etag + * @return bool + */ + public function createFile($uri,$data, &$etag = null) { + + list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri); + + if (!$this->broadcastEvent('beforeBind',array($uri))) return false; + + $parent = $this->tree->getNodeForPath($dir); + + if (!$this->broadcastEvent('beforeCreateFile',array($uri, &$data, $parent))) return false; + + $etag = $parent->createFile($name,$data); + $this->tree->markDirty($dir); + + $this->broadcastEvent('afterBind',array($uri)); + $this->broadcastEvent('afterCreateFile',array($uri, $parent)); + + return true; + } + + /** + * This method is invoked by sub-systems creating a new directory. + * + * @param string $uri + * @return void + */ + public function createDirectory($uri) { + + $this->createCollection($uri,array('{DAV:}collection'),array()); + + } + + /** + * Use this method to create a new collection + * + * The {DAV:}resourcetype is specified using the resourceType array. + * At the very least it must contain {DAV:}collection. + * + * The properties array can contain a list of additional properties. + * + * @param string $uri The new uri + * @param array $resourceType The resourceType(s) + * @param array $properties A list of properties + * @return array|null + */ + public function createCollection($uri, array $resourceType, array $properties) { + + list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri); + + // Making sure {DAV:}collection was specified as resourceType + if (!in_array('{DAV:}collection', $resourceType)) { + throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection'); + } + + + // Making sure the parent exists + try { + + $parent = $this->tree->getNodeForPath($parentUri); + + } catch (Sabre_DAV_Exception_NotFound $e) { + + throw new Sabre_DAV_Exception_Conflict('Parent node does not exist'); + + } + + // Making sure the parent is a collection + if (!$parent instanceof Sabre_DAV_ICollection) { + throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection'); + } + + + + // Making sure the child does not already exist + try { + $parent->getChild($newName); + + // If we got here.. it means there's already a node on that url, and we need to throw a 405 + throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists'); + + } catch (Sabre_DAV_Exception_NotFound $e) { + // This is correct + } + + + if (!$this->broadcastEvent('beforeBind',array($uri))) return; + + // There are 2 modes of operation. The standard collection + // creates the directory, and then updates properties + // the extended collection can create it directly. + if ($parent instanceof Sabre_DAV_IExtendedCollection) { + + $parent->createExtendedCollection($newName, $resourceType, $properties); + + } else { + + // No special resourcetypes are supported + if (count($resourceType)>1) { + throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.'); + } + + $parent->createDirectory($newName); + $rollBack = false; + $exception = null; + $errorResult = null; + + if (count($properties)>0) { + + try { + + $errorResult = $this->updateProperties($uri, $properties); + if (!isset($errorResult[200])) { + $rollBack = true; + } + + } catch (Sabre_DAV_Exception $e) { + + $rollBack = true; + $exception = $e; + + } + + } + + if ($rollBack) { + if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; + $this->tree->delete($uri); + + // Re-throwing exception + if ($exception) throw $exception; + + return $errorResult; + } + + } + $this->tree->markDirty($parentUri); + $this->broadcastEvent('afterBind',array($uri)); + + } + + /** + * This method updates a resource's properties + * + * The properties array must be a list of properties. Array-keys are + * property names in clarknotation, array-values are it's values. + * If a property must be deleted, the value should be null. + * + * Note that this request should either completely succeed, or + * completely fail. + * + * The response is an array with statuscodes for keys, which in turn + * contain arrays with propertynames. This response can be used + * to generate a multistatus body. + * + * @param string $uri + * @param array $properties + * @return array + */ + public function updateProperties($uri, array $properties) { + + // we'll start by grabbing the node, this will throw the appropriate + // exceptions if it doesn't. + $node = $this->tree->getNodeForPath($uri); + + $result = array( + 200 => array(), + 403 => array(), + 424 => array(), + ); + $remainingProperties = $properties; + $hasError = false; + + // Running through all properties to make sure none of them are protected + if (!$hasError) foreach($properties as $propertyName => $value) { + if(in_array($propertyName, $this->protectedProperties)) { + $result[403][$propertyName] = null; + unset($remainingProperties[$propertyName]); + $hasError = true; + } + } + + if (!$hasError) { + // Allowing plugins to take care of property updating + $hasError = !$this->broadcastEvent('updateProperties',array( + &$remainingProperties, + &$result, + $node + )); + } + + // If the node is not an instance of Sabre_DAV_IProperties, every + // property is 403 Forbidden + if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) { + $hasError = true; + foreach($properties as $propertyName=> $value) { + $result[403][$propertyName] = null; + } + $remainingProperties = array(); + } + + // Only if there were no errors we may attempt to update the resource + if (!$hasError) { + + if (count($remainingProperties)>0) { + + $updateResult = $node->updateProperties($remainingProperties); + + if ($updateResult===true) { + // success + foreach($remainingProperties as $propertyName=>$value) { + $result[200][$propertyName] = null; + } + + } elseif ($updateResult===false) { + // The node failed to update the properties for an + // unknown reason + foreach($remainingProperties as $propertyName=>$value) { + $result[403][$propertyName] = null; + } + + } elseif (is_array($updateResult)) { + + // The node has detailed update information + // We need to merge the results with the earlier results. + foreach($updateResult as $status => $props) { + if (is_array($props)) { + if (!isset($result[$status])) + $result[$status] = array(); + + $result[$status] = array_merge($result[$status], $updateResult[$status]); + } + } + + } else { + throw new Sabre_DAV_Exception('Invalid result from updateProperties'); + } + $remainingProperties = array(); + } + + } + + foreach($remainingProperties as $propertyName=>$value) { + // if there are remaining properties, it must mean + // there's a dependency failure + $result[424][$propertyName] = null; + } + + // Removing empty array values + foreach($result as $status=>$props) { + + if (count($props)===0) unset($result[$status]); + + } + $result['href'] = $uri; + return $result; + + } + + /** + * This method checks the main HTTP preconditions. + * + * Currently these are: + * * If-Match + * * If-None-Match + * * If-Modified-Since + * * If-Unmodified-Since + * + * The method will return true if all preconditions are met + * The method will return false, or throw an exception if preconditions + * failed. If false is returned the operation should be aborted, and + * the appropriate HTTP response headers are already set. + * + * Normally this method will throw 412 Precondition Failed for failures + * related to If-None-Match, If-Match and If-Unmodified Since. It will + * set the status to 304 Not Modified for If-Modified_since. + * + * If the $handleAsGET argument is set to true, it will also return 304 + * Not Modified for failure of the If-None-Match precondition. This is the + * desired behaviour for HTTP GET and HTTP HEAD requests. + * + * @param bool $handleAsGET + * @return bool + */ + public function checkPreconditions($handleAsGET = false) { + + $uri = $this->getRequestUri(); + $node = null; + $lastMod = null; + $etag = null; + + if ($ifMatch = $this->httpRequest->getHeader('If-Match')) { + + // If-Match contains an entity tag. Only if the entity-tag + // matches we are allowed to make the request succeed. + // If the entity-tag is '*' we are only allowed to make the + // request succeed if a resource exists at that url. + try { + $node = $this->tree->getNodeForPath($uri); + } catch (Sabre_DAV_Exception_NotFound $e) { + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match'); + } + + // Only need to check entity tags if they are not * + if ($ifMatch!=='*') { + + // There can be multiple etags + $ifMatch = explode(',',$ifMatch); + $haveMatch = false; + foreach($ifMatch as $ifMatchItem) { + + // Stripping any extra spaces + $ifMatchItem = trim($ifMatchItem,' '); + + $etag = $node->getETag(); + if ($etag===$ifMatchItem) { + $haveMatch = true; + } + } + if (!$haveMatch) { + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match'); + } + } + } + + if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) { + + // The If-None-Match header contains an etag. + // Only if the ETag does not match the current ETag, the request will succeed + // The header can also contain *, in which case the request + // will only succeed if the entity does not exist at all. + $nodeExists = true; + if (!$node) { + try { + $node = $this->tree->getNodeForPath($uri); + } catch (Sabre_DAV_Exception_NotFound $e) { + $nodeExists = false; + } + } + if ($nodeExists) { + $haveMatch = false; + if ($ifNoneMatch==='*') $haveMatch = true; + else { + + // There might be multiple etags + $ifNoneMatch = explode(',', $ifNoneMatch); + $etag = $node->getETag(); + + foreach($ifNoneMatch as $ifNoneMatchItem) { + + // Stripping any extra spaces + $ifNoneMatchItem = trim($ifNoneMatchItem,' '); + + if ($etag===$ifNoneMatchItem) $haveMatch = true; + + } + + } + + if ($haveMatch) { + if ($handleAsGET) { + $this->httpResponse->sendStatus(304); + return false; + } else { + throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match'); + } + } + } + + } + + if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) { + + // The If-Modified-Since header contains a date. We + // will only return the entity if it has been changed since + // that date. If it hasn't been changed, we return a 304 + // header + // Note that this header only has to be checked if there was no If-None-Match header + // as per the HTTP spec. + $date = Sabre_HTTP_Util::parseHTTPDate($ifModifiedSince); + + if ($date) { + if (is_null($node)) { + $node = $this->tree->getNodeForPath($uri); + } + $lastMod = $node->getLastModified(); + if ($lastMod) { + $lastMod = new DateTime('@' . $lastMod); + if ($lastMod <= $date) { + $this->httpResponse->sendStatus(304); + $this->httpResponse->setHeader('Last-Modified', Sabre_HTTP_Util::toHTTPDate($lastMod)); + return false; + } + } + } + } + + if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) { + + // The If-Unmodified-Since will allow allow the request if the + // entity has not changed since the specified date. + $date = Sabre_HTTP_Util::parseHTTPDate($ifUnmodifiedSince); + + // We must only check the date if it's valid + if ($date) { + if (is_null($node)) { + $node = $this->tree->getNodeForPath($uri); + } + $lastMod = $node->getLastModified(); + if ($lastMod) { + $lastMod = new DateTime('@' . $lastMod); + if ($lastMod > $date) { + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since'); + } + } + } + + } + return true; + + } + + // }}} + // {{{ XML Readers & Writers + + + /** + * Generates a WebDAV propfind response body based on a list of nodes + * + * @param array $fileProperties The list with nodes + * @return string + */ + public function generateMultiStatus(array $fileProperties) { + + $dom = new DOMDocument('1.0','utf-8'); + //$dom->formatOutput = true; + $multiStatus = $dom->createElement('d:multistatus'); + $dom->appendChild($multiStatus); + + // Adding in default namespaces + foreach($this->xmlNamespaces as $namespace=>$prefix) { + + $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); + + } + + foreach($fileProperties as $entry) { + + $href = $entry['href']; + unset($entry['href']); + + $response = new Sabre_DAV_Property_Response($href,$entry); + $response->serialize($this,$multiStatus); + + } + + return $dom->saveXML(); + + } + + /** + * This method parses a PropPatch request + * + * PropPatch changes the properties for a resource. This method + * returns a list of properties. + * + * The keys in the returned array contain the property name (e.g.: {DAV:}displayname, + * and the value contains the property value. If a property is to be removed the value + * will be null. + * + * @param string $body xml body + * @return array list of properties in need of updating or deletion + */ + public function parsePropPatchRequest($body) { + + //We'll need to change the DAV namespace declaration to something else in order to make it parsable + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); + + $newProperties = array(); + + foreach($dom->firstChild->childNodes as $child) { + + if ($child->nodeType !== XML_ELEMENT_NODE) continue; + + $operation = Sabre_DAV_XMLUtil::toClarkNotation($child); + + if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue; + + $innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap); + + foreach($innerProperties as $propertyName=>$propertyValue) { + + if ($operation==='{DAV:}remove') { + $propertyValue = null; + } + + $newProperties[$propertyName] = $propertyValue; + + } + + } + + return $newProperties; + + } + + /** + * This method parses the PROPFIND request and returns its information + * + * This will either be a list of properties, or an empty array; in which case + * an {DAV:}allprop was requested. + * + * @param string $body + * @return array + */ + public function parsePropFindRequest($body) { + + // If the propfind body was empty, it means IE is requesting 'all' properties + if (!$body) return array(); + + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); + $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0); + return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); + + } + + // }}} + +} + diff --git a/3rdparty/Sabre/DAV/ServerPlugin.php b/3rdparty/Sabre/DAV/ServerPlugin.php new file mode 100755 index 00000000000..131863d13fb --- /dev/null +++ b/3rdparty/Sabre/DAV/ServerPlugin.php @@ -0,0 +1,90 @@ +name = $name; + foreach($children as $child) { + + if (!($child instanceof Sabre_DAV_INode)) throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); + $this->addChild($child); + + } + + } + + /** + * Adds a new childnode to this collection + * + * @param Sabre_DAV_INode $child + * @return void + */ + public function addChild(Sabre_DAV_INode $child) { + + $this->children[$child->getName()] = $child; + + } + + /** + * Returns the name of the collection + * + * @return string + */ + public function getName() { + + return $this->name; + + } + + /** + * Returns a child object, by its name. + * + * This method makes use of the getChildren method to grab all the child nodes, and compares the name. + * Generally its wise to override this, as this can usually be optimized + * + * @param string $name + * @throws Sabre_DAV_Exception_NotFound + * @return Sabre_DAV_INode + */ + public function getChild($name) { + + if (isset($this->children[$name])) return $this->children[$name]; + throw new Sabre_DAV_Exception_NotFound('File not found: ' . $name . ' in \'' . $this->getName() . '\''); + + } + + /** + * Returns a list of children for this collection + * + * @return array + */ + public function getChildren() { + + return array_values($this->children); + + } + + +} + diff --git a/3rdparty/Sabre/DAV/SimpleDirectory.php b/3rdparty/Sabre/DAV/SimpleDirectory.php new file mode 100755 index 00000000000..621222ebc53 --- /dev/null +++ b/3rdparty/Sabre/DAV/SimpleDirectory.php @@ -0,0 +1,21 @@ +name = $name; + $this->contents = $contents; + $this->mimeType = $mimeType; + + } + + /** + * Returns the node name for this file. + * + * This name is used to construct the url. + * + * @return string + */ + public function getName() { + + return $this->name; + + } + + /** + * Returns the data + * + * This method may either return a string or a readable stream resource + * + * @return mixed + */ + public function get() { + + return $this->contents; + + } + + /** + * Returns the size of the file, in bytes. + * + * @return int + */ + public function getSize() { + + return strlen($this->contents); + + } + + /** + * Returns the ETag for a file + * + * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. + * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. + * + * Return null if the ETag can not effectively be determined + * @return string + */ + public function getETag() { + + return '"' . md5($this->contents) . '"'; + + } + + /** + * Returns the mime-type for a file + * + * If null is returned, we'll assume application/octet-stream + * @return string + */ + public function getContentType() { + + return $this->mimeType; + + } + +} diff --git a/3rdparty/Sabre/DAV/StringUtil.php b/3rdparty/Sabre/DAV/StringUtil.php new file mode 100755 index 00000000000..b126a94c825 --- /dev/null +++ b/3rdparty/Sabre/DAV/StringUtil.php @@ -0,0 +1,91 @@ +dataDir = $dataDir; + + } + + /** + * Initialize the plugin + * + * This is called automatically be the Server class after this plugin is + * added with Sabre_DAV_Server::addPlugin() + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + $server->subscribeEvent('beforeMethod',array($this,'beforeMethod')); + $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile')); + + } + + /** + * This method is called before any HTTP method handler + * + * This method intercepts any GET, DELETE, PUT and PROPFIND calls to + * filenames that are known to match the 'temporary file' regex. + * + * @param string $method + * @param string $uri + * @return bool + */ + public function beforeMethod($method, $uri) { + + if (!$tempLocation = $this->isTempFile($uri)) + return true; + + switch($method) { + case 'GET' : + return $this->httpGet($tempLocation); + case 'PUT' : + return $this->httpPut($tempLocation); + case 'PROPFIND' : + return $this->httpPropfind($tempLocation, $uri); + case 'DELETE' : + return $this->httpDelete($tempLocation); + } + return true; + + } + + /** + * This method is invoked if some subsystem creates a new file. + * + * This is used to deal with HTTP LOCK requests which create a new + * file. + * + * @param string $uri + * @param resource $data + * @return bool + */ + public function beforeCreateFile($uri,$data) { + + if ($tempPath = $this->isTempFile($uri)) { + + $hR = $this->server->httpResponse; + $hR->setHeader('X-Sabre-Temp','true'); + file_put_contents($tempPath,$data); + return false; + } + return true; + + } + + /** + * This method will check if the url matches the temporary file pattern + * if it does, it will return an path based on $this->dataDir for the + * temporary file storage. + * + * @param string $path + * @return boolean|string + */ + protected function isTempFile($path) { + + // We're only interested in the basename. + list(, $tempPath) = Sabre_DAV_URLUtil::splitPath($path); + + foreach($this->temporaryFilePatterns as $tempFile) { + + if (preg_match($tempFile,$tempPath)) { + return $this->getDataDir() . '/sabredav_' . md5($path) . '.tempfile'; + } + + } + + return false; + + } + + + /** + * This method handles the GET method for temporary files. + * If the file doesn't exist, it will return false which will kick in + * the regular system for the GET method. + * + * @param string $tempLocation + * @return bool + */ + public function httpGet($tempLocation) { + + if (!file_exists($tempLocation)) return true; + + $hR = $this->server->httpResponse; + $hR->setHeader('Content-Type','application/octet-stream'); + $hR->setHeader('Content-Length',filesize($tempLocation)); + $hR->setHeader('X-Sabre-Temp','true'); + $hR->sendStatus(200); + $hR->sendBody(fopen($tempLocation,'r')); + return false; + + } + + /** + * This method handles the PUT method. + * + * @param string $tempLocation + * @return bool + */ + public function httpPut($tempLocation) { + + $hR = $this->server->httpResponse; + $hR->setHeader('X-Sabre-Temp','true'); + + $newFile = !file_exists($tempLocation); + + if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) { + throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); + } + + file_put_contents($tempLocation,$this->server->httpRequest->getBody()); + $hR->sendStatus($newFile?201:200); + return false; + + } + + /** + * This method handles the DELETE method. + * + * If the file didn't exist, it will return false, which will make the + * standard HTTP DELETE handler kick in. + * + * @param string $tempLocation + * @return bool + */ + public function httpDelete($tempLocation) { + + if (!file_exists($tempLocation)) return true; + + unlink($tempLocation); + $hR = $this->server->httpResponse; + $hR->setHeader('X-Sabre-Temp','true'); + $hR->sendStatus(204); + return false; + + } + + /** + * This method handles the PROPFIND method. + * + * It's a very lazy method, it won't bother checking the request body + * for which properties were requested, and just sends back a default + * set of properties. + * + * @param string $tempLocation + * @param string $uri + * @return bool + */ + public function httpPropfind($tempLocation, $uri) { + + if (!file_exists($tempLocation)) return true; + + $hR = $this->server->httpResponse; + $hR->setHeader('X-Sabre-Temp','true'); + $hR->sendStatus(207); + $hR->setHeader('Content-Type','application/xml; charset=utf-8'); + + $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true)); + + $properties = array( + 'href' => $uri, + 200 => array( + '{DAV:}getlastmodified' => new Sabre_DAV_Property_GetLastModified(filemtime($tempLocation)), + '{DAV:}getcontentlength' => filesize($tempLocation), + '{DAV:}resourcetype' => new Sabre_DAV_Property_ResourceType(null), + '{'.Sabre_DAV_Server::NS_SABREDAV.'}tempFile' => true, + + ), + ); + + $data = $this->server->generateMultiStatus(array($properties)); + $hR->sendBody($data); + return false; + + } + + + /** + * This method returns the directory where the temporary files should be stored. + * + * @return string + */ + protected function getDataDir() + { + return $this->dataDir; + } +} diff --git a/3rdparty/Sabre/DAV/Tree.php b/3rdparty/Sabre/DAV/Tree.php new file mode 100755 index 00000000000..50216394155 --- /dev/null +++ b/3rdparty/Sabre/DAV/Tree.php @@ -0,0 +1,193 @@ +getNodeForPath($path); + return true; + + } catch (Sabre_DAV_Exception_NotFound $e) { + + return false; + + } + + } + + /** + * Copies a file from path to another + * + * @param string $sourcePath The source location + * @param string $destinationPath The full destination path + * @return void + */ + public function copy($sourcePath, $destinationPath) { + + $sourceNode = $this->getNodeForPath($sourcePath); + + // grab the dirname and basename components + list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); + + $destinationParent = $this->getNodeForPath($destinationDir); + $this->copyNode($sourceNode,$destinationParent,$destinationName); + + $this->markDirty($destinationDir); + + } + + /** + * Moves a file from one location to another + * + * @param string $sourcePath The path to the file which should be moved + * @param string $destinationPath The full destination path, so not just the destination parent node + * @return int + */ + public function move($sourcePath, $destinationPath) { + + list($sourceDir, $sourceName) = Sabre_DAV_URLUtil::splitPath($sourcePath); + list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); + + if ($sourceDir===$destinationDir) { + $renameable = $this->getNodeForPath($sourcePath); + $renameable->setName($destinationName); + } else { + $this->copy($sourcePath,$destinationPath); + $this->getNodeForPath($sourcePath)->delete(); + } + $this->markDirty($sourceDir); + $this->markDirty($destinationDir); + + } + + /** + * Deletes a node from the tree + * + * @param string $path + * @return void + */ + public function delete($path) { + + $node = $this->getNodeForPath($path); + $node->delete(); + + list($parent) = Sabre_DAV_URLUtil::splitPath($path); + $this->markDirty($parent); + + } + + /** + * Returns a list of childnodes for a given path. + * + * @param string $path + * @return array + */ + public function getChildren($path) { + + $node = $this->getNodeForPath($path); + return $node->getChildren(); + + } + + /** + * This method is called with every tree update + * + * Examples of tree updates are: + * * node deletions + * * node creations + * * copy + * * move + * * renaming nodes + * + * If Tree classes implement a form of caching, this will allow + * them to make sure caches will be expired. + * + * If a path is passed, it is assumed that the entire subtree is dirty + * + * @param string $path + * @return void + */ + public function markDirty($path) { + + + } + + /** + * copyNode + * + * @param Sabre_DAV_INode $source + * @param Sabre_DAV_ICollection $destinationParent + * @param string $destinationName + * @return void + */ + protected function copyNode(Sabre_DAV_INode $source,Sabre_DAV_ICollection $destinationParent,$destinationName = null) { + + if (!$destinationName) $destinationName = $source->getName(); + + if ($source instanceof Sabre_DAV_IFile) { + + $data = $source->get(); + + // If the body was a string, we need to convert it to a stream + if (is_string($data)) { + $stream = fopen('php://temp','r+'); + fwrite($stream,$data); + rewind($stream); + $data = $stream; + } + $destinationParent->createFile($destinationName,$data); + $destination = $destinationParent->getChild($destinationName); + + } elseif ($source instanceof Sabre_DAV_ICollection) { + + $destinationParent->createDirectory($destinationName); + + $destination = $destinationParent->getChild($destinationName); + foreach($source->getChildren() as $child) { + + $this->copyNode($child,$destination); + + } + + } + if ($source instanceof Sabre_DAV_IProperties && $destination instanceof Sabre_DAV_IProperties) { + + $props = $source->getProperties(array()); + $destination->updateProperties($props); + + } + + } + +} + diff --git a/3rdparty/Sabre/DAV/Tree/Filesystem.php b/3rdparty/Sabre/DAV/Tree/Filesystem.php new file mode 100755 index 00000000000..85a9ee317be --- /dev/null +++ b/3rdparty/Sabre/DAV/Tree/Filesystem.php @@ -0,0 +1,123 @@ +basePath = $basePath; + + } + + /** + * Returns a new node for the given path + * + * @param string $path + * @return Sabre_DAV_FS_Node + */ + public function getNodeForPath($path) { + + $realPath = $this->getRealPath($path); + if (!file_exists($realPath)) throw new Sabre_DAV_Exception_NotFound('File at location ' . $realPath . ' not found'); + if (is_dir($realPath)) { + return new Sabre_DAV_FS_Directory($path); + } else { + return new Sabre_DAV_FS_File($path); + } + + } + + /** + * Returns the real filesystem path for a webdav url. + * + * @param string $publicPath + * @return string + */ + protected function getRealPath($publicPath) { + + return rtrim($this->basePath,'/') . '/' . trim($publicPath,'/'); + + } + + /** + * Copies a file or directory. + * + * This method must work recursively and delete the destination + * if it exists + * + * @param string $source + * @param string $destination + * @return void + */ + public function copy($source,$destination) { + + $source = $this->getRealPath($source); + $destination = $this->getRealPath($destination); + $this->realCopy($source,$destination); + + } + + /** + * Used by self::copy + * + * @param string $source + * @param string $destination + * @return void + */ + protected function realCopy($source,$destination) { + + if (is_file($source)) { + copy($source,$destination); + } else { + mkdir($destination); + foreach(scandir($source) as $subnode) { + + if ($subnode=='.' || $subnode=='..') continue; + $this->realCopy($source.'/'.$subnode,$destination.'/'.$subnode); + + } + } + + } + + /** + * Moves a file or directory recursively. + * + * If the destination exists, delete it first. + * + * @param string $source + * @param string $destination + * @return void + */ + public function move($source,$destination) { + + $source = $this->getRealPath($source); + $destination = $this->getRealPath($destination); + rename($source,$destination); + + } + +} + diff --git a/3rdparty/Sabre/DAV/URLUtil.php b/3rdparty/Sabre/DAV/URLUtil.php new file mode 100755 index 00000000000..794665a44f6 --- /dev/null +++ b/3rdparty/Sabre/DAV/URLUtil.php @@ -0,0 +1,121 @@ + + * will be returned as: + * {http://www.example.org}myelem + * + * This format is used throughout the SabreDAV sourcecode. + * Elements encoded with the urn:DAV namespace will + * be returned as if they were in the DAV: namespace. This is to avoid + * compatibility problems. + * + * This function will return null if a nodetype other than an Element is passed. + * + * @param DOMNode $dom + * @return string + */ + static function toClarkNotation(DOMNode $dom) { + + if ($dom->nodeType !== XML_ELEMENT_NODE) return null; + + // Mapping back to the real namespace, in case it was dav + if ($dom->namespaceURI=='urn:DAV') $ns = 'DAV:'; else $ns = $dom->namespaceURI; + + // Mapping to clark notation + return '{' . $ns . '}' . $dom->localName; + + } + + /** + * Parses a clark-notation string, and returns the namespace and element + * name components. + * + * If the string was invalid, it will throw an InvalidArgumentException. + * + * @param string $str + * @throws InvalidArgumentException + * @return array + */ + static function parseClarkNotation($str) { + + if (!preg_match('/^{([^}]*)}(.*)$/',$str,$matches)) { + throw new InvalidArgumentException('\'' . $str . '\' is not a valid clark-notation formatted string'); + } + + return array( + $matches[1], + $matches[2] + ); + + } + + /** + * This method takes an XML document (as string) and converts all instances of the + * DAV: namespace to urn:DAV + * + * This is unfortunately needed, because the DAV: namespace violates the xml namespaces + * spec, and causes the DOM to throw errors + * + * @param string $xmlDocument + * @return array|string|null + */ + static function convertDAVNamespace($xmlDocument) { + + // This is used to map the DAV: namespace to urn:DAV. This is needed, because the DAV: + // namespace is actually a violation of the XML namespaces specification, and will cause errors + return preg_replace("/xmlns(:[A-Za-z0-9_]*)?=(\"|\')DAV:(\\2)/","xmlns\\1=\\2urn:DAV\\2",$xmlDocument); + + } + + /** + * This method provides a generic way to load a DOMDocument for WebDAV use. + * + * This method throws a Sabre_DAV_Exception_BadRequest exception for any xml errors. + * It does not preserve whitespace, and it converts the DAV: namespace to urn:DAV. + * + * @param string $xml + * @throws Sabre_DAV_Exception_BadRequest + * @return DOMDocument + */ + static function loadDOMDocument($xml) { + + if (empty($xml)) + throw new Sabre_DAV_Exception_BadRequest('Empty XML document sent'); + + // The BitKinex client sends xml documents as UTF-16. PHP 5.3.1 (and presumably lower) + // does not support this, so we must intercept this and convert to UTF-8. + if (substr($xml,0,12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { + + // Note: the preceeding byte sequence is "]*)encoding="UTF-16"([^>]*)>|u','',$xml); + + } + + // Retaining old error setting + $oldErrorSetting = libxml_use_internal_errors(true); + + // Clearing any previous errors + libxml_clear_errors(); + + $dom = new DOMDocument(); + $dom->loadXML(self::convertDAVNamespace($xml),LIBXML_NOWARNING | LIBXML_NOERROR); + + // We don't generally care about any whitespace + $dom->preserveWhiteSpace = false; + + if ($error = libxml_get_last_error()) { + libxml_clear_errors(); + throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: ' . $error->message . ', errorcode: ' . $error->code . ', line: ' . $error->line . ')'); + } + + // Restoring old mechanism for error handling + if ($oldErrorSetting===false) libxml_use_internal_errors(false); + + return $dom; + + } + + /** + * Parses all WebDAV properties out of a DOM Element + * + * Generally WebDAV properties are enclosed in {DAV:}prop elements. This + * method helps by going through all these and pulling out the actual + * propertynames, making them array keys and making the property values, + * well.. the array values. + * + * If no value was given (self-closing element) null will be used as the + * value. This is used in for example PROPFIND requests. + * + * Complex values are supported through the propertyMap argument. The + * propertyMap should have the clark-notation properties as it's keys, and + * classnames as values. + * + * When any of these properties are found, the unserialize() method will be + * (statically) called. The result of this method is used as the value. + * + * @param DOMElement $parentNode + * @param array $propertyMap + * @return array + */ + static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) { + + $propList = array(); + foreach($parentNode->childNodes as $propNode) { + + if (Sabre_DAV_XMLUtil::toClarkNotation($propNode)!=='{DAV:}prop') continue; + + foreach($propNode->childNodes as $propNodeData) { + + /* If there are no elements in here, we actually get 1 text node, this special case is dedicated to netdrive */ + if ($propNodeData->nodeType != XML_ELEMENT_NODE) continue; + + $propertyName = Sabre_DAV_XMLUtil::toClarkNotation($propNodeData); + if (isset($propertyMap[$propertyName])) { + $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName],'unserialize'),$propNodeData); + } else { + $propList[$propertyName] = $propNodeData->textContent; + } + } + + + } + return $propList; + + } + +} diff --git a/3rdparty/Sabre/DAV/includes.php b/3rdparty/Sabre/DAV/includes.php new file mode 100755 index 00000000000..6a4890677ea --- /dev/null +++ b/3rdparty/Sabre/DAV/includes.php @@ -0,0 +1,97 @@ +principalPrefix = $principalPrefix; + $this->principalBackend = $principalBackend; + + } + + /** + * This method returns a node for a principal. + * + * The passed array contains principal information, and is guaranteed to + * at least contain a uri item. Other properties may or may not be + * supplied by the authentication backend. + * + * @param array $principalInfo + * @return Sabre_DAVACL_IPrincipal + */ + abstract function getChildForPrincipal(array $principalInfo); + + /** + * Returns the name of this collection. + * + * @return string + */ + public function getName() { + + list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); + return $name; + + } + + /** + * Return the list of users + * + * @return array + */ + public function getChildren() { + + if ($this->disableListing) + throw new Sabre_DAV_Exception_MethodNotAllowed('Listing members of this collection is disabled'); + + $children = array(); + foreach($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { + + $children[] = $this->getChildForPrincipal($principalInfo); + + + } + return $children; + + } + + /** + * Returns a child object, by its name. + * + * @param string $name + * @throws Sabre_DAV_Exception_NotFound + * @return Sabre_DAV_IPrincipal + */ + public function getChild($name) { + + $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/' . $name); + if (!$principalInfo) throw new Sabre_DAV_Exception_NotFound('Principal with name ' . $name . ' not found'); + return $this->getChildForPrincipal($principalInfo); + + } + + /** + * This method is used to search for principals matching a set of + * properties. + * + * This search is specifically used by RFC3744's principal-property-search + * REPORT. You should at least allow searching on + * http://sabredav.org/ns}email-address. + * + * The actual search should be a unicode-non-case-sensitive search. The + * keys in searchProperties are the WebDAV property names, while the values + * are the property values to search on. + * + * If multiple properties are being searched on, the search should be + * AND'ed. + * + * This method should simply return a list of 'child names', which may be + * used to call $this->getChild in the future. + * + * @param array $searchProperties + * @return array + */ + public function searchPrincipals(array $searchProperties) { + + $result = $this->principalBackend->searchPrincipals($this->principalPrefix, $searchProperties); + $r = array(); + + foreach($result as $row) { + list(, $r[]) = Sabre_DAV_URLUtil::splitPath($row); + } + + return $r; + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php b/3rdparty/Sabre/DAVACL/Exception/AceConflict.php new file mode 100755 index 00000000000..4b9f93b0036 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Exception/AceConflict.php @@ -0,0 +1,32 @@ +ownerDocument; + + $np = $doc->createElementNS('DAV:','d:no-ace-conflict'); + $errorNode->appendChild($np); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php b/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php new file mode 100755 index 00000000000..9b055dd9709 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php @@ -0,0 +1,81 @@ +uri = $uri; + $this->privileges = $privileges; + + parent::__construct('User did not have the required privileges (' . implode(',', $privileges) . ') for path "' . $uri . '"'); + + } + + /** + * Adds in extra information in the xml response. + * + * This method adds the {DAV:}need-privileges element as defined in rfc3744 + * + * @param Sabre_DAV_Server $server + * @param DOMElement $errorNode + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { + + $doc = $errorNode->ownerDocument; + + $np = $doc->createElementNS('DAV:','d:need-privileges'); + $errorNode->appendChild($np); + + foreach($this->privileges as $privilege) { + + $resource = $doc->createElementNS('DAV:','d:resource'); + $np->appendChild($resource); + + $resource->appendChild($doc->createElementNS('DAV:','d:href',$server->getBaseUri() . $this->uri)); + + $priv = $doc->createElementNS('DAV:','d:privilege'); + $resource->appendChild($priv); + + preg_match('/^{([^}]*)}(.*)$/',$privilege,$privilegeParts); + $priv->appendChild($doc->createElementNS($privilegeParts[1],'d:' . $privilegeParts[2])); + + + } + + } + +} + diff --git a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php b/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php new file mode 100755 index 00000000000..f44e3e32281 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php @@ -0,0 +1,32 @@ +ownerDocument; + + $np = $doc->createElementNS('DAV:','d:no-abstract'); + $errorNode->appendChild($np); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php b/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php new file mode 100755 index 00000000000..8d1e38ca1b4 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php @@ -0,0 +1,32 @@ +ownerDocument; + + $np = $doc->createElementNS('DAV:','d:recognized-principal'); + $errorNode->appendChild($np); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php b/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php new file mode 100755 index 00000000000..3b5d012d7fa --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php @@ -0,0 +1,32 @@ +ownerDocument; + + $np = $doc->createElementNS('DAV:','d:not-supported-privilege'); + $errorNode->appendChild($np); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/IACL.php b/3rdparty/Sabre/DAVACL/IACL.php new file mode 100755 index 00000000000..003e6993483 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/IACL.php @@ -0,0 +1,73 @@ + array( + * '{DAV:}prop1' => null, + * ), + * 201 => array( + * '{DAV:}prop2' => null, + * ), + * 403 => array( + * '{DAV:}prop3' => null, + * ), + * 424 => array( + * '{DAV:}prop4' => null, + * ), + * ); + * + * In this previous example prop1 was successfully updated or deleted, and + * prop2 was succesfully created. + * + * prop3 failed to update due to '403 Forbidden' and because of this prop4 + * also could not be updated with '424 Failed dependency'. + * + * This last example was actually incorrect. While 200 and 201 could appear + * in 1 response, if there's any error (403) the other properties should + * always fail with 423 (failed dependency). + * + * But anyway, if you don't want to scratch your head over this, just + * return true or false. + * + * @param string $path + * @param array $mutations + * @return array|bool + */ + function updatePrincipal($path, $mutations); + + /** + * This method is used to search for principals matching a set of + * properties. + * + * This search is specifically used by RFC3744's principal-property-search + * REPORT. You should at least allow searching on + * http://sabredav.org/ns}email-address. + * + * The actual search should be a unicode-non-case-sensitive search. The + * keys in searchProperties are the WebDAV property names, while the values + * are the property values to search on. + * + * If multiple properties are being searched on, the search should be + * AND'ed. + * + * This method should simply return an array with full principal uri's. + * + * If somebody attempted to search on a property the backend does not + * support, you should simply return 0 results. + * + * You can also just return 0 results if you choose to not support + * searching at all, but keep in mind that this may stop certain features + * from working. + * + * @param string $prefixPath + * @param array $searchProperties + * @return array + */ + function searchPrincipals($prefixPath, array $searchProperties); + + /** + * Returns the list of members for a group-principal + * + * @param string $principal + * @return array + */ + function getGroupMemberSet($principal); + + /** + * Returns the list of groups a principal is a member of + * + * @param string $principal + * @return array + */ + function getGroupMembership($principal); + + /** + * Updates the list of group members for a group principal. + * + * The principals should be passed as a list of uri's. + * + * @param string $principal + * @param array $members + * @return void + */ + function setGroupMemberSet($principal, array $members); + +} diff --git a/3rdparty/Sabre/DAVACL/Plugin.php b/3rdparty/Sabre/DAVACL/Plugin.php new file mode 100755 index 00000000000..5c828c6d97b --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Plugin.php @@ -0,0 +1,1348 @@ + 'Display name', + '{http://sabredav.org/ns}email-address' => 'Email address', + ); + + /** + * Any principal uri's added here, will automatically be added to the list + * of ACL's. They will effectively receive {DAV:}all privileges, as a + * protected privilege. + * + * @var array + */ + public $adminPrincipals = array(); + + /** + * Returns a list of features added by this plugin. + * + * This list is used in the response of a HTTP OPTIONS request. + * + * @return array + */ + public function getFeatures() { + + return array('access-control'); + + } + + /** + * Returns a list of available methods for a given url + * + * @param string $uri + * @return array + */ + public function getMethods($uri) { + + return array('ACL'); + + } + + /** + * Returns a plugin name. + * + * Using this name other plugins will be able to access other plugins + * using Sabre_DAV_Server::getPlugin + * + * @return string + */ + public function getPluginName() { + + return 'acl'; + + } + + /** + * Returns a list of reports this plugin supports. + * + * This will be used in the {DAV:}supported-report-set property. + * Note that you still need to subscribe to the 'report' event to actually + * implement them + * + * @param string $uri + * @return array + */ + public function getSupportedReportSet($uri) { + + return array( + '{DAV:}expand-property', + '{DAV:}principal-property-search', + '{DAV:}principal-search-property-set', + ); + + } + + + /** + * Checks if the current user has the specified privilege(s). + * + * You can specify a single privilege, or a list of privileges. + * This method will throw an exception if the privilege is not available + * and return true otherwise. + * + * @param string $uri + * @param array|string $privileges + * @param int $recursion + * @param bool $throwExceptions if set to false, this method won't through exceptions. + * @throws Sabre_DAVACL_Exception_NeedPrivileges + * @return bool + */ + public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) { + + if (!is_array($privileges)) $privileges = array($privileges); + + $acl = $this->getCurrentUserPrivilegeSet($uri); + + if (is_null($acl)) { + if ($this->allowAccessToNodesWithoutACL) { + return true; + } else { + if ($throwExceptions) + throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$privileges); + else + return false; + + } + } + + $failed = array(); + foreach($privileges as $priv) { + + if (!in_array($priv, $acl)) { + $failed[] = $priv; + } + + } + + if ($failed) { + if ($throwExceptions) + throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$failed); + else + return false; + } + return true; + + } + + /** + * Returns the standard users' principal. + * + * This is one authorative principal url for the current user. + * This method will return null if the user wasn't logged in. + * + * @return string|null + */ + public function getCurrentUserPrincipal() { + + $authPlugin = $this->server->getPlugin('auth'); + if (is_null($authPlugin)) return null; + + $userName = $authPlugin->getCurrentUser(); + if (!$userName) return null; + + return $this->defaultUsernamePath . '/' . $userName; + + } + + /** + * Returns a list of principals that's associated to the current + * user, either directly or through group membership. + * + * @return array + */ + public function getCurrentUserPrincipals() { + + $currentUser = $this->getCurrentUserPrincipal(); + + if (is_null($currentUser)) return array(); + + $check = array($currentUser); + $principals = array($currentUser); + + while(count($check)) { + + $principal = array_shift($check); + + $node = $this->server->tree->getNodeForPath($principal); + if ($node instanceof Sabre_DAVACL_IPrincipal) { + foreach($node->getGroupMembership() as $groupMember) { + + if (!in_array($groupMember, $principals)) { + + $check[] = $groupMember; + $principals[] = $groupMember; + + } + + } + + } + + } + + return $principals; + + } + + /** + * Returns the supported privilege structure for this ACL plugin. + * + * See RFC3744 for more details. Currently we default on a simple, + * standard structure. + * + * You can either get the list of privileges by a uri (path) or by + * specifying a Node. + * + * @param string|Sabre_DAV_INode $node + * @return array + */ + public function getSupportedPrivilegeSet($node) { + + if (is_string($node)) { + $node = $this->server->tree->getNodeForPath($node); + } + + if ($node instanceof Sabre_DAVACL_IACL) { + $result = $node->getSupportedPrivilegeSet(); + + if ($result) + return $result; + } + + return self::getDefaultSupportedPrivilegeSet(); + + } + + /** + * Returns a fairly standard set of privileges, which may be useful for + * other systems to use as a basis. + * + * @return array + */ + static function getDefaultSupportedPrivilegeSet() { + + return array( + 'privilege' => '{DAV:}all', + 'abstract' => true, + 'aggregates' => array( + array( + 'privilege' => '{DAV:}read', + 'aggregates' => array( + array( + 'privilege' => '{DAV:}read-acl', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}read-current-user-privilege-set', + 'abstract' => true, + ), + ), + ), // {DAV:}read + array( + 'privilege' => '{DAV:}write', + 'aggregates' => array( + array( + 'privilege' => '{DAV:}write-acl', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}write-properties', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}write-content', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}bind', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}unbind', + 'abstract' => true, + ), + array( + 'privilege' => '{DAV:}unlock', + 'abstract' => true, + ), + ), + ), // {DAV:}write + ), + ); // {DAV:}all + + } + + /** + * Returns the supported privilege set as a flat list + * + * This is much easier to parse. + * + * The returned list will be index by privilege name. + * The value is a struct containing the following properties: + * - aggregates + * - abstract + * - concrete + * + * @param string|Sabre_DAV_INode $node + * @return array + */ + final public function getFlatPrivilegeSet($node) { + + $privs = $this->getSupportedPrivilegeSet($node); + + $flat = array(); + $this->getFPSTraverse($privs, null, $flat); + + return $flat; + + } + + /** + * Traverses the privilege set tree for reordering + * + * This function is solely used by getFlatPrivilegeSet, and would have been + * a closure if it wasn't for the fact I need to support PHP 5.2. + * + * @param array $priv + * @param $concrete + * @param array $flat + * @return void + */ + final private function getFPSTraverse($priv, $concrete, &$flat) { + + $myPriv = array( + 'privilege' => $priv['privilege'], + 'abstract' => isset($priv['abstract']) && $priv['abstract'], + 'aggregates' => array(), + 'concrete' => isset($priv['abstract']) && $priv['abstract']?$concrete:$priv['privilege'], + ); + + if (isset($priv['aggregates'])) + foreach($priv['aggregates'] as $subPriv) $myPriv['aggregates'][] = $subPriv['privilege']; + + $flat[$priv['privilege']] = $myPriv; + + if (isset($priv['aggregates'])) { + + foreach($priv['aggregates'] as $subPriv) { + + $this->getFPSTraverse($subPriv, $myPriv['concrete'], $flat); + + } + + } + + } + + /** + * Returns the full ACL list. + * + * Either a uri or a Sabre_DAV_INode may be passed. + * + * null will be returned if the node doesn't support ACLs. + * + * @param string|Sabre_DAV_INode $node + * @return array + */ + public function getACL($node) { + + if (is_string($node)) { + $node = $this->server->tree->getNodeForPath($node); + } + if (!$node instanceof Sabre_DAVACL_IACL) { + return null; + } + $acl = $node->getACL(); + foreach($this->adminPrincipals as $adminPrincipal) { + $acl[] = array( + 'principal' => $adminPrincipal, + 'privilege' => '{DAV:}all', + 'protected' => true, + ); + } + return $acl; + + } + + /** + * Returns a list of privileges the current user has + * on a particular node. + * + * Either a uri or a Sabre_DAV_INode may be passed. + * + * null will be returned if the node doesn't support ACLs. + * + * @param string|Sabre_DAV_INode $node + * @return array + */ + public function getCurrentUserPrivilegeSet($node) { + + if (is_string($node)) { + $node = $this->server->tree->getNodeForPath($node); + } + + $acl = $this->getACL($node); + + if (is_null($acl)) return null; + + $principals = $this->getCurrentUserPrincipals(); + + $collected = array(); + + foreach($acl as $ace) { + + $principal = $ace['principal']; + + switch($principal) { + + case '{DAV:}owner' : + $owner = $node->getOwner(); + if ($owner && in_array($owner, $principals)) { + $collected[] = $ace; + } + break; + + + // 'all' matches for every user + case '{DAV:}all' : + + // 'authenticated' matched for every user that's logged in. + // Since it's not possible to use ACL while not being logged + // in, this is also always true. + case '{DAV:}authenticated' : + $collected[] = $ace; + break; + + // 'unauthenticated' can never occur either, so we simply + // ignore these. + case '{DAV:}unauthenticated' : + break; + + default : + if (in_array($ace['principal'], $principals)) { + $collected[] = $ace; + } + break; + + } + + + + } + + // Now we deduct all aggregated privileges. + $flat = $this->getFlatPrivilegeSet($node); + + $collected2 = array(); + while(count($collected)) { + + $current = array_pop($collected); + $collected2[] = $current['privilege']; + + foreach($flat[$current['privilege']]['aggregates'] as $subPriv) { + $collected2[] = $subPriv; + $collected[] = $flat[$subPriv]; + } + + } + + return array_values(array_unique($collected2)); + + } + + /** + * Principal property search + * + * This method can search for principals matching certain values in + * properties. + * + * This method will return a list of properties for the matched properties. + * + * @param array $searchProperties The properties to search on. This is a + * key-value list. The keys are property + * names, and the values the strings to + * match them on. + * @param array $requestedProperties This is the list of properties to + * return for every match. + * @param string $collectionUri The principal collection to search on. + * If this is ommitted, the standard + * principal collection-set will be used. + * @return array This method returns an array structure similar to + * Sabre_DAV_Server::getPropertiesForPath. Returned + * properties are index by a HTTP status code. + * + */ + public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null) { + + if (!is_null($collectionUri)) { + $uris = array($collectionUri); + } else { + $uris = $this->principalCollectionSet; + } + + $lookupResults = array(); + foreach($uris as $uri) { + + $principalCollection = $this->server->tree->getNodeForPath($uri); + if (!$principalCollection instanceof Sabre_DAVACL_AbstractPrincipalCollection) { + // Not a principal collection, we're simply going to ignore + // this. + continue; + } + + $results = $principalCollection->searchPrincipals($searchProperties); + foreach($results as $result) { + $lookupResults[] = rtrim($uri,'/') . '/' . $result; + } + + } + + $matches = array(); + + foreach($lookupResults as $lookupResult) { + + list($matches[]) = $this->server->getPropertiesForPath($lookupResult, $requestedProperties, 0); + + } + + return $matches; + + } + + /** + * Sets up the plugin + * + * This method is automatically called by the server class. + * + * @param Sabre_DAV_Server $server + * @return void + */ + public function initialize(Sabre_DAV_Server $server) { + + $this->server = $server; + $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); + + $server->subscribeEvent('beforeMethod', array($this,'beforeMethod'),20); + $server->subscribeEvent('beforeBind', array($this,'beforeBind'),20); + $server->subscribeEvent('beforeUnbind', array($this,'beforeUnbind'),20); + $server->subscribeEvent('updateProperties',array($this,'updateProperties')); + $server->subscribeEvent('beforeUnlock', array($this,'beforeUnlock'),20); + $server->subscribeEvent('report',array($this,'report')); + $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); + + array_push($server->protectedProperties, + '{DAV:}alternate-URI-set', + '{DAV:}principal-URL', + '{DAV:}group-membership', + '{DAV:}principal-collection-set', + '{DAV:}current-user-principal', + '{DAV:}supported-privilege-set', + '{DAV:}current-user-privilege-set', + '{DAV:}acl', + '{DAV:}acl-restrictions', + '{DAV:}inherited-acl-set', + '{DAV:}owner', + '{DAV:}group' + ); + + // Automatically mapping nodes implementing IPrincipal to the + // {DAV:}principal resourcetype. + $server->resourceTypeMapping['Sabre_DAVACL_IPrincipal'] = '{DAV:}principal'; + + // Mapping the group-member-set property to the HrefList property + // class. + $server->propertyMap['{DAV:}group-member-set'] = 'Sabre_DAV_Property_HrefList'; + + } + + + /* {{{ Event handlers */ + + /** + * Triggered before any method is handled + * + * @param string $method + * @param string $uri + * @return void + */ + public function beforeMethod($method, $uri) { + + $exists = $this->server->tree->nodeExists($uri); + + // If the node doesn't exists, none of these checks apply + if (!$exists) return; + + switch($method) { + + case 'GET' : + case 'HEAD' : + case 'OPTIONS' : + // For these 3 we only need to know if the node is readable. + $this->checkPrivileges($uri,'{DAV:}read'); + break; + + case 'PUT' : + case 'LOCK' : + case 'UNLOCK' : + // This method requires the write-content priv if the node + // already exists, and bind on the parent if the node is being + // created. + // The bind privilege is handled in the beforeBind event. + $this->checkPrivileges($uri,'{DAV:}write-content'); + break; + + + case 'PROPPATCH' : + $this->checkPrivileges($uri,'{DAV:}write-properties'); + break; + + case 'ACL' : + $this->checkPrivileges($uri,'{DAV:}write-acl'); + break; + + case 'COPY' : + case 'MOVE' : + // Copy requires read privileges on the entire source tree. + // If the target exists write-content normally needs to be + // checked, however, we're deleting the node beforehand and + // creating a new one after, so this is handled by the + // beforeUnbind event. + // + // The creation of the new node is handled by the beforeBind + // event. + // + // If MOVE is used beforeUnbind will also be used to check if + // the sourcenode can be deleted. + $this->checkPrivileges($uri,'{DAV:}read',self::R_RECURSIVE); + + break; + + } + + } + + /** + * Triggered before a new node is created. + * + * This allows us to check permissions for any operation that creates a + * new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. + * + * @param string $uri + * @return void + */ + public function beforeBind($uri) { + + list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); + $this->checkPrivileges($parentUri,'{DAV:}bind'); + + } + + /** + * Triggered before a node is deleted + * + * This allows us to check permissions for any operation that will delete + * an existing node. + * + * @param string $uri + * @return void + */ + public function beforeUnbind($uri) { + + list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); + $this->checkPrivileges($parentUri,'{DAV:}unbind',self::R_RECURSIVEPARENTS); + + } + + /** + * Triggered before a node is unlocked. + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lock + * @TODO: not yet implemented + * @return void + */ + public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) { + + + } + + /** + * Triggered before properties are looked up in specific nodes. + * + * @param string $uri + * @param Sabre_DAV_INode $node + * @param array $requestedProperties + * @param array $returnedProperties + * @TODO really should be broken into multiple methods, or even a class. + * @return void + */ + public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { + + // Checking the read permission + if (!$this->checkPrivileges($uri,'{DAV:}read',self::R_PARENT,false)) { + + // User is not allowed to read properties + if ($this->hideNodesFromListings) { + return false; + } + + // Marking all requested properties as '403'. + foreach($requestedProperties as $key=>$requestedProperty) { + unset($requestedProperties[$key]); + $returnedProperties[403][$requestedProperty] = null; + } + return; + + } + + /* Adding principal properties */ + if ($node instanceof Sabre_DAVACL_IPrincipal) { + + if (false !== ($index = array_search('{DAV:}alternate-URI-set', $requestedProperties))) { + + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}alternate-URI-set'] = new Sabre_DAV_Property_HrefList($node->getAlternateUriSet()); + + } + if (false !== ($index = array_search('{DAV:}principal-URL', $requestedProperties))) { + + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl() . '/'); + + } + if (false !== ($index = array_search('{DAV:}group-member-set', $requestedProperties))) { + + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}group-member-set'] = new Sabre_DAV_Property_HrefList($node->getGroupMemberSet()); + + } + if (false !== ($index = array_search('{DAV:}group-membership', $requestedProperties))) { + + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}group-membership'] = new Sabre_DAV_Property_HrefList($node->getGroupMembership()); + + } + + if (false !== ($index = array_search('{DAV:}displayname', $requestedProperties))) { + + $returnedProperties[200]['{DAV:}displayname'] = $node->getDisplayName(); + + } + + } + if (false !== ($index = array_search('{DAV:}principal-collection-set', $requestedProperties))) { + + unset($requestedProperties[$index]); + $val = $this->principalCollectionSet; + // Ensuring all collections end with a slash + foreach($val as $k=>$v) $val[$k] = $v . '/'; + $returnedProperties[200]['{DAV:}principal-collection-set'] = new Sabre_DAV_Property_HrefList($val); + + } + if (false !== ($index = array_search('{DAV:}current-user-principal', $requestedProperties))) { + + unset($requestedProperties[$index]); + if ($url = $this->getCurrentUserPrincipal()) { + $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url . '/'); + } else { + $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); + } + + } + if (false !== ($index = array_search('{DAV:}supported-privilege-set', $requestedProperties))) { + + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}supported-privilege-set'] = new Sabre_DAVACL_Property_SupportedPrivilegeSet($this->getSupportedPrivilegeSet($node)); + + } + if (false !== ($index = array_search('{DAV:}current-user-privilege-set', $requestedProperties))) { + + if (!$this->checkPrivileges($uri, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) { + $returnedProperties[403]['{DAV:}current-user-privilege-set'] = null; + unset($requestedProperties[$index]); + } else { + $val = $this->getCurrentUserPrivilegeSet($node); + if (!is_null($val)) { + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}current-user-privilege-set'] = new Sabre_DAVACL_Property_CurrentUserPrivilegeSet($val); + } + } + + } + + /* The ACL property contains all the permissions */ + if (false !== ($index = array_search('{DAV:}acl', $requestedProperties))) { + + if (!$this->checkPrivileges($uri, '{DAV:}read-acl', self::R_PARENT, false)) { + + unset($requestedProperties[$index]); + $returnedProperties[403]['{DAV:}acl'] = null; + + } else { + + $acl = $this->getACL($node); + if (!is_null($acl)) { + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}acl'] = new Sabre_DAVACL_Property_Acl($this->getACL($node)); + } + + } + + } + + /* The acl-restrictions property contains information on how privileges + * must behave. + */ + if (false !== ($index = array_search('{DAV:}acl-restrictions', $requestedProperties))) { + unset($requestedProperties[$index]); + $returnedProperties[200]['{DAV:}acl-restrictions'] = new Sabre_DAVACL_Property_AclRestrictions(); + } + + } + + /** + * This method intercepts PROPPATCH methods and make sure the + * group-member-set is updated correctly. + * + * @param array $propertyDelta + * @param array $result + * @param Sabre_DAV_INode $node + * @return bool + */ + public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) { + + if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) + return; + + if (is_null($propertyDelta['{DAV:}group-member-set'])) { + $memberSet = array(); + } elseif ($propertyDelta['{DAV:}group-member-set'] instanceof Sabre_DAV_Property_HrefList) { + $memberSet = $propertyDelta['{DAV:}group-member-set']->getHrefs(); + } else { + throw new Sabre_DAV_Exception('The group-member-set property MUST be an instance of Sabre_DAV_Property_HrefList or null'); + } + + if (!($node instanceof Sabre_DAVACL_IPrincipal)) { + $result[403]['{DAV:}group-member-set'] = null; + unset($propertyDelta['{DAV:}group-member-set']); + + // Returning false will stop the updateProperties process + return false; + } + + $node->setGroupMemberSet($memberSet); + + $result[200]['{DAV:}group-member-set'] = null; + unset($propertyDelta['{DAV:}group-member-set']); + + } + + /** + * This method handels HTTP REPORT requests + * + * @param string $reportName + * @param DOMNode $dom + * @return bool + */ + public function report($reportName, $dom) { + + switch($reportName) { + + case '{DAV:}principal-property-search' : + $this->principalPropertySearchReport($dom); + return false; + case '{DAV:}principal-search-property-set' : + $this->principalSearchPropertySetReport($dom); + return false; + case '{DAV:}expand-property' : + $this->expandPropertyReport($dom); + return false; + + } + + } + + /** + * This event is triggered for any HTTP method that is not known by the + * webserver. + * + * @param string $method + * @param string $uri + * @return bool + */ + public function unknownMethod($method, $uri) { + + if ($method!=='ACL') return; + + $this->httpACL($uri); + return false; + + } + + /** + * This method is responsible for handling the 'ACL' event. + * + * @param string $uri + * @return void + */ + public function httpACL($uri) { + + $body = $this->server->httpRequest->getBody(true); + $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); + + $newAcl = + Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild) + ->getPrivileges(); + + // Normalizing urls + foreach($newAcl as $k=>$newAce) { + $newAcl[$k]['principal'] = $this->server->calculateUri($newAce['principal']); + } + + $node = $this->server->tree->getNodeForPath($uri); + + if (!($node instanceof Sabre_DAVACL_IACL)) { + throw new Sabre_DAV_Exception_MethodNotAllowed('This node does not support the ACL method'); + } + + $oldAcl = $this->getACL($node); + + $supportedPrivileges = $this->getFlatPrivilegeSet($node); + + /* Checking if protected principals from the existing principal set are + not overwritten. */ + foreach($oldAcl as $oldAce) { + + if (!isset($oldAce['protected']) || !$oldAce['protected']) continue; + + $found = false; + foreach($newAcl as $newAce) { + if ( + $newAce['privilege'] === $oldAce['privilege'] && + $newAce['principal'] === $oldAce['principal'] && + $newAce['protected'] + ) + $found = true; + } + + if (!$found) + throw new Sabre_DAVACL_Exception_AceConflict('This resource contained a protected {DAV:}ace, but this privilege did not occur in the ACL request'); + + } + + foreach($newAcl as $newAce) { + + // Do we recognize the privilege + if (!isset($supportedPrivileges[$newAce['privilege']])) { + throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified (' . $newAce['privilege'] . ') is not recognized by this server'); + } + + if ($supportedPrivileges[$newAce['privilege']]['abstract']) { + throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified (' . $newAce['privilege'] . ') is an abstract privilege'); + } + + // Looking up the principal + try { + $principal = $this->server->tree->getNodeForPath($newAce['principal']); + } catch (Sabre_DAV_Exception_NotFound $e) { + throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal (' . $newAce['principal'] . ') does not exist'); + } + if (!($principal instanceof Sabre_DAVACL_IPrincipal)) { + throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri (' . $newAce['principal'] . ') is not a principal'); + } + + } + $node->setACL($newAcl); + + } + + /* }}} */ + + /* Reports {{{ */ + + /** + * The expand-property report is defined in RFC3253 section 3-8. + * + * This report is very similar to a standard PROPFIND. The difference is + * that it has the additional ability to look at properties containing a + * {DAV:}href element, follow that property and grab additional elements + * there. + * + * Other rfc's, such as ACL rely on this report, so it made sense to put + * it in this plugin. + * + * @param DOMElement $dom + * @return void + */ + protected function expandPropertyReport($dom) { + + $requestedProperties = $this->parseExpandPropertyReportRequest($dom->firstChild->firstChild); + $depth = $this->server->getHTTPDepth(0); + $requestUri = $this->server->getRequestUri(); + + $result = $this->expandProperties($requestUri,$requestedProperties,$depth); + + $dom = new DOMDocument('1.0','utf-8'); + $dom->formatOutput = true; + $multiStatus = $dom->createElement('d:multistatus'); + $dom->appendChild($multiStatus); + + // Adding in default namespaces + foreach($this->server->xmlNamespaces as $namespace=>$prefix) { + + $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); + + } + + foreach($result as $response) { + $response->serialize($this->server, $multiStatus); + } + + $xml = $dom->saveXML(); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->sendBody($xml); + + } + + /** + * This method is used by expandPropertyReport to parse + * out the entire HTTP request. + * + * @param DOMElement $node + * @return array + */ + protected function parseExpandPropertyReportRequest($node) { + + $requestedProperties = array(); + do { + + if (Sabre_DAV_XMLUtil::toClarkNotation($node)!=='{DAV:}property') continue; + + if ($node->firstChild) { + + $children = $this->parseExpandPropertyReportRequest($node->firstChild); + + } else { + + $children = array(); + + } + + $namespace = $node->getAttribute('namespace'); + if (!$namespace) $namespace = 'DAV:'; + + $propName = '{'.$namespace.'}' . $node->getAttribute('name'); + $requestedProperties[$propName] = $children; + + } while ($node = $node->nextSibling); + + return $requestedProperties; + + } + + /** + * This method expands all the properties and returns + * a list with property values + * + * @param array $path + * @param array $requestedProperties the list of required properties + * @param int $depth + * @return array + */ + protected function expandProperties($path, array $requestedProperties, $depth) { + + $foundProperties = $this->server->getPropertiesForPath($path, array_keys($requestedProperties), $depth); + + $result = array(); + + foreach($foundProperties as $node) { + + foreach($requestedProperties as $propertyName=>$childRequestedProperties) { + + // We're only traversing if sub-properties were requested + if(count($childRequestedProperties)===0) continue; + + // We only have to do the expansion if the property was found + // and it contains an href element. + if (!array_key_exists($propertyName,$node[200])) continue; + + if ($node[200][$propertyName] instanceof Sabre_DAV_Property_IHref) { + $hrefs = array($node[200][$propertyName]->getHref()); + } elseif ($node[200][$propertyName] instanceof Sabre_DAV_Property_HrefList) { + $hrefs = $node[200][$propertyName]->getHrefs(); + } + + $childProps = array(); + foreach($hrefs as $href) { + $childProps = array_merge($childProps, $this->expandProperties($href, $childRequestedProperties, 0)); + } + $node[200][$propertyName] = new Sabre_DAV_Property_ResponseList($childProps); + + } + $result[] = new Sabre_DAV_Property_Response($path, $node); + + } + + return $result; + + } + + /** + * principalSearchPropertySetReport + * + * This method responsible for handing the + * {DAV:}principal-search-property-set report. This report returns a list + * of properties the client may search on, using the + * {DAV:}principal-property-search report. + * + * @param DOMDocument $dom + * @return void + */ + protected function principalSearchPropertySetReport(DOMDocument $dom) { + + $httpDepth = $this->server->getHTTPDepth(0); + if ($httpDepth!==0) { + throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); + } + + if ($dom->firstChild->hasChildNodes()) + throw new Sabre_DAV_Exception_BadRequest('The principal-search-property-set report element is not allowed to have child elements'); + + $dom = new DOMDocument('1.0','utf-8'); + $dom->formatOutput = true; + $root = $dom->createElement('d:principal-search-property-set'); + $dom->appendChild($root); + // Adding in default namespaces + foreach($this->server->xmlNamespaces as $namespace=>$prefix) { + + $root->setAttribute('xmlns:' . $prefix,$namespace); + + } + + $nsList = $this->server->xmlNamespaces; + + foreach($this->principalSearchPropertySet as $propertyName=>$description) { + + $psp = $dom->createElement('d:principal-search-property'); + $root->appendChild($psp); + + $prop = $dom->createElement('d:prop'); + $psp->appendChild($prop); + + $propName = null; + preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); + + $currentProperty = $dom->createElement($nsList[$propName[1]] . ':' . $propName[2]); + $prop->appendChild($currentProperty); + + $descriptionElem = $dom->createElement('d:description'); + $descriptionElem->setAttribute('xml:lang','en'); + $descriptionElem->appendChild($dom->createTextNode($description)); + $psp->appendChild($descriptionElem); + + + } + + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendStatus(200); + $this->server->httpResponse->sendBody($dom->saveXML()); + + } + + /** + * principalPropertySearchReport + * + * This method is responsible for handing the + * {DAV:}principal-property-search report. This report can be used for + * clients to search for groups of principals, based on the value of one + * or more properties. + * + * @param DOMDocument $dom + * @return void + */ + protected function principalPropertySearchReport(DOMDocument $dom) { + + list($searchProperties, $requestedProperties, $applyToPrincipalCollectionSet) = $this->parsePrincipalPropertySearchReportRequest($dom); + + $uri = null; + if (!$applyToPrincipalCollectionSet) { + $uri = $this->server->getRequestUri(); + } + $result = $this->principalSearch($searchProperties, $requestedProperties, $uri); + + $xml = $this->server->generateMultiStatus($result); + $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->sendStatus(207); + $this->server->httpResponse->sendBody($xml); + + } + + /** + * parsePrincipalPropertySearchReportRequest + * + * This method parses the request body from a + * {DAV:}principal-property-search report. + * + * This method returns an array with two elements: + * 1. an array with properties to search on, and their values + * 2. a list of propertyvalues that should be returned for the request. + * + * @param DOMDocument $dom + * @return array + */ + protected function parsePrincipalPropertySearchReportRequest($dom) { + + $httpDepth = $this->server->getHTTPDepth(0); + if ($httpDepth!==0) { + throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); + } + + $searchProperties = array(); + + $applyToPrincipalCollectionSet = false; + + // Parsing the search request + foreach($dom->firstChild->childNodes as $searchNode) { + + if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) == '{DAV:}apply-to-principal-collection-set') { + $applyToPrincipalCollectionSet = true; + } + + if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode)!=='{DAV:}property-search') + continue; + + $propertyName = null; + $propertyValue = null; + + foreach($searchNode->childNodes as $childNode) { + + switch(Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { + + case '{DAV:}prop' : + $property = Sabre_DAV_XMLUtil::parseProperties($searchNode); + reset($property); + $propertyName = key($property); + break; + + case '{DAV:}match' : + $propertyValue = $childNode->textContent; + break; + + } + + + } + + if (is_null($propertyName) || is_null($propertyValue)) + throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: ' . $propertyName . '. propertvvalue: ' . $propertyValue); + + $searchProperties[$propertyName] = $propertyValue; + + } + + return array($searchProperties, array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)), $applyToPrincipalCollectionSet); + + } + + + /* }}} */ + +} diff --git a/3rdparty/Sabre/DAVACL/Principal.php b/3rdparty/Sabre/DAVACL/Principal.php new file mode 100755 index 00000000000..51c6658afd6 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Principal.php @@ -0,0 +1,279 @@ +principalBackend = $principalBackend; + $this->principalProperties = $principalProperties; + + } + + /** + * Returns the full principal url + * + * @return string + */ + public function getPrincipalUrl() { + + return $this->principalProperties['uri']; + + } + + /** + * Returns a list of alternative urls for a principal + * + * This can for example be an email address, or ldap url. + * + * @return array + */ + public function getAlternateUriSet() { + + $uris = array(); + if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { + + $uris = $this->principalProperties['{DAV:}alternate-URI-set']; + + } + + if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { + $uris[] = 'mailto:' . $this->principalProperties['{http://sabredav.org/ns}email-address']; + } + + return array_unique($uris); + + } + + /** + * Returns the list of group members + * + * If this principal is a group, this function should return + * all member principal uri's for the group. + * + * @return array + */ + public function getGroupMemberSet() { + + return $this->principalBackend->getGroupMemberSet($this->principalProperties['uri']); + + } + + /** + * Returns the list of groups this principal is member of + * + * If this principal is a member of a (list of) groups, this function + * should return a list of principal uri's for it's members. + * + * @return array + */ + public function getGroupMembership() { + + return $this->principalBackend->getGroupMemberShip($this->principalProperties['uri']); + + } + + + /** + * Sets a list of group members + * + * If this principal is a group, this method sets all the group members. + * The list of members is always overwritten, never appended to. + * + * This method should throw an exception if the members could not be set. + * + * @param array $groupMembers + * @return void + */ + public function setGroupMemberSet(array $groupMembers) { + + $this->principalBackend->setGroupMemberSet($this->principalProperties['uri'], $groupMembers); + + } + + + /** + * Returns this principals name. + * + * @return string + */ + public function getName() { + + $uri = $this->principalProperties['uri']; + list(, $name) = Sabre_DAV_URLUtil::splitPath($uri); + return $name; + + } + + /** + * Returns the name of the user + * + * @return string + */ + public function getDisplayName() { + + if (isset($this->principalProperties['{DAV:}displayname'])) { + return $this->principalProperties['{DAV:}displayname']; + } else { + return $this->getName(); + } + + } + + /** + * Returns a list of properties + * + * @param array $requestedProperties + * @return array + */ + public function getProperties($requestedProperties) { + + $newProperties = array(); + foreach($requestedProperties as $propName) { + + if (isset($this->principalProperties[$propName])) { + $newProperties[$propName] = $this->principalProperties[$propName]; + } + + } + + return $newProperties; + + } + + /** + * Updates this principals properties. + * + * @param array $mutations + * @see Sabre_DAV_IProperties::updateProperties + * @return bool|array + */ + public function updateProperties($mutations) { + + return $this->principalBackend->updatePrincipal($this->principalProperties['uri'], $mutations); + + } + + /** + * Returns the owner principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() { + + return $this->principalProperties['uri']; + + + } + + /** + * Returns a group principal + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() { + + return null; + + } + + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() { + + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->getPrincipalUrl(), + 'protected' => true, + ), + ); + + } + + /** + * Updates the ACL + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * @return void + */ + public function setACL(array $acl) { + + throw new Sabre_DAV_Exception_MethodNotAllowed('Updating ACLs is not allowed here'); + + } + + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() { + + return null; + + } + +} diff --git a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php b/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php new file mode 100755 index 00000000000..a76b4a9d727 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php @@ -0,0 +1,427 @@ + array( + 'dbField' => 'displayname', + ), + + /** + * This property is actually used by the CardDAV plugin, where it gets + * mapped to {http://calendarserver.orgi/ns/}me-card. + * + * The reason we don't straight-up use that property, is because + * me-card is defined as a property on the users' addressbook + * collection. + */ + '{http://sabredav.org/ns}vcard-url' => array( + 'dbField' => 'vcardurl', + ), + /** + * This is the users' primary email-address. + */ + '{http://sabredav.org/ns}email-address' => array( + 'dbField' => 'email', + ), + ); + + /** + * Sets up the backend. + * + * @param PDO $pdo + * @param string $tableName + * @param string $groupMembersTableName + */ + public function __construct(PDO $pdo, $tableName = 'principals', $groupMembersTableName = 'groupmembers') { + + $this->pdo = $pdo; + $this->tableName = $tableName; + $this->groupMembersTableName = $groupMembersTableName; + + } + + + /** + * Returns a list of principals based on a prefix. + * + * This prefix will often contain something like 'principals'. You are only + * expected to return principals that are in this base path. + * + * You are expected to return at least a 'uri' for every user, you can + * return any additional properties if you wish so. Common properties are: + * {DAV:}displayname + * {http://sabredav.org/ns}email-address - This is a custom SabreDAV + * field that's actualy injected in a number of other properties. If + * you have an email address, use this property. + * + * @param string $prefixPath + * @return array + */ + public function getPrincipalsByPrefix($prefixPath) { + + $fields = array( + 'uri', + ); + + foreach($this->fieldMap as $key=>$value) { + $fields[] = $value['dbField']; + } + $result = $this->pdo->query('SELECT '.implode(',', $fields).' FROM '. $this->tableName); + + $principals = array(); + + while($row = $result->fetch(PDO::FETCH_ASSOC)) { + + // Checking if the principal is in the prefix + list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); + if ($rowPrefix !== $prefixPath) continue; + + $principal = array( + 'uri' => $row['uri'], + ); + foreach($this->fieldMap as $key=>$value) { + if ($row[$value['dbField']]) { + $principal[$key] = $row[$value['dbField']]; + } + } + $principals[] = $principal; + + } + + return $principals; + + } + + /** + * Returns a specific principal, specified by it's path. + * The returned structure should be the exact same as from + * getPrincipalsByPrefix. + * + * @param string $path + * @return array + */ + public function getPrincipalByPath($path) { + + $fields = array( + 'id', + 'uri', + ); + + foreach($this->fieldMap as $key=>$value) { + $fields[] = $value['dbField']; + } + $stmt = $this->pdo->prepare('SELECT '.implode(',', $fields).' FROM '. $this->tableName . ' WHERE uri = ?'); + $stmt->execute(array($path)); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$row) return; + + $principal = array( + 'id' => $row['id'], + 'uri' => $row['uri'], + ); + foreach($this->fieldMap as $key=>$value) { + if ($row[$value['dbField']]) { + $principal[$key] = $row[$value['dbField']]; + } + } + return $principal; + + } + + /** + * Updates one ore more webdav properties on a principal. + * + * The list of mutations is supplied as an array. Each key in the array is + * a propertyname, such as {DAV:}displayname. + * + * Each value is the actual value to be updated. If a value is null, it + * must be deleted. + * + * This method should be atomic. It must either completely succeed, or + * completely fail. Success and failure can simply be returned as 'true' or + * 'false'. + * + * It is also possible to return detailed failure information. In that case + * an array such as this should be returned: + * + * array( + * 200 => array( + * '{DAV:}prop1' => null, + * ), + * 201 => array( + * '{DAV:}prop2' => null, + * ), + * 403 => array( + * '{DAV:}prop3' => null, + * ), + * 424 => array( + * '{DAV:}prop4' => null, + * ), + * ); + * + * In this previous example prop1 was successfully updated or deleted, and + * prop2 was succesfully created. + * + * prop3 failed to update due to '403 Forbidden' and because of this prop4 + * also could not be updated with '424 Failed dependency'. + * + * This last example was actually incorrect. While 200 and 201 could appear + * in 1 response, if there's any error (403) the other properties should + * always fail with 423 (failed dependency). + * + * But anyway, if you don't want to scratch your head over this, just + * return true or false. + * + * @param string $path + * @param array $mutations + * @return array|bool + */ + public function updatePrincipal($path, $mutations) { + + $updateAble = array(); + foreach($mutations as $key=>$value) { + + // We are not aware of this field, we must fail. + if (!isset($this->fieldMap[$key])) { + + $response = array( + 403 => array( + $key => null, + ), + 424 => array(), + ); + + // Adding the rest to the response as a 424 + foreach($mutations as $subKey=>$subValue) { + if ($subKey !== $key) { + $response[424][$subKey] = null; + } + } + return $response; + } + + $updateAble[$this->fieldMap[$key]['dbField']] = $value; + + } + + // No fields to update + $query = "UPDATE " . $this->tableName . " SET "; + + $first = true; + foreach($updateAble as $key => $value) { + if (!$first) { + $query.= ', '; + } + $first = false; + $query.= "$key = :$key "; + } + $query.='WHERE uri = :uri'; + $stmt = $this->pdo->prepare($query); + $updateAble['uri'] = $path; + $stmt->execute($updateAble); + + return true; + + } + + /** + * This method is used to search for principals matching a set of + * properties. + * + * This search is specifically used by RFC3744's principal-property-search + * REPORT. You should at least allow searching on + * http://sabredav.org/ns}email-address. + * + * The actual search should be a unicode-non-case-sensitive search. The + * keys in searchProperties are the WebDAV property names, while the values + * are the property values to search on. + * + * If multiple properties are being searched on, the search should be + * AND'ed. + * + * This method should simply return an array with full principal uri's. + * + * If somebody attempted to search on a property the backend does not + * support, you should simply return 0 results. + * + * You can also just return 0 results if you choose to not support + * searching at all, but keep in mind that this may stop certain features + * from working. + * + * @param string $prefixPath + * @param array $searchProperties + * @return array + */ + public function searchPrincipals($prefixPath, array $searchProperties) { + + $query = 'SELECT uri FROM ' . $this->tableName . ' WHERE 1=1 '; + $values = array(); + foreach($searchProperties as $property => $value) { + + switch($property) { + + case '{DAV:}displayname' : + $query.=' AND displayname LIKE ?'; + $values[] = '%' . $value . '%'; + break; + case '{http://sabredav.org/ns}email-address' : + $query.=' AND email LIKE ?'; + $values[] = '%' . $value . '%'; + break; + default : + // Unsupported property + return array(); + + } + + } + $stmt = $this->pdo->prepare($query); + $stmt->execute($values); + + $principals = array(); + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + + // Checking if the principal is in the prefix + list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); + if ($rowPrefix !== $prefixPath) continue; + + $principals[] = $row['uri']; + + } + + return $principals; + + } + + /** + * Returns the list of members for a group-principal + * + * @param string $principal + * @return array + */ + public function getGroupMemberSet($principal) { + + $principal = $this->getPrincipalByPath($principal); + if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); + + $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM '.$this->groupMembersTableName.' AS groupmembers LEFT JOIN '.$this->tableName.' AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?'); + $stmt->execute(array($principal['id'])); + + $result = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $result[] = $row['uri']; + } + return $result; + + } + + /** + * Returns the list of groups a principal is a member of + * + * @param string $principal + * @return array + */ + public function getGroupMembership($principal) { + + $principal = $this->getPrincipalByPath($principal); + if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); + + $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM '.$this->groupMembersTableName.' AS groupmembers LEFT JOIN '.$this->tableName.' AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?'); + $stmt->execute(array($principal['id'])); + + $result = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $result[] = $row['uri']; + } + return $result; + + } + + /** + * Updates the list of group members for a group principal. + * + * The principals should be passed as a list of uri's. + * + * @param string $principal + * @param array $members + * @return void + */ + public function setGroupMemberSet($principal, array $members) { + + // Grabbing the list of principal id's. + $stmt = $this->pdo->prepare('SELECT id, uri FROM '.$this->tableName.' WHERE uri IN (? ' . str_repeat(', ? ', count($members)) . ');'); + $stmt->execute(array_merge(array($principal), $members)); + + $memberIds = array(); + $principalId = null; + + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row['uri'] == $principal) { + $principalId = $row['id']; + } else { + $memberIds[] = $row['id']; + } + } + if (!$principalId) throw new Sabre_DAV_Exception('Principal not found'); + + // Wiping out old members + $stmt = $this->pdo->prepare('DELETE FROM '.$this->groupMembersTableName.' WHERE principal_id = ?;'); + $stmt->execute(array($principalId)); + + foreach($memberIds as $memberId) { + + $stmt = $this->pdo->prepare('INSERT INTO '.$this->groupMembersTableName.' (principal_id, member_id) VALUES (?, ?);'); + $stmt->execute(array($principalId, $memberId)); + + } + + } + +} diff --git a/3rdparty/Sabre/DAVACL/PrincipalCollection.php b/3rdparty/Sabre/DAVACL/PrincipalCollection.php new file mode 100755 index 00000000000..c3e4cb83f23 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/PrincipalCollection.php @@ -0,0 +1,35 @@ +principalBackend, $principal); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Property/Acl.php b/3rdparty/Sabre/DAVACL/Property/Acl.php new file mode 100755 index 00000000000..05e1a690b3c --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Property/Acl.php @@ -0,0 +1,209 @@ +privileges = $privileges; + $this->prefixBaseUrl = $prefixBaseUrl; + + } + + /** + * Returns the list of privileges for this property + * + * @return array + */ + public function getPrivileges() { + + return $this->privileges; + + } + + /** + * Serializes the property into a DOMElement + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $node) { + + $doc = $node->ownerDocument; + foreach($this->privileges as $ace) { + + $this->serializeAce($doc, $node, $ace, $server); + + } + + } + + /** + * Unserializes the {DAV:}acl xml element. + * + * @param DOMElement $dom + * @return Sabre_DAVACL_Property_Acl + */ + static public function unserialize(DOMElement $dom) { + + $privileges = array(); + $xaces = $dom->getElementsByTagNameNS('urn:DAV','ace'); + for($ii=0; $ii < $xaces->length; $ii++) { + + $xace = $xaces->item($ii); + $principal = $xace->getElementsByTagNameNS('urn:DAV','principal'); + if ($principal->length !== 1) { + throw new Sabre_DAV_Exception_BadRequest('Each {DAV:}ace element must have one {DAV:}principal element'); + } + $principal = Sabre_DAVACL_Property_Principal::unserialize($principal->item(0)); + + switch($principal->getType()) { + case Sabre_DAVACL_Property_Principal::HREF : + $principal = $principal->getHref(); + break; + case Sabre_DAVACL_Property_Principal::AUTHENTICATED : + $principal = '{DAV:}authenticated'; + break; + case Sabre_DAVACL_Property_Principal::UNAUTHENTICATED : + $principal = '{DAV:}unauthenticated'; + break; + case Sabre_DAVACL_Property_Principal::ALL : + $principal = '{DAV:}all'; + break; + + } + + $protected = false; + + if ($xace->getElementsByTagNameNS('urn:DAV','protected')->length > 0) { + $protected = true; + } + + $grants = $xace->getElementsByTagNameNS('urn:DAV','grant'); + if ($grants->length < 1) { + throw new Sabre_DAV_Exception_NotImplemented('Every {DAV:}ace element must have a {DAV:}grant element. {DAV:}deny is not yet supported'); + } + $grant = $grants->item(0); + + $xprivs = $grant->getElementsByTagNameNS('urn:DAV','privilege'); + for($jj=0; $jj<$xprivs->length; $jj++) { + + $xpriv = $xprivs->item($jj); + + $privilegeName = null; + + for ($kk=0;$kk<$xpriv->childNodes->length;$kk++) { + + $childNode = $xpriv->childNodes->item($kk); + if ($t = Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { + $privilegeName = $t; + break; + } + } + if (is_null($privilegeName)) { + throw new Sabre_DAV_Exception_BadRequest('{DAV:}privilege elements must have a privilege element contained within them.'); + } + + $privileges[] = array( + 'principal' => $principal, + 'protected' => $protected, + 'privilege' => $privilegeName, + ); + + } + + } + + return new self($privileges); + + } + + /** + * Serializes a single access control entry. + * + * @param DOMDocument $doc + * @param DOMElement $node + * @param array $ace + * @param Sabre_DAV_Server $server + * @return void + */ + private function serializeAce($doc,$node,$ace, $server) { + + $xace = $doc->createElementNS('DAV:','d:ace'); + $node->appendChild($xace); + + $principal = $doc->createElementNS('DAV:','d:principal'); + $xace->appendChild($principal); + switch($ace['principal']) { + case '{DAV:}authenticated' : + $principal->appendChild($doc->createElementNS('DAV:','d:authenticated')); + break; + case '{DAV:}unauthenticated' : + $principal->appendChild($doc->createElementNS('DAV:','d:unauthenticated')); + break; + case '{DAV:}all' : + $principal->appendChild($doc->createElementNS('DAV:','d:all')); + break; + default: + $principal->appendChild($doc->createElementNS('DAV:','d:href',($this->prefixBaseUrl?$server->getBaseUri():'') . $ace['principal'] . '/')); + } + + $grant = $doc->createElementNS('DAV:','d:grant'); + $xace->appendChild($grant); + + $privParts = null; + + preg_match('/^{([^}]*)}(.*)$/',$ace['privilege'],$privParts); + + $xprivilege = $doc->createElementNS('DAV:','d:privilege'); + $grant->appendChild($xprivilege); + + $xprivilege->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + + if (isset($ace['protected']) && $ace['protected']) + $xace->appendChild($doc->createElement('d:protected')); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Property/AclRestrictions.php b/3rdparty/Sabre/DAVACL/Property/AclRestrictions.php new file mode 100755 index 00000000000..a8b054956dd --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Property/AclRestrictions.php @@ -0,0 +1,32 @@ +ownerDocument; + + $elem->appendChild($doc->createElementNS('DAV:','d:grant-only')); + $elem->appendChild($doc->createElementNS('DAV:','d:no-invert')); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php new file mode 100755 index 00000000000..94a29640615 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php @@ -0,0 +1,75 @@ +privileges = $privileges; + + } + + /** + * Serializes the property in the DOM + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $node) { + + $doc = $node->ownerDocument; + foreach($this->privileges as $privName) { + + $this->serializePriv($doc,$node,$privName); + + } + + } + + /** + * Serializes one privilege + * + * @param DOMDocument $doc + * @param DOMElement $node + * @param string $privName + * @return void + */ + protected function serializePriv($doc,$node,$privName) { + + $xp = $doc->createElementNS('DAV:','d:privilege'); + $node->appendChild($xp); + + $privParts = null; + preg_match('/^{([^}]*)}(.*)$/',$privName,$privParts); + + $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Property/Principal.php b/3rdparty/Sabre/DAVACL/Property/Principal.php new file mode 100755 index 00000000000..c36328a58e0 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Property/Principal.php @@ -0,0 +1,160 @@ +type = $type; + + if ($type===self::HREF && is_null($href)) { + throw new Sabre_DAV_Exception('The href argument must be specified for the HREF principal type.'); + } + $this->href = $href; + + } + + /** + * Returns the principal type + * + * @return int + */ + public function getType() { + + return $this->type; + + } + + /** + * Returns the principal uri. + * + * @return string + */ + public function getHref() { + + return $this->href; + + } + + /** + * Serializes the property into a DOMElement. + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server, DOMElement $node) { + + $prefix = $server->xmlNamespaces['DAV:']; + switch($this->type) { + + case self::UNAUTHENTICATED : + $node->appendChild( + $node->ownerDocument->createElement($prefix . ':unauthenticated') + ); + break; + case self::AUTHENTICATED : + $node->appendChild( + $node->ownerDocument->createElement($prefix . ':authenticated') + ); + break; + case self::HREF : + $href = $node->ownerDocument->createElement($prefix . ':href'); + $href->nodeValue = $server->getBaseUri() . $this->href; + $node->appendChild($href); + break; + + } + + } + + /** + * Deserializes a DOM element into a property object. + * + * @param DOMElement $dom + * @return Sabre_DAV_Property_Principal + */ + static public function unserialize(DOMElement $dom) { + + $parent = $dom->firstChild; + while(!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { + $parent = $parent->nextSibling; + } + + switch(Sabre_DAV_XMLUtil::toClarkNotation($parent)) { + + case '{DAV:}unauthenticated' : + return new self(self::UNAUTHENTICATED); + case '{DAV:}authenticated' : + return new self(self::AUTHENTICATED); + case '{DAV:}href': + return new self(self::HREF, $parent->textContent); + case '{DAV:}all': + return new self(self::ALL); + default : + throw new Sabre_DAV_Exception_BadRequest('Unexpected element (' . Sabre_DAV_XMLUtil::toClarkNotation($parent) . '). Could not deserialize'); + + } + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php new file mode 100755 index 00000000000..276d57ae093 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php @@ -0,0 +1,92 @@ +privileges = $privileges; + + } + + /** + * Serializes the property into a domdocument. + * + * @param Sabre_DAV_Server $server + * @param DOMElement $node + * @return void + */ + public function serialize(Sabre_DAV_Server $server,DOMElement $node) { + + $doc = $node->ownerDocument; + $this->serializePriv($doc, $node, $this->privileges); + + } + + /** + * Serializes a property + * + * This is a recursive function. + * + * @param DOMDocument $doc + * @param DOMElement $node + * @param array $privilege + * @return void + */ + private function serializePriv($doc,$node,$privilege) { + + $xsp = $doc->createElementNS('DAV:','d:supported-privilege'); + $node->appendChild($xsp); + + $xp = $doc->createElementNS('DAV:','d:privilege'); + $xsp->appendChild($xp); + + $privParts = null; + preg_match('/^{([^}]*)}(.*)$/',$privilege['privilege'],$privParts); + + $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + + if (isset($privilege['abstract']) && $privilege['abstract']) { + $xsp->appendChild($doc->createElementNS('DAV:','d:abstract')); + } + + if (isset($privilege['description'])) { + $xsp->appendChild($doc->createElementNS('DAV:','d:description',$privilege['description'])); + } + + if (isset($privilege['aggregates'])) { + foreach($privilege['aggregates'] as $subPrivilege) { + $this->serializePriv($doc,$xsp,$subPrivilege); + } + } + + } + +} diff --git a/3rdparty/Sabre/DAVACL/Version.php b/3rdparty/Sabre/DAVACL/Version.php new file mode 100755 index 00000000000..9950f748741 --- /dev/null +++ b/3rdparty/Sabre/DAVACL/Version.php @@ -0,0 +1,24 @@ +httpRequest->getHeader('Authorization'); + $authHeader = explode(' ',$authHeader); + + if ($authHeader[0]!='AWS' || !isset($authHeader[1])) { + $this->errorCode = self::ERR_NOAWSHEADER; + return false; + } + + list($this->accessKey,$this->signature) = explode(':',$authHeader[1]); + + return true; + + } + + /** + * Returns the username for the request + * + * @return string + */ + public function getAccessKey() { + + return $this->accessKey; + + } + + /** + * Validates the signature based on the secretKey + * + * @param string $secretKey + * @return bool + */ + public function validate($secretKey) { + + $contentMD5 = $this->httpRequest->getHeader('Content-MD5'); + + if ($contentMD5) { + // We need to validate the integrity of the request + $body = $this->httpRequest->getBody(true); + $this->httpRequest->setBody($body,true); + + if ($contentMD5!=base64_encode(md5($body,true))) { + // content-md5 header did not match md5 signature of body + $this->errorCode = self::ERR_MD5CHECKSUMWRONG; + return false; + } + + } + + if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) + $requestDate = $this->httpRequest->getHeader('Date'); + + if (!$this->validateRFC2616Date($requestDate)) + return false; + + $amzHeaders = $this->getAmzHeaders(); + + $signature = base64_encode( + $this->hmacsha1($secretKey, + $this->httpRequest->getMethod() . "\n" . + $contentMD5 . "\n" . + $this->httpRequest->getHeader('Content-type') . "\n" . + $requestDate . "\n" . + $amzHeaders . + $this->httpRequest->getURI() + ) + ); + + if ($this->signature != $signature) { + + $this->errorCode = self::ERR_INVALIDSIGNATURE; + return false; + + } + + return true; + + } + + + /** + * Returns an HTTP 401 header, forcing login + * + * This should be called when username and password are incorrect, or not supplied at all + * + * @return void + */ + public function requireLogin() { + + $this->httpResponse->setHeader('WWW-Authenticate','AWS'); + $this->httpResponse->sendStatus(401); + + } + + /** + * Makes sure the supplied value is a valid RFC2616 date. + * + * If we would just use strtotime to get a valid timestamp, we have no way of checking if a + * user just supplied the word 'now' for the date header. + * + * This function also makes sure the Date header is within 15 minutes of the operating + * system date, to prevent replay attacks. + * + * @param string $dateHeader + * @return bool + */ + protected function validateRFC2616Date($dateHeader) { + + $date = Sabre_HTTP_Util::parseHTTPDate($dateHeader); + + // Unknown format + if (!$date) { + $this->errorCode = self::ERR_INVALIDDATEFORMAT; + return false; + } + + $min = new DateTime('-15 minutes'); + $max = new DateTime('+15 minutes'); + + // We allow 15 minutes around the current date/time + if ($date > $max || $date < $min) { + $this->errorCode = self::ERR_REQUESTTIMESKEWED; + return false; + } + + return $date; + + } + + /** + * Returns a list of AMZ headers + * + * @return string + */ + protected function getAmzHeaders() { + + $amzHeaders = array(); + $headers = $this->httpRequest->getHeaders(); + foreach($headers as $headerName => $headerValue) { + if (strpos(strtolower($headerName),'x-amz-')===0) { + $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"),array(' '),$headerValue) . "\n"; + } + } + ksort($amzHeaders); + + $headerStr = ''; + foreach($amzHeaders as $h=>$v) { + $headerStr.=$h.':'.$v; + } + + return $headerStr; + + } + + /** + * Generates an HMAC-SHA1 signature + * + * @param string $key + * @param string $message + * @return string + */ + private function hmacsha1($key, $message) { + + $blocksize=64; + if (strlen($key)>$blocksize) + $key=pack('H*', sha1($key)); + $key=str_pad($key,$blocksize,chr(0x00)); + $ipad=str_repeat(chr(0x36),$blocksize); + $opad=str_repeat(chr(0x5c),$blocksize); + $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); + return $hmac; + + } + +} diff --git a/3rdparty/Sabre/HTTP/AbstractAuth.php b/3rdparty/Sabre/HTTP/AbstractAuth.php new file mode 100755 index 00000000000..3bccabcd1c1 --- /dev/null +++ b/3rdparty/Sabre/HTTP/AbstractAuth.php @@ -0,0 +1,111 @@ +httpResponse = new Sabre_HTTP_Response(); + $this->httpRequest = new Sabre_HTTP_Request(); + + } + + /** + * Sets an alternative HTTP response object + * + * @param Sabre_HTTP_Response $response + * @return void + */ + public function setHTTPResponse(Sabre_HTTP_Response $response) { + + $this->httpResponse = $response; + + } + + /** + * Sets an alternative HTTP request object + * + * @param Sabre_HTTP_Request $request + * @return void + */ + public function setHTTPRequest(Sabre_HTTP_Request $request) { + + $this->httpRequest = $request; + + } + + + /** + * Sets the realm + * + * The realm is often displayed in authentication dialog boxes + * Commonly an application name displayed here + * + * @param string $realm + * @return void + */ + public function setRealm($realm) { + + $this->realm = $realm; + + } + + /** + * Returns the realm + * + * @return string + */ + public function getRealm() { + + return $this->realm; + + } + + /** + * Returns an HTTP 401 header, forcing login + * + * This should be called when username and password are incorrect, or not supplied at all + * + * @return void + */ + abstract public function requireLogin(); + +} diff --git a/3rdparty/Sabre/HTTP/BasicAuth.php b/3rdparty/Sabre/HTTP/BasicAuth.php new file mode 100755 index 00000000000..a747cc6a31b --- /dev/null +++ b/3rdparty/Sabre/HTTP/BasicAuth.php @@ -0,0 +1,67 @@ +httpRequest->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->httpRequest->getRawServerValue('PHP_AUTH_PW'))) { + + return array($user,$pass); + + } + + // Most other webservers + $auth = $this->httpRequest->getHeader('Authorization'); + + // Apache could prefix environment variables with REDIRECT_ when urls + // are passed through mod_rewrite + if (!$auth) { + $auth = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION'); + } + + if (!$auth) return false; + + if (strpos(strtolower($auth),'basic')!==0) return false; + + return explode(':', base64_decode(substr($auth, 6))); + + } + + /** + * Returns an HTTP 401 header, forcing login + * + * This should be called when username and password are incorrect, or not supplied at all + * + * @return void + */ + public function requireLogin() { + + $this->httpResponse->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); + $this->httpResponse->sendStatus(401); + + } + +} diff --git a/3rdparty/Sabre/HTTP/DigestAuth.php b/3rdparty/Sabre/HTTP/DigestAuth.php new file mode 100755 index 00000000000..ee7f05c08ed --- /dev/null +++ b/3rdparty/Sabre/HTTP/DigestAuth.php @@ -0,0 +1,240 @@ +nonce = uniqid(); + $this->opaque = md5($this->realm); + parent::__construct(); + + } + + /** + * Gathers all information from the headers + * + * This method needs to be called prior to anything else. + * + * @return void + */ + public function init() { + + $digest = $this->getDigest(); + $this->digestParts = $this->parseDigest($digest); + + } + + /** + * Sets the quality of protection value. + * + * Possible values are: + * Sabre_HTTP_DigestAuth::QOP_AUTH + * Sabre_HTTP_DigestAuth::QOP_AUTHINT + * + * Multiple values can be specified using logical OR. + * + * QOP_AUTHINT ensures integrity of the request body, but this is not + * supported by most HTTP clients. QOP_AUTHINT also requires the entire + * request body to be md5'ed, which can put strains on CPU and memory. + * + * @param int $qop + * @return void + */ + public function setQOP($qop) { + + $this->qop = $qop; + + } + + /** + * Validates the user. + * + * The A1 parameter should be md5($username . ':' . $realm . ':' . $password); + * + * @param string $A1 + * @return bool + */ + public function validateA1($A1) { + + $this->A1 = $A1; + return $this->validate(); + + } + + /** + * Validates authentication through a password. The actual password must be provided here. + * It is strongly recommended not store the password in plain-text and use validateA1 instead. + * + * @param string $password + * @return bool + */ + public function validatePassword($password) { + + $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password); + return $this->validate(); + + } + + /** + * Returns the username for the request + * + * @return string + */ + public function getUsername() { + + return $this->digestParts['username']; + + } + + /** + * Validates the digest challenge + * + * @return bool + */ + protected function validate() { + + $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri']; + + if ($this->digestParts['qop']=='auth-int') { + // Making sure we support this qop value + if (!($this->qop & self::QOP_AUTHINT)) return false; + // We need to add an md5 of the entire request body to the A2 part of the hash + $body = $this->httpRequest->getBody(true); + $this->httpRequest->setBody($body,true); + $A2 .= ':' . md5($body); + } else { + + // We need to make sure we support this qop value + if (!($this->qop & self::QOP_AUTH)) return false; + } + + $A2 = md5($A2); + + $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}"); + + return $this->digestParts['response']==$validResponse; + + + } + + /** + * Returns an HTTP 401 header, forcing login + * + * This should be called when username and password are incorrect, or not supplied at all + * + * @return void + */ + public function requireLogin() { + + $qop = ''; + switch($this->qop) { + case self::QOP_AUTH : $qop = 'auth'; break; + case self::QOP_AUTHINT : $qop = 'auth-int'; break; + case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break; + } + + $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"'); + $this->httpResponse->sendStatus(401); + + } + + + /** + * This method returns the full digest string. + * + * It should be compatibile with mod_php format and other webservers. + * + * If the header could not be found, null will be returned + * + * @return mixed + */ + public function getDigest() { + + // mod_php + $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST'); + if ($digest) return $digest; + + // most other servers + $digest = $this->httpRequest->getHeader('Authorization'); + + // Apache could prefix environment variables with REDIRECT_ when urls + // are passed through mod_rewrite + if (!$digest) { + $digest = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION'); + } + + if ($digest && strpos(strtolower($digest),'digest')===0) { + return substr($digest,7); + } else { + return null; + } + + } + + + /** + * Parses the different pieces of the digest string into an array. + * + * This method returns false if an incomplete digest was supplied + * + * @param string $digest + * @return mixed + */ + protected function parseDigest($digest) { + + // protect against missing data + $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); + $data = array(); + + preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER); + + foreach ($matches as $m) { + $data[$m[1]] = $m[2] ? $m[2] : $m[3]; + unset($needed_parts[$m[1]]); + } + + return $needed_parts ? false : $data; + + } + +} diff --git a/3rdparty/Sabre/HTTP/Request.php b/3rdparty/Sabre/HTTP/Request.php new file mode 100755 index 00000000000..4746ef77704 --- /dev/null +++ b/3rdparty/Sabre/HTTP/Request.php @@ -0,0 +1,268 @@ +_SERVER = $serverData; + else $this->_SERVER =& $_SERVER; + + if ($postData) $this->_POST = $postData; + else $this->_POST =& $_POST; + + } + + /** + * Returns the value for a specific http header. + * + * This method returns null if the header did not exist. + * + * @param string $name + * @return string + */ + public function getHeader($name) { + + $name = strtoupper(str_replace(array('-'),array('_'),$name)); + if (isset($this->_SERVER['HTTP_' . $name])) { + return $this->_SERVER['HTTP_' . $name]; + } + + // There's a few headers that seem to end up in the top-level + // server array. + switch($name) { + case 'CONTENT_TYPE' : + case 'CONTENT_LENGTH' : + if (isset($this->_SERVER[$name])) { + return $this->_SERVER[$name]; + } + break; + + } + return; + + } + + /** + * Returns all (known) HTTP headers. + * + * All headers are converted to lower-case, and additionally all underscores + * are automatically converted to dashes + * + * @return array + */ + public function getHeaders() { + + $hdrs = array(); + foreach($this->_SERVER as $key=>$value) { + + switch($key) { + case 'CONTENT_LENGTH' : + case 'CONTENT_TYPE' : + $hdrs[strtolower(str_replace('_','-',$key))] = $value; + break; + default : + if (strpos($key,'HTTP_')===0) { + $hdrs[substr(strtolower(str_replace('_','-',$key)),5)] = $value; + } + break; + } + + } + + return $hdrs; + + } + + /** + * Returns the HTTP request method + * + * This is for example POST or GET + * + * @return string + */ + public function getMethod() { + + return $this->_SERVER['REQUEST_METHOD']; + + } + + /** + * Returns the requested uri + * + * @return string + */ + public function getUri() { + + return $this->_SERVER['REQUEST_URI']; + + } + + /** + * Will return protocol + the hostname + the uri + * + * @return string + */ + public function getAbsoluteUri() { + + // Checking if the request was made through HTTPS. The last in line is for IIS + $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']!='off'); + return ($protocol?'https':'http') . '://' . $this->getHeader('Host') . $this->getUri(); + + } + + /** + * Returns everything after the ? from the current url + * + * @return string + */ + public function getQueryString() { + + return isset($this->_SERVER['QUERY_STRING'])?$this->_SERVER['QUERY_STRING']:''; + + } + + /** + * Returns the HTTP request body body + * + * This method returns a readable stream resource. + * If the asString parameter is set to true, a string is sent instead. + * + * @param bool asString + * @return resource + */ + public function getBody($asString = false) { + + if (is_null($this->body)) { + if (!is_null(self::$defaultInputStream)) { + $this->body = self::$defaultInputStream; + } else { + $this->body = fopen('php://input','r'); + self::$defaultInputStream = $this->body; + } + } + if ($asString) { + $body = stream_get_contents($this->body); + return $body; + } else { + return $this->body; + } + + } + + /** + * Sets the contents of the HTTP request body + * + * This method can either accept a string, or a readable stream resource. + * + * If the setAsDefaultInputStream is set to true, it means for this run of the + * script the supplied body will be used instead of php://input. + * + * @param mixed $body + * @param bool $setAsDefaultInputStream + * @return void + */ + public function setBody($body,$setAsDefaultInputStream = false) { + + if(is_resource($body)) { + $this->body = $body; + } else { + + $stream = fopen('php://temp','r+'); + fputs($stream,$body); + rewind($stream); + // String is assumed + $this->body = $stream; + } + if ($setAsDefaultInputStream) { + self::$defaultInputStream = $this->body; + } + + } + + /** + * Returns PHP's _POST variable. + * + * The reason this is in a method is so it can be subclassed and + * overridden. + * + * @return array + */ + public function getPostVars() { + + return $this->_POST; + + } + + /** + * Returns a specific item from the _SERVER array. + * + * Do not rely on this feature, it is for internal use only. + * + * @param string $field + * @return string + */ + public function getRawServerValue($field) { + + return isset($this->_SERVER[$field])?$this->_SERVER[$field]:null; + + } + +} + diff --git a/3rdparty/Sabre/HTTP/Response.php b/3rdparty/Sabre/HTTP/Response.php new file mode 100755 index 00000000000..ffe9bda2082 --- /dev/null +++ b/3rdparty/Sabre/HTTP/Response.php @@ -0,0 +1,157 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authorative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', // RFC 4918 + 208 => 'Already Reported', // RFC 5842 + 226 => 'IM Used', // RFC 3229 + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Reserved', + 307 => 'Temporary Redirect', + 400 => 'Bad request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', // RFC 2324 + 422 => 'Unprocessable Entity', // RFC 4918 + 423 => 'Locked', // RFC 4918 + 424 => 'Failed Dependency', // RFC 4918 + 426 => 'Upgrade required', + 428 => 'Precondition required', // draft-nottingham-http-new-status + 429 => 'Too Many Requests', // draft-nottingham-http-new-status + 431 => 'Request Header Fields Too Large', // draft-nottingham-http-new-status + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', // RFC 4918 + 508 => 'Loop Detected', // RFC 5842 + 509 => 'Bandwidth Limit Exceeded', // non-standard + 510 => 'Not extended', + 511 => 'Network Authentication Required', // draft-nottingham-http-new-status + ); + + return 'HTTP/1.1 ' . $code . ' ' . $msg[$code]; + + } + + /** + * Sends an HTTP status header to the client + * + * @param int $code HTTP status code + * @return bool + */ + public function sendStatus($code) { + + if (!headers_sent()) + return header($this->getStatusMessage($code)); + else return false; + + } + + /** + * Sets an HTTP header for the response + * + * @param string $name + * @param string $value + * @param bool $replace + * @return bool + */ + public function setHeader($name, $value, $replace = true) { + + $value = str_replace(array("\r","\n"),array('\r','\n'),$value); + if (!headers_sent()) + return header($name . ': ' . $value, $replace); + else return false; + + } + + /** + * Sets a bunch of HTTP Headers + * + * headersnames are specified as keys, value in the array value + * + * @param array $headers + * @return void + */ + public function setHeaders(array $headers) { + + foreach($headers as $key=>$value) + $this->setHeader($key, $value); + + } + + /** + * Sends the entire response body + * + * This method can accept either an open filestream, or a string. + * + * @param mixed $body + * @return void + */ + public function sendBody($body) { + + if (is_resource($body)) { + + fpassthru($body); + + } else { + + // We assume a string + echo $body; + + } + + } + +} diff --git a/3rdparty/Sabre/HTTP/Util.php b/3rdparty/Sabre/HTTP/Util.php new file mode 100755 index 00000000000..67bdd489e1e --- /dev/null +++ b/3rdparty/Sabre/HTTP/Util.php @@ -0,0 +1,82 @@ += 0) + return new DateTime('@' . $realDate, new DateTimeZone('UTC')); + + } + + /** + * Transforms a DateTime object to HTTP's most common date format. + * + * We're serializing it as the RFC 1123 date, which, for HTTP must be + * specified as GMT. + * + * @param DateTime $dateTime + * @return string + */ + static function toHTTPDate(DateTime $dateTime) { + + // We need to clone it, as we don't want to affect the existing + // DateTime. + $dateTime = clone $dateTime; + $dateTime->setTimeZone(new DateTimeZone('GMT')); + return $dateTime->format('D, d M Y H:i:s \G\M\T'); + + } + +} diff --git a/3rdparty/Sabre/HTTP/Version.php b/3rdparty/Sabre/HTTP/Version.php new file mode 100755 index 00000000000..23dc7f8a7a1 --- /dev/null +++ b/3rdparty/Sabre/HTTP/Version.php @@ -0,0 +1,24 @@ + 'Sabre_VObject_Component_VCalendar', + 'VEVENT' => 'Sabre_VObject_Component_VEvent', + 'VTODO' => 'Sabre_VObject_Component_VTodo', + 'VJOURNAL' => 'Sabre_VObject_Component_VJournal', + 'VALARM' => 'Sabre_VObject_Component_VAlarm', + ); + + /** + * Creates the new component by name, but in addition will also see if + * there's a class mapped to the property name. + * + * @param string $name + * @param string $value + * @return Sabre_VObject_Component + */ + static public function create($name, $value = null) { + + $name = strtoupper($name); + + if (isset(self::$classMap[$name])) { + return new self::$classMap[$name]($name, $value); + } else { + return new self($name, $value); + } + + } + + /** + * Creates a new component. + * + * By default this object will iterate over its own children, but this can + * be overridden with the iterator argument + * + * @param string $name + * @param Sabre_VObject_ElementList $iterator + */ + public function __construct($name, Sabre_VObject_ElementList $iterator = null) { + + $this->name = strtoupper($name); + if (!is_null($iterator)) $this->iterator = $iterator; + + } + + /** + * Turns the object back into a serialized blob. + * + * @return string + */ + public function serialize() { + + $str = "BEGIN:" . $this->name . "\r\n"; + + /** + * Gives a component a 'score' for sorting purposes. + * + * This is solely used by the childrenSort method. + * + * A higher score means the item will be higher in the list + * + * @param Sabre_VObject_Node $n + * @return int + */ + $sortScore = function($n) { + + if ($n instanceof Sabre_VObject_Component) { + // We want to encode VTIMEZONE first, this is a personal + // preference. + if ($n->name === 'VTIMEZONE') { + return 1; + } else { + return 0; + } + } else { + // VCARD version 4.0 wants the VERSION property to appear first + if ($n->name === 'VERSION') { + return 3; + } else { + return 2; + } + } + + }; + + usort($this->children, function($a, $b) use ($sortScore) { + + $sA = $sortScore($a); + $sB = $sortScore($b); + + if ($sA === $sB) return 0; + + return ($sA > $sB) ? -1 : 1; + + }); + + foreach($this->children as $child) $str.=$child->serialize(); + $str.= "END:" . $this->name . "\r\n"; + + return $str; + + } + + /** + * Adds a new component or element + * + * You can call this method with the following syntaxes: + * + * add(Sabre_VObject_Element $element) + * add(string $name, $value) + * + * The first version adds an Element + * The second adds a property as a string. + * + * @param mixed $item + * @param mixed $itemValue + * @return void + */ + public function add($item, $itemValue = null) { + + if ($item instanceof Sabre_VObject_Element) { + if (!is_null($itemValue)) { + throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); + } + $item->parent = $this; + $this->children[] = $item; + } elseif(is_string($item)) { + + if (!is_scalar($itemValue)) { + throw new InvalidArgumentException('The second argument must be scalar'); + } + $item = Sabre_VObject_Property::create($item,$itemValue); + $item->parent = $this; + $this->children[] = $item; + + } else { + + throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); + + } + + } + + /** + * Returns an iterable list of children + * + * @return Sabre_VObject_ElementList + */ + public function children() { + + return new Sabre_VObject_ElementList($this->children); + + } + + /** + * Returns an array with elements that match the specified name. + * + * This function is also aware of MIME-Directory groups (as they appear in + * vcards). This means that if a property is grouped as "HOME.EMAIL", it + * will also be returned when searching for just "EMAIL". If you want to + * search for a property in a specific group, you can select on the entire + * string ("HOME.EMAIL"). If you want to search on a specific property that + * has not been assigned a group, specify ".EMAIL". + * + * Keys are retained from the 'children' array, which may be confusing in + * certain cases. + * + * @param string $name + * @return array + */ + public function select($name) { + + $group = null; + $name = strtoupper($name); + if (strpos($name,'.')!==false) { + list($group,$name) = explode('.', $name, 2); + } + + $result = array(); + foreach($this->children as $key=>$child) { + + if ( + strtoupper($child->name) === $name && + (is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group)) + ) { + + $result[$key] = $child; + + } + } + + reset($result); + return $result; + + } + + /** + * This method only returns a list of sub-components. Properties are + * ignored. + * + * @return array + */ + public function getComponents() { + + $result = array(); + foreach($this->children as $child) { + if ($child instanceof Sabre_VObject_Component) { + $result[] = $child; + } + } + + return $result; + + } + + /* Magic property accessors {{{ */ + + /** + * Using 'get' you will either get a property or component, + * + * If there were no child-elements found with the specified name, + * null is returned. + * + * @param string $name + * @return Sabre_VObject_Property + */ + public function __get($name) { + + $matches = $this->select($name); + if (count($matches)===0) { + return null; + } else { + $firstMatch = current($matches); + /** @var $firstMatch Sabre_VObject_Property */ + $firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches))); + return $firstMatch; + } + + } + + /** + * This method checks if a sub-element with the specified name exists. + * + * @param string $name + * @return bool + */ + public function __isset($name) { + + $matches = $this->select($name); + return count($matches)>0; + + } + + /** + * Using the setter method you can add properties or subcomponents + * + * You can either pass a Sabre_VObject_Component, Sabre_VObject_Property + * object, or a string to automatically create a Property. + * + * If the item already exists, it will be removed. If you want to add + * a new item with the same name, always use the add() method. + * + * @param string $name + * @param mixed $value + * @return void + */ + public function __set($name, $value) { + + $matches = $this->select($name); + $overWrite = count($matches)?key($matches):null; + + if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) { + $value->parent = $this; + if (!is_null($overWrite)) { + $this->children[$overWrite] = $value; + } else { + $this->children[] = $value; + } + } elseif (is_scalar($value)) { + $property = Sabre_VObject_Property::create($name,$value); + $property->parent = $this; + if (!is_null($overWrite)) { + $this->children[$overWrite] = $property; + } else { + $this->children[] = $property; + } + } else { + throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type'); + } + + } + + /** + * Removes all properties and components within this component. + * + * @param string $name + * @return void + */ + public function __unset($name) { + + $matches = $this->select($name); + foreach($matches as $k=>$child) { + + unset($this->children[$k]); + $child->parent = null; + + } + + } + + /* }}} */ + + /** + * This method is automatically called when the object is cloned. + * Specifically, this will ensure all child elements are also cloned. + * + * @return void + */ + public function __clone() { + + foreach($this->children as $key=>$child) { + $this->children[$key] = clone $child; + $this->children[$key]->parent = $this; + } + + } + +} diff --git a/3rdparty/Sabre/VObject/Component/VAlarm.php b/3rdparty/Sabre/VObject/Component/VAlarm.php new file mode 100755 index 00000000000..ebb4a9b18f6 --- /dev/null +++ b/3rdparty/Sabre/VObject/Component/VAlarm.php @@ -0,0 +1,102 @@ +TRIGGER; + if(!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') { + $triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($this->TRIGGER); + $related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START'; + + $parentComponent = $this->parent; + if ($related === 'START') { + $effectiveTrigger = clone $parentComponent->DTSTART->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } else { + if ($parentComponent->name === 'VTODO') { + $endProp = 'DUE'; + } elseif ($parentComponent->name === 'VEVENT') { + $endProp = 'DTEND'; + } else { + throw new Sabre_DAV_Exception('time-range filters on VALARM components are only supported when they are a child of VTODO or VEVENT'); + } + + if (isset($parentComponent->$endProp)) { + $effectiveTrigger = clone $parentComponent->$endProp->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } elseif (isset($parentComponent->DURATION)) { + $effectiveTrigger = clone $parentComponent->DTSTART->getDateTime(); + $duration = Sabre_VObject_DateTimeParser::parseDuration($parentComponent->DURATION); + $effectiveTrigger->add($duration); + $effectiveTrigger->add($triggerDuration); + } else { + $effectiveTrigger = clone $parentComponent->DTSTART->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } + } + } else { + $effectiveTrigger = $trigger->getDateTime(); + } + return $effectiveTrigger; + + } + + /** + * Returns true or false depending on if the event falls in the specified + * time-range. This is used for filtering purposes. + * + * The rules used to determine if an event falls within the specified + * time-range is based on the CalDAV specification. + * + * @param DateTime $start + * @param DateTime $end + * @return bool + */ + public function isInTimeRange(DateTime $start, DateTime $end) { + + $effectiveTrigger = $this->getEffectiveTriggerTime(); + + if (isset($this->DURATION)) { + $duration = Sabre_VObject_DateTimeParser::parseDuration($this->DURATION); + $repeat = (string)$this->repeat; + if (!$repeat) { + $repeat = 1; + } + + $period = new DatePeriod($effectiveTrigger, $duration, (int)$repeat); + + foreach($period as $occurrence) { + + if ($start <= $occurrence && $end > $occurrence) { + return true; + } + } + return false; + } else { + return ($start <= $effectiveTrigger && $end > $effectiveTrigger); + } + + } + +} + +?> diff --git a/3rdparty/Sabre/VObject/Component/VCalendar.php b/3rdparty/Sabre/VObject/Component/VCalendar.php new file mode 100755 index 00000000000..f3be29afdbb --- /dev/null +++ b/3rdparty/Sabre/VObject/Component/VCalendar.php @@ -0,0 +1,133 @@ +children as $component) { + + if (!$component instanceof Sabre_VObject_Component) + continue; + + if (isset($component->{'RECURRENCE-ID'})) + continue; + + if ($componentName && $component->name !== strtoupper($componentName)) + continue; + + if ($component->name === 'VTIMEZONE') + continue; + + $components[] = $component; + + } + + return $components; + + } + + /** + * If this calendar object, has events with recurrence rules, this method + * can be used to expand the event into multiple sub-events. + * + * Each event will be stripped from it's recurrence information, and only + * the instances of the event in the specified timerange will be left + * alone. + * + * In addition, this method will cause timezone information to be stripped, + * and normalized to UTC. + * + * This method will alter the VCalendar. This cannot be reversed. + * + * This functionality is specifically used by the CalDAV standard. It is + * possible for clients to request expand events, if they are rather simple + * clients and do not have the possibility to calculate recurrences. + * + * @param DateTime $start + * @param DateTime $end + * @return void + */ + public function expand(DateTime $start, DateTime $end) { + + $newEvents = array(); + + foreach($this->select('VEVENT') as $key=>$vevent) { + + if (isset($vevent->{'RECURRENCE-ID'})) { + unset($this->children[$key]); + continue; + } + + + if (!$vevent->rrule) { + unset($this->children[$key]); + if ($vevent->isInTimeRange($start, $end)) { + $newEvents[] = $vevent; + } + continue; + } + + $uid = (string)$vevent->uid; + if (!$uid) { + throw new LogicException('Event did not have a UID!'); + } + + $it = new Sabre_VObject_RecurrenceIterator($this, $vevent->uid); + $it->fastForward($start); + + while($it->valid() && $it->getDTStart() < $end) { + + if ($it->getDTEnd() > $start) { + + $newEvents[] = $it->getEventObject(); + + } + $it->next(); + + } + unset($this->children[$key]); + + } + + foreach($newEvents as $newEvent) { + + foreach($newEvent->children as $child) { + if ($child instanceof Sabre_VObject_Property_DateTime && + $child->getDateType() == Sabre_VObject_Property_DateTime::LOCALTZ) { + $child->setDateTime($child->getDateTime(),Sabre_VObject_Property_DateTime::UTC); + } + } + + $this->add($newEvent); + + } + + // Removing all VTIMEZONE components + unset($this->VTIMEZONE); + + } + +} + diff --git a/3rdparty/Sabre/VObject/Component/VEvent.php b/3rdparty/Sabre/VObject/Component/VEvent.php new file mode 100755 index 00000000000..4cc1e36d7d6 --- /dev/null +++ b/3rdparty/Sabre/VObject/Component/VEvent.php @@ -0,0 +1,70 @@ +RRULE) { + $it = new Sabre_VObject_RecurrenceIterator($this); + $it->fastForward($start); + + // We fast-forwarded to a spot where the end-time of the + // recurrence instance exceeded the start of the requested + // time-range. + // + // If the starttime of the recurrence did not exceed the + // end of the time range as well, we have a match. + return ($it->getDTStart() < $end && $it->getDTEnd() > $start); + + } + + $effectiveStart = $this->DTSTART->getDateTime(); + if (isset($this->DTEND)) { + $effectiveEnd = $this->DTEND->getDateTime(); + // If this was an all-day event, we should just increase the + // end-date by 1. Otherwise the event will last until the second + // the date changed, by increasing this by 1 day the event lasts + // all of the last day as well. + if ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) { + $effectiveEnd->modify('+1 day'); + } + } elseif (isset($this->DURATION)) { + $effectiveEnd = clone $effectiveStart; + $effectiveEnd->add( Sabre_VObject_DateTimeParser::parseDuration($this->DURATION) ); + } elseif ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) { + $effectiveEnd = clone $effectiveStart; + $effectiveEnd->modify('+1 day'); + } else { + $effectiveEnd = clone $effectiveStart; + } + return ( + ($start <= $effectiveEnd) && ($end > $effectiveStart) + ); + + } + +} + +?> diff --git a/3rdparty/Sabre/VObject/Component/VJournal.php b/3rdparty/Sabre/VObject/Component/VJournal.php new file mode 100755 index 00000000000..22b3ec921e5 --- /dev/null +++ b/3rdparty/Sabre/VObject/Component/VJournal.php @@ -0,0 +1,46 @@ +DTSTART)?$this->DTSTART->getDateTime():null; + if ($dtstart) { + $effectiveEnd = clone $dtstart; + if ($this->DTSTART->getDateType() == Sabre_VObject_Element_DateTime::DATE) { + $effectiveEnd->modify('+1 day'); + } + + return ($start <= $effectiveEnd && $end > $dtstart); + + } + return false; + + + } + +} + +?> diff --git a/3rdparty/Sabre/VObject/Component/VTodo.php b/3rdparty/Sabre/VObject/Component/VTodo.php new file mode 100755 index 00000000000..79d06298d7f --- /dev/null +++ b/3rdparty/Sabre/VObject/Component/VTodo.php @@ -0,0 +1,68 @@ +DTSTART)?$this->DTSTART->getDateTime():null; + $duration = isset($this->DURATION)?Sabre_VObject_DateTimeParser::parseDuration($this->DURATION):null; + $due = isset($this->DUE)?$this->DUE->getDateTime():null; + $completed = isset($this->COMPLETED)?$this->COMPLETED->getDateTime():null; + $created = isset($this->CREATED)?$this->CREATED->getDateTime():null; + + if ($dtstart) { + if ($duration) { + $effectiveEnd = clone $dtstart; + $effectiveEnd->add($duration); + return $start <= $effectiveEnd && $end > $dtstart; + } elseif ($due) { + return + ($start < $due || $start <= $dtstart) && + ($end > $dtstart || $end >= $due); + } else { + return $start <= $dtstart && $end > $dtstart; + } + } + if ($due) { + return ($start < $due && $end >= $due); + } + if ($completed && $created) { + return + ($start <= $created || $start <= $completed) && + ($end >= $created || $end >= $completed); + } + if ($completed) { + return ($start <= $completed && $end >= $completed); + } + if ($created) { + return ($end > $created); + } + return true; + + } + +} + +?> diff --git a/3rdparty/Sabre/VObject/DateTimeParser.php b/3rdparty/Sabre/VObject/DateTimeParser.php new file mode 100755 index 00000000000..1e2d54ef3a9 --- /dev/null +++ b/3rdparty/Sabre/VObject/DateTimeParser.php @@ -0,0 +1,177 @@ +setTimeZone(new DateTimeZone('UTC')); + return $date; + + } + + /** + * Parses an iCalendar (rfc5545) formatted date and returns a DateTime object + * + * @param string $date + * @return DateTime + */ + static public function parseDate($date) { + + // Format is YYYYMMDD + $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches); + + if (!$result) { + throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar date value is incorrect: ' . $date); + } + + $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC')); + return $date; + + } + + /** + * Parses an iCalendar (RFC5545) formatted duration value. + * + * This method will either return a DateTimeInterval object, or a string + * suitable for strtotime or DateTime::modify. + * + * @param string $duration + * @param bool $asString + * @return DateInterval|string + */ + static public function parseDuration($duration, $asString = false) { + + $result = preg_match('/^(?P\+|-)?P((?P\d+)W)?((?P\d+)D)?(T((?P\d+)H)?((?P\d+)M)?((?P\d+)S)?)?$/', $duration, $matches); + if (!$result) { + throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar duration value is incorrect: ' . $duration); + } + + if (!$asString) { + $invert = false; + if ($matches['plusminus']==='-') { + $invert = true; + } + + + $parts = array( + 'week', + 'day', + 'hour', + 'minute', + 'second', + ); + foreach($parts as $part) { + $matches[$part] = isset($matches[$part])&&$matches[$part]?(int)$matches[$part]:0; + } + + + // We need to re-construct the $duration string, because weeks and + // days are not supported by DateInterval in the same string. + $duration = 'P'; + $days = $matches['day']; + if ($matches['week']) { + $days+=$matches['week']*7; + } + if ($days) + $duration.=$days . 'D'; + + if ($matches['minute'] || $matches['second'] || $matches['hour']) { + $duration.='T'; + + if ($matches['hour']) + $duration.=$matches['hour'].'H'; + + if ($matches['minute']) + $duration.=$matches['minute'].'M'; + + if ($matches['second']) + $duration.=$matches['second'].'S'; + + } + + $iv = new DateInterval($duration); + if ($invert) $iv->invert = true; + + return $iv; + + } + + + + $parts = array( + 'week', + 'day', + 'hour', + 'minute', + 'second', + ); + + $newDur = ''; + foreach($parts as $part) { + if (isset($matches[$part]) && $matches[$part]) { + $newDur.=' '.$matches[$part] . ' ' . $part . 's'; + } + } + + $newDur = ($matches['plusminus']==='-'?'-':'+') . trim($newDur); + return $newDur; + + } + + /** + * Parses either a Date or DateTime, or Duration value. + * + * @param string $date + * @param DateTimeZone|string $referenceTZ + * @return DateTime|DateInterval + */ + static public function parse($date, $referenceTZ = null) { + + if ($date[0]==='P' || ($date[0]==='-' && $date[1]==='P')) { + return self::parseDuration($date); + } elseif (strlen($date)===8) { + return self::parseDate($date); + } else { + return self::parseDateTime($date, $referenceTZ); + } + + } + + +} diff --git a/3rdparty/Sabre/VObject/Element.php b/3rdparty/Sabre/VObject/Element.php new file mode 100755 index 00000000000..e20ff0b353c --- /dev/null +++ b/3rdparty/Sabre/VObject/Element.php @@ -0,0 +1,16 @@ +vevent where there's multiple VEVENT objects. + * + * @package Sabre + * @subpackage VObject + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License + */ +class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess { + + /** + * Inner elements + * + * @var array + */ + protected $elements = array(); + + /** + * Creates the element list. + * + * @param array $elements + */ + public function __construct(array $elements) { + + $this->elements = $elements; + + } + + /* {{{ Iterator interface */ + + /** + * Current position + * + * @var int + */ + private $key = 0; + + /** + * Returns current item in iteration + * + * @return Sabre_VObject_Element + */ + public function current() { + + return $this->elements[$this->key]; + + } + + /** + * To the next item in the iterator + * + * @return void + */ + public function next() { + + $this->key++; + + } + + /** + * Returns the current iterator key + * + * @return int + */ + public function key() { + + return $this->key; + + } + + /** + * Returns true if the current position in the iterator is a valid one + * + * @return bool + */ + public function valid() { + + return isset($this->elements[$this->key]); + + } + + /** + * Rewinds the iterator + * + * @return void + */ + public function rewind() { + + $this->key = 0; + + } + + /* }}} */ + + /* {{{ Countable interface */ + + /** + * Returns the number of elements + * + * @return int + */ + public function count() { + + return count($this->elements); + + } + + /* }}} */ + + /* {{{ ArrayAccess Interface */ + + + /** + * Checks if an item exists through ArrayAccess. + * + * @param int $offset + * @return bool + */ + public function offsetExists($offset) { + + return isset($this->elements[$offset]); + + } + + /** + * Gets an item through ArrayAccess. + * + * @param int $offset + * @return mixed + */ + public function offsetGet($offset) { + + return $this->elements[$offset]; + + } + + /** + * Sets an item through ArrayAccess. + * + * @param int $offset + * @param mixed $value + * @return void + */ + public function offsetSet($offset,$value) { + + throw new LogicException('You can not add new objects to an ElementList'); + + } + + /** + * Sets an item through ArrayAccess. + * + * This method just forwards the request to the inner iterator + * + * @param int $offset + * @return void + */ + public function offsetUnset($offset) { + + throw new LogicException('You can not remove objects from an ElementList'); + + } + + /* }}} */ + +} diff --git a/3rdparty/Sabre/VObject/FreeBusyGenerator.php b/3rdparty/Sabre/VObject/FreeBusyGenerator.php new file mode 100755 index 00000000000..1c96a64a004 --- /dev/null +++ b/3rdparty/Sabre/VObject/FreeBusyGenerator.php @@ -0,0 +1,297 @@ +baseObject = $vcalendar; + + } + + /** + * Sets the input objects + * + * Every object must either be a string or a Sabre_VObject_Component. + * + * @param array $objects + * @return void + */ + public function setObjects(array $objects) { + + $this->objects = array(); + foreach($objects as $object) { + + if (is_string($object)) { + $this->objects[] = Sabre_VObject_Reader::read($object); + } elseif ($object instanceof Sabre_VObject_Component) { + $this->objects[] = $object; + } else { + throw new InvalidArgumentException('You can only pass strings or Sabre_VObject_Component arguments to setObjects'); + } + + } + + } + + /** + * Sets the time range + * + * Any freebusy object falling outside of this time range will be ignored. + * + * @param DateTime $start + * @param DateTime $end + * @return void + */ + public function setTimeRange(DateTime $start = null, DateTime $end = null) { + + $this->start = $start; + $this->end = $end; + + } + + /** + * Parses the input data and returns a correct VFREEBUSY object, wrapped in + * a VCALENDAR. + * + * @return Sabre_VObject_Component + */ + public function getResult() { + + $busyTimes = array(); + + foreach($this->objects as $object) { + + foreach($object->getBaseComponents() as $component) { + + switch($component->name) { + + case 'VEVENT' : + + $FBTYPE = 'BUSY'; + if (isset($component->TRANSP) && (strtoupper($component->TRANSP) === 'TRANSPARENT')) { + break; + } + if (isset($component->STATUS)) { + $status = strtoupper($component->STATUS); + if ($status==='CANCELLED') { + break; + } + if ($status==='TENTATIVE') { + $FBTYPE = 'BUSY-TENTATIVE'; + } + } + + $times = array(); + + if ($component->RRULE) { + + $iterator = new Sabre_VObject_RecurrenceIterator($object, (string)$component->uid); + if ($this->start) { + $iterator->fastForward($this->start); + } + + $maxRecurrences = 200; + + while($iterator->valid() && --$maxRecurrences) { + + $startTime = $iterator->getDTStart(); + if ($this->end && $startTime > $this->end) { + break; + } + $times[] = array( + $iterator->getDTStart(), + $iterator->getDTEnd(), + ); + + $iterator->next(); + + } + + } else { + + $startTime = $component->DTSTART->getDateTime(); + if ($this->end && $startTime > $this->end) { + break; + } + $endTime = null; + if (isset($component->DTEND)) { + $endTime = $component->DTEND->getDateTime(); + } elseif (isset($component->DURATION)) { + $duration = Sabre_VObject_DateTimeParser::parseDuration((string)$component->DURATION); + $endTime = clone $startTime; + $endTime->add($duration); + } elseif ($component->DTSTART->getDateType() === Sabre_VObject_Property_DateTime::DATE) { + $endTime = clone $startTime; + $endTime->modify('+1 day'); + } else { + // The event had no duration (0 seconds) + break; + } + + $times[] = array($startTime, $endTime); + + } + + foreach($times as $time) { + + if ($this->end && $time[0] > $this->end) break; + if ($this->start && $time[1] < $this->start) break; + + $busyTimes[] = array( + $time[0], + $time[1], + $FBTYPE, + ); + } + break; + + case 'VFREEBUSY' : + foreach($component->FREEBUSY as $freebusy) { + + $fbType = isset($freebusy['FBTYPE'])?strtoupper($freebusy['FBTYPE']):'BUSY'; + + // Skipping intervals marked as 'free' + if ($fbType==='FREE') + continue; + + $values = explode(',', $freebusy); + foreach($values as $value) { + list($startTime, $endTime) = explode('/', $value); + $startTime = Sabre_VObject_DateTimeParser::parseDateTime($startTime); + + if (substr($endTime,0,1)==='P' || substr($endTime,0,2)==='-P') { + $duration = Sabre_VObject_DateTimeParser::parseDuration($endTime); + $endTime = clone $startTime; + $endTime->add($duration); + } else { + $endTime = Sabre_VObject_DateTimeParser::parseDateTime($endTime); + } + + if($this->start && $this->start > $endTime) continue; + if($this->end && $this->end < $startTime) continue; + $busyTimes[] = array( + $startTime, + $endTime, + $fbType + ); + + } + + + } + break; + + + + } + + + } + + } + + if ($this->baseObject) { + $calendar = $this->baseObject; + } else { + $calendar = new Sabre_VObject_Component('VCALENDAR'); + $calendar->version = '2.0'; + if (Sabre_DAV_Server::$exposeVersion) { + $calendar->prodid = '-//SabreDAV//Sabre VObject ' . Sabre_VObject_Version::VERSION . '//EN'; + } else { + $calendar->prodid = '-//SabreDAV//Sabre VObject//EN'; + } + $calendar->calscale = 'GREGORIAN'; + } + + $vfreebusy = new Sabre_VObject_Component('VFREEBUSY'); + $calendar->add($vfreebusy); + + if ($this->start) { + $dtstart = new Sabre_VObject_Property_DateTime('DTSTART'); + $dtstart->setDateTime($this->start,Sabre_VObject_Property_DateTime::UTC); + $vfreebusy->add($dtstart); + } + if ($this->end) { + $dtend = new Sabre_VObject_Property_DateTime('DTEND'); + $dtend->setDateTime($this->start,Sabre_VObject_Property_DateTime::UTC); + $vfreebusy->add($dtend); + } + $dtstamp = new Sabre_VObject_Property_DateTime('DTSTAMP'); + $dtstamp->setDateTime(new DateTime('now'), Sabre_VObject_Property_DateTime::UTC); + $vfreebusy->add($dtstamp); + + foreach($busyTimes as $busyTime) { + + $busyTime[0]->setTimeZone(new DateTimeZone('UTC')); + $busyTime[1]->setTimeZone(new DateTimeZone('UTC')); + + $prop = new Sabre_VObject_Property( + 'FREEBUSY', + $busyTime[0]->format('Ymd\\THis\\Z') . '/' . $busyTime[1]->format('Ymd\\THis\\Z') + ); + $prop['FBTYPE'] = $busyTime[2]; + $vfreebusy->add($prop); + + } + + return $calendar; + + } + +} + diff --git a/3rdparty/Sabre/VObject/Node.php b/3rdparty/Sabre/VObject/Node.php new file mode 100755 index 00000000000..d89e01b56c6 --- /dev/null +++ b/3rdparty/Sabre/VObject/Node.php @@ -0,0 +1,149 @@ +iterator)) + return $this->iterator; + + return new Sabre_VObject_ElementList(array($this)); + + } + + /** + * Sets the overridden iterator + * + * Note that this is not actually part of the iterator interface + * + * @param Sabre_VObject_ElementList $iterator + * @return void + */ + public function setIterator(Sabre_VObject_ElementList $iterator) { + + $this->iterator = $iterator; + + } + + /* }}} */ + + /* {{{ Countable interface */ + + /** + * Returns the number of elements + * + * @return int + */ + public function count() { + + $it = $this->getIterator(); + return $it->count(); + + } + + /* }}} */ + + /* {{{ ArrayAccess Interface */ + + + /** + * Checks if an item exists through ArrayAccess. + * + * This method just forwards the request to the inner iterator + * + * @param int $offset + * @return bool + */ + public function offsetExists($offset) { + + $iterator = $this->getIterator(); + return $iterator->offsetExists($offset); + + } + + /** + * Gets an item through ArrayAccess. + * + * This method just forwards the request to the inner iterator + * + * @param int $offset + * @return mixed + */ + public function offsetGet($offset) { + + $iterator = $this->getIterator(); + return $iterator->offsetGet($offset); + + } + + /** + * Sets an item through ArrayAccess. + * + * This method just forwards the request to the inner iterator + * + * @param int $offset + * @param mixed $value + * @return void + */ + public function offsetSet($offset,$value) { + + $iterator = $this->getIterator(); + return $iterator->offsetSet($offset,$value); + + } + + /** + * Sets an item through ArrayAccess. + * + * This method just forwards the request to the inner iterator + * + * @param int $offset + * @return void + */ + public function offsetUnset($offset) { + + $iterator = $this->getIterator(); + return $iterator->offsetUnset($offset); + + } + + /* }}} */ + +} diff --git a/3rdparty/Sabre/VObject/Parameter.php b/3rdparty/Sabre/VObject/Parameter.php new file mode 100755 index 00000000000..2e39af5f78a --- /dev/null +++ b/3rdparty/Sabre/VObject/Parameter.php @@ -0,0 +1,84 @@ +name = strtoupper($name); + $this->value = $value; + + } + + /** + * Turns the object back into a serialized blob. + * + * @return string + */ + public function serialize() { + + if (is_null($this->value)) { + return $this->name; + } + $src = array( + '\\', + "\n", + ';', + ',', + ); + $out = array( + '\\\\', + '\n', + '\;', + '\,', + ); + + return $this->name . '=' . str_replace($src, $out, $this->value); + + } + + /** + * Called when this object is being cast to a string + * + * @return string + */ + public function __toString() { + + return $this->value; + + } + +} diff --git a/3rdparty/Sabre/VObject/ParseException.php b/3rdparty/Sabre/VObject/ParseException.php new file mode 100755 index 00000000000..1b5e95bf16e --- /dev/null +++ b/3rdparty/Sabre/VObject/ParseException.php @@ -0,0 +1,12 @@ + 'Sabre_VObject_Property_DateTime', + 'CREATED' => 'Sabre_VObject_Property_DateTime', + 'DTEND' => 'Sabre_VObject_Property_DateTime', + 'DTSTAMP' => 'Sabre_VObject_Property_DateTime', + 'DTSTART' => 'Sabre_VObject_Property_DateTime', + 'DUE' => 'Sabre_VObject_Property_DateTime', + 'EXDATE' => 'Sabre_VObject_Property_MultiDateTime', + 'LAST-MODIFIED' => 'Sabre_VObject_Property_DateTime', + 'RECURRENCE-ID' => 'Sabre_VObject_Property_DateTime', + 'TRIGGER' => 'Sabre_VObject_Property_DateTime', + ); + + /** + * Creates the new property by name, but in addition will also see if + * there's a class mapped to the property name. + * + * @param string $name + * @param string $value + * @return void + */ + static public function create($name, $value = null) { + + $name = strtoupper($name); + $shortName = $name; + $group = null; + if (strpos($shortName,'.')!==false) { + list($group, $shortName) = explode('.', $shortName); + } + + if (isset(self::$classMap[$shortName])) { + return new self::$classMap[$shortName]($name, $value); + } else { + return new self($name, $value); + } + + } + + /** + * Creates a new property object + * + * By default this object will iterate over its own children, but this can + * be overridden with the iterator argument + * + * @param string $name + * @param string $value + * @param Sabre_VObject_ElementList $iterator + */ + public function __construct($name, $value = null, $iterator = null) { + + $name = strtoupper($name); + $group = null; + if (strpos($name,'.')!==false) { + list($group, $name) = explode('.', $name); + } + $this->name = $name; + $this->group = $group; + if (!is_null($iterator)) $this->iterator = $iterator; + $this->setValue($value); + + } + + + + /** + * Updates the internal value + * + * @param string $value + * @return void + */ + public function setValue($value) { + + $this->value = $value; + + } + + /** + * Turns the object back into a serialized blob. + * + * @return string + */ + public function serialize() { + + $str = $this->name; + if ($this->group) $str = $this->group . '.' . $this->name; + + if (count($this->parameters)) { + foreach($this->parameters as $param) { + + $str.=';' . $param->serialize(); + + } + } + $src = array( + '\\', + "\n", + ); + $out = array( + '\\\\', + '\n', + ); + $str.=':' . str_replace($src, $out, $this->value); + + $out = ''; + while(strlen($str)>0) { + if (strlen($str)>75) { + $out.= mb_strcut($str,0,75,'utf-8') . "\r\n"; + $str = ' ' . mb_strcut($str,75,strlen($str),'utf-8'); + } else { + $out.=$str . "\r\n"; + $str=''; + break; + } + } + + return $out; + + } + + /** + * Adds a new componenten or element + * + * You can call this method with the following syntaxes: + * + * add(Sabre_VObject_Parameter $element) + * add(string $name, $value) + * + * The first version adds an Parameter + * The second adds a property as a string. + * + * @param mixed $item + * @param mixed $itemValue + * @return void + */ + public function add($item, $itemValue = null) { + + if ($item instanceof Sabre_VObject_Parameter) { + if (!is_null($itemValue)) { + throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); + } + $item->parent = $this; + $this->parameters[] = $item; + } elseif(is_string($item)) { + + if (!is_scalar($itemValue) && !is_null($itemValue)) { + throw new InvalidArgumentException('The second argument must be scalar'); + } + $parameter = new Sabre_VObject_Parameter($item,$itemValue); + $parameter->parent = $this; + $this->parameters[] = $parameter; + + } else { + + throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); + + } + + } + + /* ArrayAccess interface {{{ */ + + /** + * Checks if an array element exists + * + * @param mixed $name + * @return bool + */ + public function offsetExists($name) { + + if (is_int($name)) return parent::offsetExists($name); + + $name = strtoupper($name); + + foreach($this->parameters as $parameter) { + if ($parameter->name == $name) return true; + } + return false; + + } + + /** + * Returns a parameter, or parameter list. + * + * @param string $name + * @return Sabre_VObject_Element + */ + public function offsetGet($name) { + + if (is_int($name)) return parent::offsetGet($name); + $name = strtoupper($name); + + $result = array(); + foreach($this->parameters as $parameter) { + if ($parameter->name == $name) + $result[] = $parameter; + } + + if (count($result)===0) { + return null; + } elseif (count($result)===1) { + return $result[0]; + } else { + $result[0]->setIterator(new Sabre_VObject_ElementList($result)); + return $result[0]; + } + + } + + /** + * Creates a new parameter + * + * @param string $name + * @param mixed $value + * @return void + */ + public function offsetSet($name, $value) { + + if (is_int($name)) return parent::offsetSet($name, $value); + + if (is_scalar($value)) { + if (!is_string($name)) + throw new InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.'); + + $this->offsetUnset($name); + $parameter = new Sabre_VObject_Parameter($name, $value); + $parameter->parent = $this; + $this->parameters[] = $parameter; + + } elseif ($value instanceof Sabre_VObject_Parameter) { + if (!is_null($name)) + throw new InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a Sabre_VObject_Parameter. Add using $array[]=$parameterObject.'); + + $value->parent = $this; + $this->parameters[] = $value; + } else { + throw new InvalidArgumentException('You can only add parameters to the property object'); + } + + } + + /** + * Removes one or more parameters with the specified name + * + * @param string $name + * @return void + */ + public function offsetUnset($name) { + + if (is_int($name)) return parent::offsetUnset($name); + $name = strtoupper($name); + + foreach($this->parameters as $key=>$parameter) { + if ($parameter->name == $name) { + $parameter->parent = null; + unset($this->parameters[$key]); + } + + } + + } + + /* }}} */ + + /** + * Called when this object is being cast to a string + * + * @return string + */ + public function __toString() { + + return (string)$this->value; + + } + + /** + * This method is automatically called when the object is cloned. + * Specifically, this will ensure all child elements are also cloned. + * + * @return void + */ + public function __clone() { + + foreach($this->parameters as $key=>$child) { + $this->parameters[$key] = clone $child; + $this->parameters[$key]->parent = $this; + } + + } + +} diff --git a/3rdparty/Sabre/VObject/Property/DateTime.php b/3rdparty/Sabre/VObject/Property/DateTime.php new file mode 100755 index 00000000000..fe2372caa81 --- /dev/null +++ b/3rdparty/Sabre/VObject/Property/DateTime.php @@ -0,0 +1,260 @@ +setValue($dt->format('Ymd\\THis')); + $this->offsetUnset('VALUE'); + $this->offsetUnset('TZID'); + $this->offsetSet('VALUE','DATE-TIME'); + break; + case self::UTC : + $dt->setTimeZone(new DateTimeZone('UTC')); + $this->setValue($dt->format('Ymd\\THis\\Z')); + $this->offsetUnset('VALUE'); + $this->offsetUnset('TZID'); + $this->offsetSet('VALUE','DATE-TIME'); + break; + case self::LOCALTZ : + $this->setValue($dt->format('Ymd\\THis')); + $this->offsetUnset('VALUE'); + $this->offsetUnset('TZID'); + $this->offsetSet('VALUE','DATE-TIME'); + $this->offsetSet('TZID', $dt->getTimeZone()->getName()); + break; + case self::DATE : + $this->setValue($dt->format('Ymd')); + $this->offsetUnset('VALUE'); + $this->offsetUnset('TZID'); + $this->offsetSet('VALUE','DATE'); + break; + default : + throw new InvalidArgumentException('You must pass a valid dateType constant'); + + } + $this->dateTime = $dt; + $this->dateType = $dateType; + + } + + /** + * Returns the current DateTime value. + * + * If no value was set, this method returns null. + * + * @return DateTime|null + */ + public function getDateTime() { + + if ($this->dateTime) + return $this->dateTime; + + list( + $this->dateType, + $this->dateTime + ) = self::parseData($this->value, $this); + return $this->dateTime; + + } + + /** + * Returns the type of Date format. + * + * This method returns one of the format constants. If no date was set, + * this method will return null. + * + * @return int|null + */ + public function getDateType() { + + if ($this->dateType) + return $this->dateType; + + list( + $this->dateType, + $this->dateTime, + ) = self::parseData($this->value, $this); + return $this->dateType; + + } + + /** + * Parses the internal data structure to figure out what the current date + * and time is. + * + * The returned array contains two elements: + * 1. A 'DateType' constant (as defined on this class), or null. + * 2. A DateTime object (or null) + * + * @param string|null $propertyValue The string to parse (yymmdd or + * ymmddThhmmss, etc..) + * @param Sabre_VObject_Property|null $property The instance of the + * property we're parsing. + * @return array + */ + static public function parseData($propertyValue, Sabre_VObject_Property $property = null) { + + if (is_null($propertyValue)) { + return array(null, null); + } + + $date = '(?P[1-2][0-9]{3})(?P[0-1][0-9])(?P[0-3][0-9])'; + $time = '(?P[0-2][0-9])(?P[0-5][0-9])(?P[0-5][0-9])'; + $regex = "/^$date(T$time(?PZ)?)?$/"; + + if (!preg_match($regex, $propertyValue, $matches)) { + throw new InvalidArgumentException($propertyValue . ' is not a valid DateTime or Date string'); + } + + if (!isset($matches['hour'])) { + // Date-only + return array( + self::DATE, + new DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00'), + ); + } + + $dateStr = + $matches['year'] .'-' . + $matches['month'] . '-' . + $matches['date'] . ' ' . + $matches['hour'] . ':' . + $matches['minute'] . ':' . + $matches['second']; + + if (isset($matches['isutc'])) { + $dt = new DateTime($dateStr,new DateTimeZone('UTC')); + $dt->setTimeZone(new DateTimeZone('UTC')); + return array( + self::UTC, + $dt + ); + } + + // Finding the timezone. + $tzid = $property['TZID']; + if (!$tzid) { + return array( + self::LOCAL, + new DateTime($dateStr) + ); + } + + try { + // tzid an Olson identifier? + $tz = new DateTimeZone($tzid->value); + } catch (Exception $e) { + + // Not an Olson id, we're going to try to find the information + // through the time zone name map. + $newtzid = Sabre_VObject_WindowsTimezoneMap::lookup($tzid->value); + if (is_null($newtzid)) { + + // Not a well known time zone name either, we're going to try + // to find the information through the VTIMEZONE object. + + // First we find the root object + $root = $property; + while($root->parent) { + $root = $root->parent; + } + + if (isset($root->VTIMEZONE)) { + foreach($root->VTIMEZONE as $vtimezone) { + if (((string)$vtimezone->TZID) == $tzid) { + if (isset($vtimezone->{'X-LIC-LOCATION'})) { + $newtzid = (string)$vtimezone->{'X-LIC-LOCATION'}; + } else { + // No libical location specified. As a last resort we could + // try matching $vtimezone's DST rules against all known + // time zones returned by DateTimeZone::list* + + // TODO + } + } + } + } + } + + try { + $tz = new DateTimeZone($newtzid); + } catch (Exception $e) { + // If all else fails, we use the default PHP timezone + $tz = new DateTimeZone(date_default_timezone_get()); + } + } + $dt = new DateTime($dateStr, $tz); + $dt->setTimeZone($tz); + + return array( + self::LOCALTZ, + $dt + ); + + } + +} diff --git a/3rdparty/Sabre/VObject/Property/MultiDateTime.php b/3rdparty/Sabre/VObject/Property/MultiDateTime.php new file mode 100755 index 00000000000..ae53ab6a617 --- /dev/null +++ b/3rdparty/Sabre/VObject/Property/MultiDateTime.php @@ -0,0 +1,166 @@ +offsetUnset('VALUE'); + $this->offsetUnset('TZID'); + switch($dateType) { + + case Sabre_VObject_Property_DateTime::LOCAL : + $val = array(); + foreach($dt as $i) { + $val[] = $i->format('Ymd\\THis'); + } + $this->setValue(implode(',',$val)); + $this->offsetSet('VALUE','DATE-TIME'); + break; + case Sabre_VObject_Property_DateTime::UTC : + $val = array(); + foreach($dt as $i) { + $i->setTimeZone(new DateTimeZone('UTC')); + $val[] = $i->format('Ymd\\THis\\Z'); + } + $this->setValue(implode(',',$val)); + $this->offsetSet('VALUE','DATE-TIME'); + break; + case Sabre_VObject_Property_DateTime::LOCALTZ : + $val = array(); + foreach($dt as $i) { + $val[] = $i->format('Ymd\\THis'); + } + $this->setValue(implode(',',$val)); + $this->offsetSet('VALUE','DATE-TIME'); + $this->offsetSet('TZID', $dt[0]->getTimeZone()->getName()); + break; + case Sabre_VObject_Property_DateTime::DATE : + $val = array(); + foreach($dt as $i) { + $val[] = $i->format('Ymd'); + } + $this->setValue(implode(',',$val)); + $this->offsetSet('VALUE','DATE'); + break; + default : + throw new InvalidArgumentException('You must pass a valid dateType constant'); + + } + $this->dateTimes = $dt; + $this->dateType = $dateType; + + } + + /** + * Returns the current DateTime value. + * + * If no value was set, this method returns null. + * + * @return array|null + */ + public function getDateTimes() { + + if ($this->dateTimes) + return $this->dateTimes; + + $dts = array(); + + if (!$this->value) { + $this->dateTimes = null; + $this->dateType = null; + return null; + } + + foreach(explode(',',$this->value) as $val) { + list( + $type, + $dt + ) = Sabre_VObject_Property_DateTime::parseData($val, $this); + $dts[] = $dt; + $this->dateType = $type; + } + $this->dateTimes = $dts; + return $this->dateTimes; + + } + + /** + * Returns the type of Date format. + * + * This method returns one of the format constants. If no date was set, + * this method will return null. + * + * @return int|null + */ + public function getDateType() { + + if ($this->dateType) + return $this->dateType; + + if (!$this->value) { + $this->dateTimes = null; + $this->dateType = null; + return null; + } + + $dts = array(); + foreach(explode(',',$this->value) as $val) { + list( + $type, + $dt + ) = Sabre_VObject_Property_DateTime::parseData($val, $this); + $dts[] = $dt; + $this->dateType = $type; + } + $this->dateTimes = $dts; + return $this->dateType; + + } + +} diff --git a/3rdparty/Sabre/VObject/Reader.php b/3rdparty/Sabre/VObject/Reader.php new file mode 100755 index 00000000000..eea73fa3dce --- /dev/null +++ b/3rdparty/Sabre/VObject/Reader.php @@ -0,0 +1,183 @@ +add(self::readLine($lines)); + + $nextLine = current($lines); + + if ($nextLine===false) + throw new Sabre_VObject_ParseException('Invalid VObject. Document ended prematurely.'); + + } + + // Checking component name of the 'END:' line. + if (substr($nextLine,4)!==$obj->name) { + throw new Sabre_VObject_ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"'); + } + next($lines); + + return $obj; + + } + + // Properties + //$result = preg_match('/(?P[A-Z0-9-]+)(?:;(?P^(?([^:^\"]|\"([^\"]*)\")*))?"; + $regex = "/^(?P$token)$parameters:(?P.*)$/i"; + + $result = preg_match($regex,$line,$matches); + + if (!$result) { + throw new Sabre_VObject_ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format'); + } + + $propertyName = strtoupper($matches['name']); + $propertyValue = preg_replace_callback('#(\\\\(\\\\|N|n|;|,))#',function($matches) { + if ($matches[2]==='n' || $matches[2]==='N') { + return "\n"; + } else { + return $matches[2]; + } + }, $matches['value']); + + $obj = Sabre_VObject_Property::create($propertyName, $propertyValue); + + if ($matches['parameters']) { + + foreach(self::readParameters($matches['parameters']) as $param) { + $obj->add($param); + } + + } + + return $obj; + + + } + + /** + * Reads a parameter list from a property + * + * This method returns an array of Sabre_VObject_Parameter + * + * @param string $parameters + * @return array + */ + static private function readParameters($parameters) { + + $token = '[A-Z0-9-]+'; + + $paramValue = '(?P[^\"^;]*|"[^"]*")'; + + $regex = "/(?<=^|;)(?P$token)(=$paramValue(?=$|;))?/i"; + preg_match_all($regex, $parameters, $matches, PREG_SET_ORDER); + + $params = array(); + foreach($matches as $match) { + + $value = isset($match['paramValue'])?$match['paramValue']:null; + + if (isset($value[0])) { + // Stripping quotes, if needed + if ($value[0] === '"') $value = substr($value,1,strlen($value)-2); + } else { + $value = ''; + } + + $value = preg_replace_callback('#(\\\\(\\\\|N|n|;|,))#',function($matches) { + if ($matches[2]==='n' || $matches[2]==='N') { + return "\n"; + } else { + return $matches[2]; + } + }, $value); + + $params[] = new Sabre_VObject_Parameter($match['paramName'], $value); + + } + + return $params; + + } + + +} diff --git a/3rdparty/Sabre/VObject/RecurrenceIterator.php b/3rdparty/Sabre/VObject/RecurrenceIterator.php new file mode 100755 index 00000000000..833aa091ab7 --- /dev/null +++ b/3rdparty/Sabre/VObject/RecurrenceIterator.php @@ -0,0 +1,1009 @@ + 0, + 'MO' => 1, + 'TU' => 2, + 'WE' => 3, + 'TH' => 4, + 'FR' => 5, + 'SA' => 6, + ); + + /** + * Mappings between the day number and english day name. + * + * @var array + */ + private $dayNames = array( + 0 => 'Sunday', + 1 => 'Monday', + 2 => 'Tuesday', + 3 => 'Wednesday', + 4 => 'Thursday', + 5 => 'Friday', + 6 => 'Saturday', + ); + + /** + * If the current iteration of the event is an overriden event, this + * property will hold the VObject + * + * @var Sabre_Component_VObject + */ + private $currentOverriddenEvent; + + /** + * This property may contain the date of the next not-overridden event. + * This date is calculated sometimes a bit early, before overridden events + * are evaluated. + * + * @var DateTime + */ + private $nextDate; + + /** + * Creates the iterator + * + * You should pass a VCALENDAR component, as well as the UID of the event + * we're going to traverse. + * + * @param Sabre_VObject_Component $vcal + * @param string|null $uid + */ + public function __construct(Sabre_VObject_Component $vcal, $uid=null) { + + if (is_null($uid)) { + if ($vcal->name === 'VCALENDAR') { + throw new InvalidArgumentException('If you pass a VCALENDAR object, you must pass a uid argument as well'); + } + $components = array($vcal); + $uid = (string)$vcal->uid; + } else { + $components = $vcal->select('VEVENT'); + } + foreach($components as $component) { + if ((string)$component->uid == $uid) { + if (isset($component->{'RECURRENCE-ID'})) { + $this->overriddenEvents[$component->DTSTART->getDateTime()->getTimeStamp()] = $component; + $this->overriddenDates[] = $component->{'RECURRENCE-ID'}->getDateTime(); + } else { + $this->baseEvent = $component; + } + } + } + if (!$this->baseEvent) { + throw new InvalidArgumentException('Could not find a base event with uid: ' . $uid); + } + + $this->startDate = clone $this->baseEvent->DTSTART->getDateTime(); + + $this->endDate = null; + if (isset($this->baseEvent->DTEND)) { + $this->endDate = clone $this->baseEvent->DTEND->getDateTime(); + } else { + $this->endDate = clone $this->startDate; + if (isset($this->baseEvent->DURATION)) { + $this->endDate->add(Sabre_VObject_DateTimeParser::parse($this->baseEvent->DURATION->value)); + } + } + $this->currentDate = clone $this->startDate; + + $rrule = (string)$this->baseEvent->RRULE; + + $parts = explode(';', $rrule); + + foreach($parts as $part) { + + list($key, $value) = explode('=', $part, 2); + + switch(strtoupper($key)) { + + case 'FREQ' : + if (!in_array( + strtolower($value), + array('secondly','minutely','hourly','daily','weekly','monthly','yearly') + )) { + throw new InvalidArgumentException('Unknown value for FREQ=' . strtoupper($value)); + + } + $this->frequency = strtolower($value); + break; + + case 'UNTIL' : + $this->until = Sabre_VObject_DateTimeParser::parse($value); + break; + + case 'COUNT' : + $this->count = (int)$value; + break; + + case 'INTERVAL' : + $this->interval = (int)$value; + break; + + case 'BYSECOND' : + $this->bySecond = explode(',', $value); + break; + + case 'BYMINUTE' : + $this->byMinute = explode(',', $value); + break; + + case 'BYHOUR' : + $this->byHour = explode(',', $value); + break; + + case 'BYDAY' : + $this->byDay = explode(',', strtoupper($value)); + break; + + case 'BYMONTHDAY' : + $this->byMonthDay = explode(',', $value); + break; + + case 'BYYEARDAY' : + $this->byYearDay = explode(',', $value); + break; + + case 'BYWEEKNO' : + $this->byWeekNo = explode(',', $value); + break; + + case 'BYMONTH' : + $this->byMonth = explode(',', $value); + break; + + case 'BYSETPOS' : + $this->bySetPos = explode(',', $value); + break; + + case 'WKST' : + $this->weekStart = strtoupper($value); + break; + + } + + } + + // Parsing exception dates + if (isset($this->baseEvent->EXDATE)) { + foreach($this->baseEvent->EXDATE as $exDate) { + + foreach(explode(',', (string)$exDate) as $exceptionDate) { + + $this->exceptionDates[] = + Sabre_VObject_DateTimeParser::parse($exceptionDate, $this->startDate->getTimeZone()); + + } + + } + + } + + } + + /** + * Returns the current item in the list + * + * @return DateTime + */ + public function current() { + + if (!$this->valid()) return null; + return clone $this->currentDate; + + } + + /** + * This method returns the startdate for the current iteration of the + * event. + * + * @return DateTime + */ + public function getDtStart() { + + if (!$this->valid()) return null; + return clone $this->currentDate; + + } + + /** + * This method returns the enddate for the current iteration of the + * event. + * + * @return DateTime + */ + public function getDtEnd() { + + if (!$this->valid()) return null; + $dtEnd = clone $this->currentDate; + $dtEnd->add( $this->startDate->diff( $this->endDate ) ); + return clone $dtEnd; + + } + + /** + * Returns a VEVENT object with the updated start and end date. + * + * Any recurrence information is removed, and this function may return an + * 'overridden' event instead. + * + * This method always returns a cloned instance. + * + * @return void + */ + public function getEventObject() { + + if ($this->currentOverriddenEvent) { + return clone $this->currentOverriddenEvent; + } + $event = clone $this->baseEvent; + unset($event->RRULE); + unset($event->EXDATE); + unset($event->RDATE); + unset($event->EXRULE); + + $event->DTSTART->setDateTime($this->getDTStart(), $event->DTSTART->getDateType()); + if (isset($event->DTEND)) { + $event->DTEND->setDateTime($this->getDtEnd(), $event->DTSTART->getDateType()); + } + if ($this->counter > 0) { + $event->{'RECURRENCE-ID'} = (string)$event->DTSTART; + } + + return $event; + + } + + /** + * Returns the current item number + * + * @return int + */ + public function key() { + + return $this->counter; + + } + + /** + * Whether or not there is a 'next item' + * + * @return bool + */ + public function valid() { + + if (!is_null($this->count)) { + return $this->counter < $this->count; + } + if (!is_null($this->until)) { + return $this->currentDate <= $this->until; + } + return true; + + } + + /** + * Resets the iterator + * + * @return void + */ + public function rewind() { + + $this->currentDate = clone $this->startDate; + $this->counter = 0; + + } + + /** + * This method allows you to quickly go to the next occurrence after the + * specified date. + * + * Note that this checks the current 'endDate', not the 'stardDate'. This + * means that if you forward to January 1st, the iterator will stop at the + * first event that ends *after* January 1st. + * + * @param DateTime $dt + * @return void + */ + public function fastForward(DateTime $dt) { + + while($this->valid() && $this->getDTEnd() < $dt) { + $this->next(); + } + + } + + /** + * Goes on to the next iteration + * + * @return void + */ + public function next() { + + /* + if (!is_null($this->count) && $this->counter >= $this->count) { + $this->currentDate = null; + }*/ + + + $previousStamp = $this->currentDate->getTimeStamp(); + + while(true) { + + $this->currentOverriddenEvent = null; + + // If we have a next date 'stored', we use that + if ($this->nextDate) { + $this->currentDate = $this->nextDate; + $currentStamp = $this->currentDate->getTimeStamp(); + $this->nextDate = null; + } else { + + // Otherwise, we calculate it + switch($this->frequency) { + + case 'daily' : + $this->nextDaily(); + break; + + case 'weekly' : + $this->nextWeekly(); + break; + + case 'monthly' : + $this->nextMonthly(); + break; + + case 'yearly' : + $this->nextYearly(); + break; + + } + $currentStamp = $this->currentDate->getTimeStamp(); + + // Checking exception dates + foreach($this->exceptionDates as $exceptionDate) { + if ($this->currentDate == $exceptionDate) { + $this->counter++; + continue 2; + } + } + foreach($this->overriddenDates as $overriddenDate) { + if ($this->currentDate == $overriddenDate) { + continue 2; + } + } + + } + + // Checking overriden events + foreach($this->overriddenEvents as $index=>$event) { + if ($index > $previousStamp && $index <= $currentStamp) { + + // We're moving the 'next date' aside, for later use. + $this->nextDate = clone $this->currentDate; + + $this->currentDate = $event->DTSTART->getDateTime(); + $this->currentOverriddenEvent = $event; + + break; + } + } + + break; + + } + + /* + if (!is_null($this->until)) { + if($this->currentDate > $this->until) { + $this->currentDate = null; + } + }*/ + + $this->counter++; + + } + + /** + * Does the processing for advancing the iterator for daily frequency. + * + * @return void + */ + protected function nextDaily() { + + if (!$this->byDay) { + $this->currentDate->modify('+' . $this->interval . ' days'); + return; + } + + $recurrenceDays = array(); + foreach($this->byDay as $byDay) { + + // The day may be preceeded with a positive (+n) or + // negative (-n) integer. However, this does not make + // sense in 'weekly' so we ignore it here. + $recurrenceDays[] = $this->dayMap[substr($byDay,-2)]; + + } + + do { + + $this->currentDate->modify('+' . $this->interval . ' days'); + + // Current day of the week + $currentDay = $this->currentDate->format('w'); + + } while (!in_array($currentDay, $recurrenceDays)); + + } + + /** + * Does the processing for advancing the iterator for weekly frequency. + * + * @return void + */ + protected function nextWeekly() { + + if (!$this->byDay) { + $this->currentDate->modify('+' . $this->interval . ' weeks'); + return; + } + + $recurrenceDays = array(); + foreach($this->byDay as $byDay) { + + // The day may be preceeded with a positive (+n) or + // negative (-n) integer. However, this does not make + // sense in 'weekly' so we ignore it here. + $recurrenceDays[] = $this->dayMap[substr($byDay,-2)]; + + } + + // Current day of the week + $currentDay = $this->currentDate->format('w'); + + // First day of the week: + $firstDay = $this->dayMap[$this->weekStart]; + + $time = array( + $this->currentDate->format('H'), + $this->currentDate->format('i'), + $this->currentDate->format('s') + ); + + // Increasing the 'current day' until we find our next + // occurrence. + while(true) { + + $currentDay++; + + if ($currentDay>6) { + $currentDay = 0; + } + + // We need to roll over to the next week + if ($currentDay === $firstDay) { + $this->currentDate->modify('+' . $this->interval . ' weeks'); + + // We need to go to the first day of this week, but only if we + // are not already on this first day of this week. + if($this->currentDate->format('w') != $firstDay) { + $this->currentDate->modify('last ' . $this->dayNames[$this->dayMap[$this->weekStart]]); + $this->currentDate->setTime($time[0],$time[1],$time[2]); + } + } + + // We have a match + if (in_array($currentDay ,$recurrenceDays)) { + $this->currentDate->modify($this->dayNames[$currentDay]); + $this->currentDate->setTime($time[0],$time[1],$time[2]); + break; + } + + } + + } + + /** + * Does the processing for advancing the iterator for monthly frequency. + * + * @return void + */ + protected function nextMonthly() { + + $currentDayOfMonth = $this->currentDate->format('j'); + if (!$this->byMonthDay && !$this->byDay) { + + // If the current day is higher than the 28th, rollover can + // occur to the next month. We Must skip these invalid + // entries. + if ($currentDayOfMonth < 29) { + $this->currentDate->modify('+' . $this->interval . ' months'); + } else { + $increase = 0; + do { + $increase++; + $tempDate = clone $this->currentDate; + $tempDate->modify('+ ' . ($this->interval*$increase) . ' months'); + } while ($tempDate->format('j') != $currentDayOfMonth); + $this->currentDate = $tempDate; + } + return; + } + + while(true) { + + $occurrences = $this->getMonthlyOccurrences(); + + foreach($occurrences as $occurrence) { + + // The first occurrence thats higher than the current + // day of the month wins. + if ($occurrence > $currentDayOfMonth) { + break 2; + } + + } + + // If we made it all the way here, it means there were no + // valid occurrences, and we need to advance to the next + // month. + $this->currentDate->modify('first day of this month'); + $this->currentDate->modify('+ ' . $this->interval . ' months'); + + // This goes to 0 because we need to start counting at hte + // beginning. + $currentDayOfMonth = 0; + + } + + $this->currentDate->setDate($this->currentDate->format('Y'), $this->currentDate->format('n'), $occurrence); + + } + + /** + * Does the processing for advancing the iterator for yearly frequency. + * + * @return void + */ + protected function nextYearly() { + + if (!$this->byMonth) { + $this->currentDate->modify('+' . $this->interval . ' years'); + return; + } + + $currentMonth = $this->currentDate->format('n'); + $currentYear = $this->currentDate->format('Y'); + $currentDayOfMonth = $this->currentDate->format('j'); + + $advancedToNewMonth = false; + + // If we got a byDay or getMonthDay filter, we must first expand + // further. + if ($this->byDay || $this->byMonthDay) { + + while(true) { + + $occurrences = $this->getMonthlyOccurrences(); + + foreach($occurrences as $occurrence) { + + // The first occurrence that's higher than the current + // day of the month wins. + // If we advanced to the next month or year, the first + // occurence is always correct. + if ($occurrence > $currentDayOfMonth || $advancedToNewMonth) { + break 2; + } + + } + + // If we made it here, it means we need to advance to + // the next month or year. + $currentDayOfMonth = 1; + $advancedToNewMonth = true; + do { + + $currentMonth++; + if ($currentMonth>12) { + $currentYear+=$this->interval; + $currentMonth = 1; + } + } while (!in_array($currentMonth, $this->byMonth)); + + $this->currentDate->setDate($currentYear, $currentMonth, $currentDayOfMonth); + + } + + // If we made it here, it means we got a valid occurrence + $this->currentDate->setDate($currentYear, $currentMonth, $occurrence); + return; + + } else { + + // no byDay or byMonthDay, so we can just loop through the + // months. + do { + + $currentMonth++; + if ($currentMonth>12) { + $currentYear+=$this->interval; + $currentMonth = 1; + } + } while (!in_array($currentMonth, $this->byMonth)); + $this->currentDate->setDate($currentYear, $currentMonth, $currentDayOfMonth); + return; + + } + + } + + /** + * Returns all the occurrences for a monthly frequency with a 'byDay' or + * 'byMonthDay' expansion for the current month. + * + * The returned list is an array of integers with the day of month (1-31). + * + * @return array + */ + protected function getMonthlyOccurrences() { + + $startDate = clone $this->currentDate; + + $byDayResults = array(); + + // Our strategy is to simply go through the byDays, advance the date to + // that point and add it to the results. + if ($this->byDay) foreach($this->byDay as $day) { + + $dayName = $this->dayNames[$this->dayMap[substr($day,-2)]]; + + // Dayname will be something like 'wednesday'. Now we need to find + // all wednesdays in this month. + $dayHits = array(); + + $checkDate = clone $startDate; + $checkDate->modify('first day of this month'); + $checkDate->modify($dayName); + + do { + $dayHits[] = $checkDate->format('j'); + $checkDate->modify('next ' . $dayName); + } while ($checkDate->format('n') === $startDate->format('n')); + + // So now we have 'all wednesdays' for month. It is however + // possible that the user only really wanted the 1st, 2nd or last + // wednesday. + if (strlen($day)>2) { + $offset = (int)substr($day,0,-2); + + if ($offset>0) { + // It is possible that the day does not exist, such as a + // 5th or 6th wednesday of the month. + if (isset($dayHits[$offset-1])) { + $byDayResults[] = $dayHits[$offset-1]; + } + } else { + + // if it was negative we count from the end of the array + $byDayResults[] = $dayHits[count($dayHits) + $offset]; + } + } else { + // There was no counter (first, second, last wednesdays), so we + // just need to add the all to the list). + $byDayResults = array_merge($byDayResults, $dayHits); + + } + + } + + $byMonthDayResults = array(); + if ($this->byMonthDay) foreach($this->byMonthDay as $monthDay) { + + // Removing values that are out of range for this month + if ($monthDay > $startDate->format('t') || + $monthDay < 0-$startDate->format('t')) { + continue; + } + if ($monthDay>0) { + $byMonthDayResults[] = $monthDay; + } else { + // Negative values + $byMonthDayResults[] = $startDate->format('t') + 1 + $monthDay; + } + } + + // If there was just byDay or just byMonthDay, they just specify our + // (almost) final list. If both were provided, then byDay limits the + // list. + if ($this->byMonthDay && $this->byDay) { + $result = array_intersect($byMonthDayResults, $byDayResults); + } elseif ($this->byMonthDay) { + $result = $byMonthDayResults; + } else { + $result = $byDayResults; + } + $result = array_unique($result); + sort($result, SORT_NUMERIC); + + // The last thing that needs checking is the BYSETPOS. If it's set, it + // means only certain items in the set survive the filter. + if (!$this->bySetPos) { + return $result; + } + + $filteredResult = array(); + foreach($this->bySetPos as $setPos) { + + if ($setPos<0) { + $setPos = count($result)-($setPos+1); + } + if (isset($result[$setPos-1])) { + $filteredResult[] = $result[$setPos-1]; + } + } + + sort($filteredResult, SORT_NUMERIC); + return $filteredResult; + + } + + +} + diff --git a/3rdparty/Sabre/VObject/Version.php b/3rdparty/Sabre/VObject/Version.php new file mode 100755 index 00000000000..00110febc07 --- /dev/null +++ b/3rdparty/Sabre/VObject/Version.php @@ -0,0 +1,24 @@ +'Australia/Darwin', + 'AUS Eastern Standard Time'=>'Australia/Sydney', + 'Afghanistan Standard Time'=>'Asia/Kabul', + 'Alaskan Standard Time'=>'America/Anchorage', + 'Arab Standard Time'=>'Asia/Riyadh', + 'Arabian Standard Time'=>'Asia/Dubai', + 'Arabic Standard Time'=>'Asia/Baghdad', + 'Argentina Standard Time'=>'America/Buenos_Aires', + 'Armenian Standard Time'=>'Asia/Yerevan', + 'Atlantic Standard Time'=>'America/Halifax', + 'Azerbaijan Standard Time'=>'Asia/Baku', + 'Azores Standard Time'=>'Atlantic/Azores', + 'Bangladesh Standard Time'=>'Asia/Dhaka', + 'Canada Central Standard Time'=>'America/Regina', + 'Cape Verde Standard Time'=>'Atlantic/Cape_Verde', + 'Caucasus Standard Time'=>'Asia/Yerevan', + 'Cen. Australia Standard Time'=>'Australia/Adelaide', + 'Central America Standard Time'=>'America/Guatemala', + 'Central Asia Standard Time'=>'Asia/Almaty', + 'Central Brazilian Standard Time'=>'America/Cuiaba', + 'Central Europe Standard Time'=>'Europe/Budapest', + 'Central European Standard Time'=>'Europe/Warsaw', + 'Central Pacific Standard Time'=>'Pacific/Guadalcanal', + 'Central Standard Time'=>'America/Chicago', + 'Central Standard Time (Mexico)'=>'America/Mexico_City', + 'China Standard Time'=>'Asia/Shanghai', + 'Dateline Standard Time'=>'Etc/GMT+12', + 'E. Africa Standard Time'=>'Africa/Nairobi', + 'E. Australia Standard Time'=>'Australia/Brisbane', + 'E. Europe Standard Time'=>'Europe/Minsk', + 'E. South America Standard Time'=>'America/Sao_Paulo', + 'Eastern Standard Time'=>'America/New_York', + 'Egypt Standard Time'=>'Africa/Cairo', + 'Ekaterinburg Standard Time'=>'Asia/Yekaterinburg', + 'FLE Standard Time'=>'Europe/Kiev', + 'Fiji Standard Time'=>'Pacific/Fiji', + 'GMT Standard Time'=>'Europe/London', + 'GTB Standard Time'=>'Europe/Istanbul', + 'Georgian Standard Time'=>'Asia/Tbilisi', + 'Greenland Standard Time'=>'America/Godthab', + 'Greenwich Standard Time'=>'Atlantic/Reykjavik', + 'Hawaiian Standard Time'=>'Pacific/Honolulu', + 'India Standard Time'=>'Asia/Calcutta', + 'Iran Standard Time'=>'Asia/Tehran', + 'Israel Standard Time'=>'Asia/Jerusalem', + 'Jordan Standard Time'=>'Asia/Amman', + 'Kamchatka Standard Time'=>'Asia/Kamchatka', + 'Korea Standard Time'=>'Asia/Seoul', + 'Magadan Standard Time'=>'Asia/Magadan', + 'Mauritius Standard Time'=>'Indian/Mauritius', + 'Mexico Standard Time'=>'America/Mexico_City', + 'Mexico Standard Time 2'=>'America/Chihuahua', + 'Mid-Atlantic Standard Time'=>'Etc/GMT+2', + 'Middle East Standard Time'=>'Asia/Beirut', + 'Montevideo Standard Time'=>'America/Montevideo', + 'Morocco Standard Time'=>'Africa/Casablanca', + 'Mountain Standard Time'=>'America/Denver', + 'Mountain Standard Time (Mexico)'=>'America/Chihuahua', + 'Myanmar Standard Time'=>'Asia/Rangoon', + 'N. Central Asia Standard Time'=>'Asia/Novosibirsk', + 'Namibia Standard Time'=>'Africa/Windhoek', + 'Nepal Standard Time'=>'Asia/Katmandu', + 'New Zealand Standard Time'=>'Pacific/Auckland', + 'Newfoundland Standard Time'=>'America/St_Johns', + 'North Asia East Standard Time'=>'Asia/Irkutsk', + 'North Asia Standard Time'=>'Asia/Krasnoyarsk', + 'Pacific SA Standard Time'=>'America/Santiago', + 'Pacific Standard Time'=>'America/Los_Angeles', + 'Pacific Standard Time (Mexico)'=>'America/Santa_Isabel', + 'Pakistan Standard Time'=>'Asia/Karachi', + 'Paraguay Standard Time'=>'America/Asuncion', + 'Romance Standard Time'=>'Europe/Paris', + 'Russian Standard Time'=>'Europe/Moscow', + 'SA Eastern Standard Time'=>'America/Cayenne', + 'SA Pacific Standard Time'=>'America/Bogota', + 'SA Western Standard Time'=>'America/La_Paz', + 'SE Asia Standard Time'=>'Asia/Bangkok', + 'Samoa Standard Time'=>'Pacific/Apia', + 'Singapore Standard Time'=>'Asia/Singapore', + 'South Africa Standard Time'=>'Africa/Johannesburg', + 'Sri Lanka Standard Time'=>'Asia/Colombo', + 'Syria Standard Time'=>'Asia/Damascus', + 'Taipei Standard Time'=>'Asia/Taipei', + 'Tasmania Standard Time'=>'Australia/Hobart', + 'Tokyo Standard Time'=>'Asia/Tokyo', + 'Tonga Standard Time'=>'Pacific/Tongatapu', + 'US Eastern Standard Time'=>'America/Indianapolis', + 'US Mountain Standard Time'=>'America/Phoenix', + 'UTC'=>'Etc/GMT', + 'UTC+12'=>'Etc/GMT-12', + 'UTC-02'=>'Etc/GMT+2', + 'UTC-11'=>'Etc/GMT+11', + 'Ulaanbaatar Standard Time'=>'Asia/Ulaanbaatar', + 'Venezuela Standard Time'=>'America/Caracas', + 'Vladivostok Standard Time'=>'Asia/Vladivostok', + 'W. Australia Standard Time'=>'Australia/Perth', + 'W. Central Africa Standard Time'=>'Africa/Lagos', + 'W. Europe Standard Time'=>'Europe/Berlin', + 'West Asia Standard Time'=>'Asia/Tashkent', + 'West Pacific Standard Time'=>'Pacific/Port_Moresby', + 'Yakutsk Standard Time'=>'Asia/Yakutsk', + ); + + static public function lookup($tzid) { + return isset(self::$map[$tzid]) ? self::$map[$tzid] : null; + } +} diff --git a/3rdparty/Sabre/VObject/includes.php b/3rdparty/Sabre/VObject/includes.php new file mode 100755 index 00000000000..0177a8f1ba6 --- /dev/null +++ b/3rdparty/Sabre/VObject/includes.php @@ -0,0 +1,41 @@ + Date: Sat, 21 Apr 2012 23:30:14 +0200 Subject: [PATCH 217/430] document the log settings --- config/config.sample.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/config.sample.php b/config/config.sample.php index 0900937c690..8561d0a7580 100755 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -25,6 +25,9 @@ $CONFIG = array( "mail_smtpname" => "", "mail_smtppassword" => "", "appcodechecker" => "", +"log_type" => "", +"logfile" => "", +"loglevel" => "", // "datadirectory" => "" ); ?> -- GitLab From 69f3b5e2d26d065351d61bfd8119181ebde08942 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Sat, 21 Apr 2012 23:34:24 +0200 Subject: [PATCH 218/430] make the button a bit more consistent to the other ownCloud interface --- apps/bookmarks/templates/bookmarklet.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/bookmarks/templates/bookmarklet.php b/apps/bookmarks/templates/bookmarklet.php index f7074462a79..a2ca0bba0e3 100644 --- a/apps/bookmarks/templates/bookmarklet.php +++ b/apps/bookmarks/templates/bookmarklet.php @@ -3,6 +3,6 @@ function createBookmarklet() { $l = OC_L10N::get('bookmarks'); echo '' . $l->t('Drag this to your browser bookmarks and click it, when you want to bookmark a webpage quickly:') . '' - . '' + . '' . $l->t('Read later') . ''; } -- GitLab From a34631f84ecdcc856741428d9f3e137616a4c444 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sat, 21 Apr 2012 20:36:17 +0200 Subject: [PATCH 219/430] Contacts: Add check for empty FN field. --- apps/contacts/js/contacts.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index 5f2bd6e9df9..e5b34e241cb 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1403,6 +1403,14 @@ $(document).ready(function(){ Contacts.UI.Card.saveProperty(this); }); + $('#fn').blur(function(){ + if($('#fn').val() == '') { + OC.dialogs.alert(t('contacts','The name field cannot be empty. Please enter a name for this contact.'), t('contacts','Name is empty'), function() { $('#fn').focus(); }); + $('#fn').focus(); + return false; + } + }); + // Name has changed. Update it and reorder. $('#fn').live('change',function(){ var name = $('#fn').val(); -- GitLab From 16fc4dfd1add9a588ed6052a94fff03a37fa7dfd Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sat, 21 Apr 2012 21:40:20 +0200 Subject: [PATCH 220/430] Contacts: Fixed contact photo drag'n'drop upload - again... --- apps/contacts/js/contacts.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index e5b34e241cb..8af23ed398b 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -387,10 +387,11 @@ Contacts={ $('#note').data('checksum', this.data.NOTE[0]['checksum']); $('#note').find('textarea').val(this.data.NOTE[0]['value']); $('#note').show(); + $('#contacts_propertymenu a[data-type="NOTE"]').parent().hide(); } else { $('#note').data('checksum', ''); $('#note').find('textarea').val(''); - //$('#note').hide(); + $('#note').hide(); } }, loadSingleProperties:function() { @@ -1437,19 +1438,19 @@ $(document).ready(function(){ $('#file_upload_start').live('change',function(){ Contacts.UI.Card.uploadPhoto(this.files); }); - $('#contacts_details_photo').bind('dragover',function(event){ + $('#contacts_details_photo_wrapper').bind('dragover',function(event){ console.log('dragover'); $(event.target).css('background-color','red'); event.stopPropagation(); event.preventDefault(); }); - $('#contacts_details_photo').bind('dragleave',function(event){ + $('#contacts_details_photo_wrapper').bind('dragleave',function(event){ console.log('dragleave'); $(event.target).css('background-color','white'); //event.stopPropagation(); //event.preventDefault(); }); - $('#contacts_details_photo').bind('drop',function(event){ + $('#contacts_details_photo_wrapper').bind('drop',function(event){ event.stopPropagation(); event.preventDefault(); console.log('drop'); -- GitLab From 56e064bd091d4ab54124bf9cd35eee3397d40a0c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sat, 21 Apr 2012 23:51:30 +0200 Subject: [PATCH 221/430] Don't trigger unnecessary change events. --- apps/contacts/js/jquery.multi-autocomplete.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/contacts/js/jquery.multi-autocomplete.js b/apps/contacts/js/jquery.multi-autocomplete.js index e1c5d63dc5f..5516a74b039 100644 --- a/apps/contacts/js/jquery.multi-autocomplete.js +++ b/apps/contacts/js/jquery.multi-autocomplete.js @@ -31,7 +31,9 @@ } else { self.element.val(tmp); } - self.element.trigger('change'); // Changes wasn't saved when only using the dropdown. + if(self.element.val().trim() != '') { + self.element.trigger('change'); // Changes wasn't saved when only using the dropdown. + } }); this.element.bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && -- GitLab From 9e3242d05ee666ef8d3ceaf038302e7254610f00 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 00:43:47 +0200 Subject: [PATCH 222/430] Contacts: Changed layout as discussed with JanC. Still WiP. --- apps/contacts/css/contacts.css | 14 +- apps/contacts/img/contact-new.svg | 449 ++++++++++++++++++++++++++++++ apps/contacts/js/contacts.js | 2 +- apps/contacts/templates/index.php | 10 +- 4 files changed, 467 insertions(+), 8 deletions(-) create mode 100644 apps/contacts/img/contact-new.svg diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index 2d207943841..33a9dd15cb9 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -1,10 +1,14 @@ /*dl > dt { font-weight: bold; }*/ - -#contacts { padding-left:2px; padding-top: 5px; background: #fff; } +#leftcontent { top: 3.5em !important; } +#rightcontent { top: 3.5em !important; padding-top: 5px; } +#contacts { background: #fff; width: 20em; top: 3.7em; bottom:3em; position: fixed; overflow: auto; } +#bottomcontrols { padding: 0; bottom:0px; height:2.8em; width: 20em; margin:0; background:#f7f7f7; border-top:1px solid #eee; position:fixed; } +#contacts_newcontact { float: left; margin: 0.2em 0 0 1em; } +#chooseaddressbook { float: right; margin: 0.2em 1em 0 0; } #leftcontent a { height: 23px; display: block; margin: 0 0 0 0; padding: 0 0 0 25px; } -#chooseaddressbook {margin-right: 170px; float: right;} +#actionbar { height: 30px; width: 60px; position: fixed; right: 0px; top: 4em; margin: 0 0 0 0; padding: 0 0 0 0; z-index: 1000; } #contacts_deletecard {position:absolute;top:15px;right:25px;} #contacts_downloadcard {position:absolute;top:15px;right:50px;} #contacts_propertymenu_button { position:absolute;top:15px;right:150px; background:url('../../../core/img/actions/add.svg') no-repeat center; } @@ -13,7 +17,6 @@ #contacts_propertymenu li a { padding: 3px; display: block } #contacts_propertymenu li:hover { background-color: #1d2d44; } #contacts_propertymenu li a:hover { color: #fff } -#actionbar { height: 30px; width: 200px; position: fixed; right: 0px; top: 75px; margin: 0 0 0 0; padding: 0 0 0 0; z-index: 1000; } #card { width: auto;/*max-width: 70em; border: thin solid lightgray; display: block;*/ } #firstrun { width: 100%; position: absolute; top: 5em; left: 0; text-align: center; font-weight:bold; font-size:1.5em; color:#777; } #firstrun #selections { font-size:0.8em; margin: 2em auto auto auto; clear: both; } @@ -21,7 +24,8 @@ #card input[type="text"].contacts_property,input[type="email"].contacts_property { width: 14em; float: left; } .categories { float: left; width: 16em; } #card input[type="text"],input[type="email"],input[type="tel"],input[type="date"], select, textarea { background-color: #fefefe; border: 0 !important; -webkit-appearance:none !important; -moz-appearance:none !important; -webkit-box-sizing:none !important; -moz-box-sizing:none !important; box-sizing:none !important; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; float: left; } -#card input[type="text"]:hover, input[type="text"]:focus, input[type="text"]:active,input[type="email"]:hover,input[type="tel"]:hover,input[type="date"]:hover,input[type="date"],input[type="date"]:hover,input[type="date"]:active,input[type="date"]:active,input[type="date"]:active,input[type="email"]:active,input[type="tel"]:active, select:hover, select:focus, select:active, textarea:focus, textarea:hover { border: 0 !important; -webkit-appearance:textfield; -moz-appearance:textfield; -webkit-box-sizing:content-box; -moz-box-sizing:content-box; box-sizing:content-box; background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #fff, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; float: left; } +#card input[type="text"]:hover, input[type="text"]:focus, input[type="text"]:active,input[type="email"]:hover,input[type="tel"]:hover,input[type="date"]:hover,input[type="date"],input[type="date"]:hover,input[type="date"]:active,input[type="date"]:active,input[type="date"]:active,input[type="email"]:active,input[type="tel"]:active, select:hover, select:focus, select:active { border: 0 !important; -webkit-appearance:textfield; -moz-appearance:textfield; -webkit-box-sizing:content-box; -moz-box-sizing:content-box; box-sizing:content-box; background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #fff, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; float: left; } +textarea:focus, textarea:hover { background:#fff; color:#333; border:1px solid #ddd; -moz-box-shadow:0 1px 1px #fff, 0 2px 0 #bbb inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; box-shadow:0 1px 1px #fff, 0 1px 0 #bbb inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; outline:none; float: left; } input[type="text"]:invalid,input[type="email"]:invalid,input[type="tel"]:invalid,input[type="date"]:invalid, textarea:invalid { color: #bbb !important; } textarea { min-height: 4em; } dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } diff --git a/apps/contacts/img/contact-new.svg b/apps/contacts/img/contact-new.svg new file mode 100644 index 00000000000..3c824dd10c9 --- /dev/null +++ b/apps/contacts/img/contact-new.svg @@ -0,0 +1,449 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index 8af23ed398b..b491b3a90ef 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -537,7 +537,7 @@ Contacts={ },*/ editNew:function(){ // add a new contact this.id = ''; this.fn = ''; this.fullname = ''; this.givname = ''; this.famname = ''; this.addname = ''; this.honpre = ''; this.honsuf = ''; - Contacts.UI.Card.add(';;;;', '', '', true); + Contacts.UI.Card.add(t('contacts', 'Contact')+';'+t('contacts', 'New')+';;;', t('contacts', 'New Contact'), '', true); /*$.getJSON(OC.filePath('contacts', 'ajax', 'newcontact.php'),{},function(jsondata){ if(jsondata.status == 'success'){ id = ''; diff --git a/apps/contacts/templates/index.php b/apps/contacts/templates/index.php index b14a35e19ed..2219d609d2e 100644 --- a/apps/contacts/templates/index.php +++ b/apps/contacts/templates/index.php @@ -3,17 +3,23 @@ var categories = ; var lang = ''; -
    +
      inc("part.contacts"); ?>
    +
    +
    + <?php echo $l->t('Add Contact'); ?>  title=t('Add Contact'); ?>" /> + <?php echo $l->t('Addressbooks'); ?> +
    +
    Date: Sun, 22 Apr 2012 01:50:46 +0200 Subject: [PATCH 223/430] Contacts: Fix error on photo crop. --- apps/contacts/ajax/savecrop.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/apps/contacts/ajax/savecrop.php b/apps/contacts/ajax/savecrop.php index 0df4e1998cb..73ac521e04b 100644 --- a/apps/contacts/ajax/savecrop.php +++ b/apps/contacts/ajax/savecrop.php @@ -44,19 +44,15 @@ function bailOut($msg) { $image = null; -$x1 = (isset($_POST['x1']) && $_POST['x1']) ? $_POST['x1'] : -1; +$x1 = (isset($_POST['x1']) && $_POST['x1']) ? $_POST['x1'] : 0; //$x2 = isset($_POST['x2']) ? $_POST['x2'] : -1; -$y1 = (isset($_POST['y1']) && $_POST['y1']) ? $_POST['y1'] : -1; +$y1 = (isset($_POST['y1']) && $_POST['y1']) ? $_POST['y1'] : 0; //$y2 = isset($_POST['y2']) ? $_POST['y2'] : -1; $w = (isset($_POST['w']) && $_POST['w']) ? $_POST['w'] : -1; $h = (isset($_POST['h']) && $_POST['h']) ? $_POST['h'] : -1; $tmp_path = isset($_POST['tmp_path']) ? $_POST['tmp_path'] : ''; $id = isset($_POST['id']) ? $_POST['id'] : ''; -if(in_array(-1, array($x1, $y1, $w, $h))) { - bailOut('Wrong crop dimensions: '.implode(', ', array($x1, $y1, $w, $h))); -} - if($tmp_path == '') { bailOut('Missing path to temporary file.'); } @@ -70,6 +66,9 @@ OC_Log::write('contacts','savecrop.php: files: '.$tmp_path.' exists: '.file_exi if(file_exists($tmp_path)) { $image = new OC_Image(); if($image->loadFromFile($tmp_path)) { + $w = ($w != -1 ? $w : $image->width()); + $h = ($h != -1 ? $h : $image->height()); + OC_Log::write('contacts','savecrop.php, x: '.$x1.' y: '.$y1.' w: '.$w.' h: '.$h, OC_Log::DEBUG); if($image->crop($x1, $y1, $w, $h)) { if($image->resize(200)) { $tmpfname = tempnam("/tmp", "occCropped"); // create a new file because of caching issues. @@ -81,7 +80,7 @@ if(file_exists($tmp_path)) { bailOut('Error getting contact object.'); } if($card->__isset('PHOTO')) { - OC_Log::write('contacts','savecrop.php: files: PHOTO property exists.', OC_Log::DEBUG); + OC_Log::write('contacts','savecrop.php: PHOTO property exists.', OC_Log::DEBUG); $property = $card->__get('PHOTO'); if(!$property) { unlink($tmpfname); -- GitLab From 80ddf37bb76743672e4b5d754cb659b30cad2f71 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 02:09:13 +0200 Subject: [PATCH 224/430] Missing double quote. --- apps/contacts/templates/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/contacts/templates/index.php b/apps/contacts/templates/index.php index 2219d609d2e..256d10afc07 100644 --- a/apps/contacts/templates/index.php +++ b/apps/contacts/templates/index.php @@ -16,7 +16,7 @@
    - <?php echo $l->t('Add Contact'); ?>  title=t('Add Contact'); ?>" /> + <?php echo $l->t('Add Contact'); ?> <?php echo $l->t('Addressbooks'); ?>
    -- GitLab From f85aaf1f5837baa9e3c4f3a4d77107211de12b4a Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 02:32:51 +0200 Subject: [PATCH 225/430] Contacts: Added bg color and shadow to controls. I suck at CSS... --- apps/contacts/css/contacts.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index 33a9dd15cb9..c19c6cc7113 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -4,7 +4,7 @@ #leftcontent { top: 3.5em !important; } #rightcontent { top: 3.5em !important; padding-top: 5px; } #contacts { background: #fff; width: 20em; top: 3.7em; bottom:3em; position: fixed; overflow: auto; } -#bottomcontrols { padding: 0; bottom:0px; height:2.8em; width: 20em; margin:0; background:#f7f7f7; border-top:1px solid #eee; position:fixed; } +#bottomcontrols { padding: 0; bottom:0px; height:2.8em; width: 20em; margin:0; background:#eee; border-top:1px solid #ccc; position:fixed; -moz-box-shadow: 0 0 0 #000, -3px 0 7px #000; -webkit-box-shadow: 0 0 0 #000, -3px 0 7px #000; box-shadow: 0 0 0 #000, -3px 0 7px #000;} #contacts_newcontact { float: left; margin: 0.2em 0 0 1em; } #chooseaddressbook { float: right; margin: 0.2em 1em 0 0; } #leftcontent a { height: 23px; display: block; margin: 0 0 0 0; padding: 0 0 0 25px; } -- GitLab From 24aff287cfb1121bde7ef5ce907085e28033a8c3 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 03:39:59 +0200 Subject: [PATCH 226/430] Link to icon was absolute. --- apps/remoteStorage/templates/settings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/remoteStorage/templates/settings.php b/apps/remoteStorage/templates/settings.php index 9b5c3b6229c..b940282b2cc 100644 --- a/apps/remoteStorage/templates/settings.php +++ b/apps/remoteStorage/templates/settings.php @@ -1,6 +1,6 @@
    ' + echo ' ' .''.$l->t('remoteStorage').' user address: ' .OC_User::getUser().'@'.$_SERVER['SERVER_NAME'] .' (more info)'; -- GitLab From f08cfcecec4d9f9ff9d6524236a0f1384e9afaee Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 03:59:28 +0200 Subject: [PATCH 227/430] Personal settings: Emphasized labels etc, mono-spaced generated paths and moved text formatting to style sheet. --- apps/calendar/templates/settings.php | 4 ++-- apps/contacts/templates/settings.php | 12 ++++++------ apps/media/templates/settings.php | 2 +- core/css/styles.css | 2 ++ settings/templates/personal.php | 2 +- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/apps/calendar/templates/settings.php b/apps/calendar/templates/settings.php index fb2a04a6498..3488fec0187 100644 --- a/apps/calendar/templates/settings.php +++ b/apps/calendar/templates/settings.php @@ -9,7 +9,7 @@ ?>
    - t('Calendar'); ?> + t('Calendar'); ?> ").append(f("left")).append(f("center")).append(f("right")))}function d(){Q.remove()}function f(u){var fa=m("";for(aa=0;aa";R+="";for(aa=0;aa";for(V=0;V
    "+(I?"
    ":"")+"
     
    ";R+=""}R+="
    @@ -241,7 +241,7 @@ t('Summary'); ?>: -
    //Alarm
    -
    //Attendees
    + \ No newline at end of file -- GitLab From 8a6cb23170b95336770bc4dcd6d58583de82815e Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 20:38:17 +0200 Subject: [PATCH 229/430] Contacts: Clear cache for contact photo and thumbnail when it has been changed. --- apps/contacts/ajax/savecrop.php | 2 ++ apps/contacts/photo.php | 9 +++++++-- apps/contacts/thumbnail.php | 3 ++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/contacts/ajax/savecrop.php b/apps/contacts/ajax/savecrop.php index 73ac521e04b..d003834ef8c 100644 --- a/apps/contacts/ajax/savecrop.php +++ b/apps/contacts/ajax/savecrop.php @@ -94,6 +94,8 @@ if(file_exists($tmp_path)) { OC_Log::write('contacts','savecrop.php: files: Adding PHOTO property.', OC_Log::DEBUG); $card->addProperty('PHOTO', $image->__toString(), array('ENCODING' => 'b', 'TYPE' => $image->mimeType())); } + $now = new DateTime; + $card->setString('REV', $now->format(DateTime::W3C)); if(!OC_Contacts_VCard::edit($id,$card)) { bailOut('Error saving contact.'); } diff --git a/apps/contacts/photo.php b/apps/contacts/photo.php index 298f1215e3c..117d0a9808f 100644 --- a/apps/contacts/photo.php +++ b/apps/contacts/photo.php @@ -19,7 +19,12 @@ function getStandardImage(){ OC_Response::redirect(OC_Helper::imagePath('contacts', 'person_large.png')); } -$id = $_GET['id']; +$id = isset($_GET['id']) ? $_GET['id'] : null; +$caching = isset($_GET['refresh']) ? 0 : null; + +if(is_null($id)) { + getStandardImage(); +} $contact = OC_Contacts_App::getContactVCard($id); $image = new OC_Image(); @@ -30,7 +35,7 @@ if(!$image) { if( is_null($contact)) { OC_Log::write('contacts','photo.php. The VCard for ID '.$id.' is not RFC compatible',OC_Log::ERROR); } else { - OC_Response::enableCaching(); + OC_Response::enableCaching($caching); OC_Contacts_App::setLastModifiedHeader($contact); // Photo :-) diff --git a/apps/contacts/thumbnail.php b/apps/contacts/thumbnail.php index 5082626499b..28b8eba22c9 100644 --- a/apps/contacts/thumbnail.php +++ b/apps/contacts/thumbnail.php @@ -39,6 +39,7 @@ if(!function_exists('imagecreatefromjpeg')) { } $id = $_GET['id']; +$caching = isset($_GET['refresh']) ? 0 : null; $contact = OC_Contacts_App::getContactVCard($id); @@ -48,7 +49,7 @@ if(is_null($contact)){ getStandardImage(); exit(); } -OC_Response::enableCaching(); +OC_Response::enableCaching($caching); OC_Contacts_App::setLastModifiedHeader($contact); $thumbnail_size = 23; -- GitLab From e8f062dc935b6bd9b8047594affda491c659b79a Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 20:44:11 +0200 Subject: [PATCH 230/430] Contacts: - Added overlay toolbar to contact photo with 'Delete current', 'Edit current', 'Load from OC_Filesystem' and 'Upload' options. - Made action icons translucent instead of hiding them. --- apps/contacts/ajax/currentphoto.php | 68 ++++++++++ apps/contacts/ajax/loadphoto.php | 4 + apps/contacts/ajax/oc_photo.php | 75 +++++++++++ apps/contacts/ajax/uploadphoto.php | 13 -- apps/contacts/css/contacts.css | 19 ++- apps/contacts/js/contacts.js | 116 ++++++++++++++---- apps/contacts/templates/part.contact.php | 5 +- apps/contacts/templates/part.contactphoto.php | 8 +- 8 files changed, 260 insertions(+), 48 deletions(-) create mode 100644 apps/contacts/ajax/currentphoto.php create mode 100644 apps/contacts/ajax/oc_photo.php diff --git a/apps/contacts/ajax/currentphoto.php b/apps/contacts/ajax/currentphoto.php new file mode 100644 index 00000000000..15cb6c7a083 --- /dev/null +++ b/apps/contacts/ajax/currentphoto.php @@ -0,0 +1,68 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see . + * + */ +// Init owncloud +require_once('../../../lib/base.php'); + +// Check if we are a user +// Firefox and Konqueror tries to download application/json for me. --Arthur +OC_JSON::setContentTypeHeader('text/plain'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('contacts'); +function bailOut($msg) { + OC_JSON::error(array('data' => array('message' => $msg))); + OC_Log::write('contacts','ajax/currentphoto.php: '.$msg, OC_Log::ERROR); + exit(); +} +function debug($msg) { + OC_Log::write('contacts','ajax/currentphoto.php: '.$msg, OC_Log::DEBUG); +} + +if (!isset($_GET['id'])) { + bailOut(OC_Contacts_App::$l10n->t('No contact ID was submitted.')); +} + +$tmpfname = tempnam("/tmp", "occOrig"); +$contact = OC_Contacts_App::getContactVCard($_GET['id']); +$image = new OC_Image(); +if(!$image) { + bailOut(OC_Contacts_App::$l10n->t('Error loading image.')); +} +// invalid vcard +if( is_null($contact)) { + bailOut(OC_Contacts_App::$l10n->t('Error reading contact photo.')); +} else { + if(!$image->loadFromBase64($contact->getAsString('PHOTO'))) { + $image->loadFromBase64($contact->getAsString('LOGO')); + } + if($image->valid()) { + if($image->save($tmpfname)) { + OC_JSON::success(array('data' => array('id'=>$_GET['id'], 'tmp'=>$tmpfname))); + exit(); + } else { + bailOut(OC_Contacts_App::$l10n->t('Error saving temporary file.')); + } + } else { + bailOut(OC_Contacts_App::$l10n->t('The loading photo is not valid.')); + } +} + +?> diff --git a/apps/contacts/ajax/loadphoto.php b/apps/contacts/ajax/loadphoto.php index 2c8bb7bf1ed..2f95cdc9328 100644 --- a/apps/contacts/ajax/loadphoto.php +++ b/apps/contacts/ajax/loadphoto.php @@ -38,6 +38,7 @@ function bailOut($msg) { $image = null; $id = isset($_GET['id']) ? $_GET['id'] : ''; +$refresh = isset($_GET['refresh']) ? true : false; if($id == '') { bailOut(OC_Contacts_App::$l10n->t('Missing contact id.')); @@ -54,6 +55,9 @@ foreach($vcard->children as $property){ $tmpl = new OC_TEMPLATE("contacts", "part.contactphoto"); $tmpl->assign('id', $id); +if($refresh) { + $tmpl->assign('refresh', 1); +} $page = $tmpl->fetchPage(); OC_JSON::success(array('data' => array('page'=>$page, 'checksum'=>$checksum))); ?> diff --git a/apps/contacts/ajax/oc_photo.php b/apps/contacts/ajax/oc_photo.php new file mode 100644 index 00000000000..14d77ea50b7 --- /dev/null +++ b/apps/contacts/ajax/oc_photo.php @@ -0,0 +1,75 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see . + * + */ +// Init owncloud +require_once('../../../lib/base.php'); + +// Check if we are a user +// Firefox and Konqueror tries to download application/json for me. --Arthur +OC_JSON::setContentTypeHeader('text/plain'); +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('contacts'); +function bailOut($msg) { + OC_JSON::error(array('data' => array('message' => $msg))); + OC_Log::write('contacts','ajax/oc_photo.php: '.$msg, OC_Log::ERROR); + exit(); +} +function debug($msg) { + OC_Log::write('contacts','ajax/oc_photo.php: '.$msg, OC_Log::DEBUG); +} + +if (!isset($_GET['id'])) { + bailOut(OC_Contacts_App::$l10n->t('No contact ID was submitted.')); +} + +if (!isset($_GET['path'])) { + bailOut(OC_Contacts_App::$l10n->t('No photo path was submitted.')); +} + +$localpath = OC_Filesystem::getLocalFile($_GET['path']); +$tmpfname = tempnam("/tmp", "occOrig"); + +if(!file_exists($localpath)) { + bailOut(OC_Contacts_App::$l10n->t('File doesn\'t exist:').$localpath); +} +file_put_contents($tmpfname, file_get_contents($localpath)); + +$image = new OC_Image(); +if(!$image) { + bailOut(OC_Contacts_App::$l10n->t('Error loading image.')); +} +if(!$image->loadFromFile($tmpfname)) { + bailOut(OC_Contacts_App::$l10n->t('Error loading image.')); +} +if($image->width() > 400 || $image->height() > 400) { + $image->resize(400); // Prettier resizing than with browser and saves bandwidth. +} +if(!$image->fixOrientation()) { // No fatal error so we don't bail out. + debug('Couldn\'t save correct image orientation: '.$tmpfname); +} +if($image->save($tmpfname)) { + OC_JSON::success(array('data' => array('mime'=>$_SERVER['CONTENT_TYPE'], 'name'=>$fn, 'id'=>$id, 'tmp'=>$tmpfname))); + exit(); +} else { + bailOut('Couldn\'t save temporary image: '.$tmpfname); +} + +?> diff --git a/apps/contacts/ajax/uploadphoto.php b/apps/contacts/ajax/uploadphoto.php index 9780df46476..15d4718241e 100644 --- a/apps/contacts/ajax/uploadphoto.php +++ b/apps/contacts/ajax/uploadphoto.php @@ -36,19 +36,6 @@ function debug($msg) { OC_Log::write('contacts','ajax/uploadphoto.php: '.$msg, OC_Log::DEBUG); } -// foreach ($_SERVER as $key=>$element) { -// debug('$_SERVER: '.$key.'=>'.$element); -// } -// foreach ($_GET as $key=>$element) { -// debug('_GET: '.$key.'=>'.$element); -// } -// foreach ($_POST as $key=>$element) { -// debug('_POST: '.$key.'=>'.$element); -// } -// foreach ($_FILES as $key=>$element) { -// debug('_FILES: '.$key.'=>'.$element); -// } - // If it is a Drag'n'Drop transfer it's handled here. $fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false); if ($fn) { diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index c19c6cc7113..b0c68c96e67 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -38,14 +38,17 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } .ui-autocomplete-loading { background: url('../../../core/img/loading.gif') right center no-repeat; } .float { float: left; } .listactions { height: 1em; width:60px; float: left; clear: right; } -.add,.edit,.delete,.mail, .globe { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; display: none; } +.add,.edit,.delete,.mail, .globe, .upload, .cloud { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } +.add:hover,.edit:hover,.delete:hover,.mail:hover, .globe:hover, .upload:hover, .cloud:hover { opacity: 1.0 } .add { background:url('../../../core/img/actions/add.svg') no-repeat center; clear: both; } .delete { background:url('../../../core/img/actions/delete.svg') no-repeat center; } .edit { background:url('../../../core/img/actions/rename.svg') no-repeat center; } .mail { background:url('../../../core/img/actions/mail.svg') no-repeat center; } +.upload { background:url('../../../core/img/actions/upload.svg') no-repeat center; } +.cloud { background:url('../../../core/img/places/picture.svg') no-repeat center; } /*.globe { background:url('../img/globe.svg') no-repeat center; }*/ .globe { background:url('../../../core/img/actions/public.svg') no-repeat center; } - +.transparent{ opacity: 0.6; } #edit_name_dialog { padding:0; } #edit_name_dialog > input { width: 15em; } #edit_address_dialog { /*width: 30em;*/ } @@ -60,9 +63,13 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } .contactpart legend { width:auto; padding:.3em; border:1px solid #ddd; font-weight:bold; cursor:pointer; background:#f8f8f8; color:#555; text-shadow:#fff 0 1px 0; -moz-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; } #cropbox { margin: auto; } -#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; cursor: pointer; background: url(../../../core/img/loading.gif) no-repeat center center; display: block; /* clear: right;*/ } -#contacts_details_photo:hover { background: #fff; } -/*#contacts_details_photo_progress { margin: 0.3em 0.3em 0.3em 7em; clear: left; }*/ +#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; background: url(../../../core/img/loading.gif) no-repeat center center; display: block; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#contacts_details_photo:hover { background: #fff; cursor: default; } +#phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.5em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#phototools li { display: inline; } +#phototools li a { float:left; cursor:pointer; width:22px; height:22px; opacity: 0.6; } +#phototools li a:hover { opacity: 0.8; } + /* Address editor */ #addressdisplay { padding: 0.5em; } dl.addresscard { background-color: #fff; float: left; width: 45%; margin: 0 0.3em 0.3em 0.3em; padding: 0; border: thin solid lightgray; } @@ -80,7 +87,7 @@ dl.addresscard dd > ul { margin: 0.3em; padding: 0.3em; } #file_upload_target, #crop_target { display:none; } -#file_upload_start { opacity:0; filter:alpha(opacity=0); z-index:1; /*position:absolute; left:0; top:0;*/ cursor:pointer; width:0; height:0;} +#file_upload_start { opacity:0; filter:alpha(opacity=0); z-index:1; /*position:absolute; left:0; top:0;*/ width:0; height:0;} input[type="checkbox"] { width: 20px; height: 20px; vertical-align: bottom; } .big { font-weight:bold; font-size:1.2em; } .huge { font-weight:bold; font-size:1.5em; } diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index b491b3a90ef..45b2fe130e2 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -117,13 +117,21 @@ Contacts={ loadListHandlers:function() { //$('.add,.delete').hide(); $('.globe,.mail,.delete,.edit,.tip').tipsy(); - $('.addresscard,.propertylist li,.propertycontainer').hover( + /*$('.addresscard,.propertylist li,.propertycontainer').hover( function () { $(this).find('.globe,.mail,.delete,.edit').fadeIn(100); }, function () { $(this).find('.globe,.mail,.delete,.edit').fadeOut(100); } + );*/ + $('.addresscard,.propertylist li,.propertycontainer').hover( + function () { + $(this).find('.globe,.mail,.delete,.edit').animate({ opacity: 1.0 }, 200, function() {}); + }, + function () { + $(this).find('.globe,.mail,.delete,.edit').animate({ opacity: 0.1 }, 200, function() {}); + } ); }, loadHandlers:function() { @@ -691,10 +699,11 @@ Contacts={ } }, deleteProperty:function(obj, type){ - //console.log('deleteProperty, id: ' + this.id); + console.log('deleteProperty, obj: ' + obj.attr('id') + ', container: ' + Contacts.UI.propertyContainerFor(obj).html()); Contacts.UI.loading(obj, true); var checksum = Contacts.UI.checksumFor(obj); - if(checksum != undefined) { + console.log('deleteProperty, id: ' + this.id + ', checksum: ' + checksum); + if(checksum) { $.getJSON('ajax/deleteproperty.php',{'id': this.id, 'checksum': checksum },function(jsondata){ if(jsondata.status == 'success'){ if(type == 'list') { @@ -707,13 +716,14 @@ Contacts={ var othertypes = ['NOTE', 'PHOTO']; if(othertypes.indexOf(proptype) != -1) { console.log('NOTE or PHOTO'); - Contacts.UI.propertyContainerFor(obj).hide(); Contacts.UI.propertyContainerFor(obj).data('checksum', ''); if(proptype == 'PHOTO') { console.log('Delete PHOTO'); Contacts.UI.Contacts.refreshThumbnail(Contacts.UI.Card.id); + Contacts.UI.Card.loadPhoto(); } else if(proptype == 'NOTE') { $('#note').find('textarea').val(''); + Contacts.UI.propertyContainerFor(obj).hide(); } } else { $('dl dt[data-element="'+proptype+'"],dd[data-element="'+proptype+'"]').hide(); @@ -1073,13 +1083,65 @@ Contacts={ form.submit(); } }, + loadPhotoHandlers:function(){ + $('#contacts_details_photo_wrapper').hover( + function () { + $('#phototools').slideDown(200); + }, + function () { + $('#phototools').slideUp(200); + } + ); + $('#phototools').hover( + function () { + $(this).removeClass('transparent'); + }, + function () { + $(this).addClass('transparent'); + } + ); + if(this.data.PHOTO) { + $('#phototools .delete').click(function() { + $(this).tipsy('hide'); + Contacts.UI.Card.deleteProperty($('#contacts_details_photo'), 'single'); + $(this).hide(); + }); + $('#phototools .edit').click(function() { + $(this).tipsy('hide'); + Contacts.UI.Card.editCurrentPhoto(); + }); + } else { + $('#phototools .delete').hide(); + $('#phototools .edit').hide(); + } + $('#phototools .upload').click(function() { + $('#file_upload_start').trigger('click'); + }); + $('#phototools .cloud').click(function() { + OC.dialogs.filepicker(t('contacts', 'Select photo'), Contacts.UI.Card.cloudPhotoSelected, false, 'image', true); + }); + }, + cloudPhotoSelected:function(path){ + console.log('cloudPhotoSelected: ' + path); + $.getJSON('ajax/oc_photo.php',{'path':path,'id':Contacts.UI.Card.id},function(jsondata){ + if(jsondata.status == 'success'){ + //alert(jsondata.data.page); + Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) + $('#edit_photo_dialog_img').html(jsondata.data.page); + } + else{ + OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); + } + }); + }, loadPhoto:function(force){ //if(this.data.PHOTO||force==true) { $.getJSON('ajax/loadphoto.php',{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); - $('#file_upload_form').data('checksum', jsondata.data.checksum); + $('#contacts_details_photo_wrapper').data('checksum', jsondata.data.checksum); $('#contacts_details_photo_wrapper').html(jsondata.data.page); + Contacts.UI.Card.loadPhotoHandlers(); } else{ OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); @@ -1093,6 +1155,18 @@ Contacts={ $('#contacts_propertymenu a[data-type="PHOTO"]').parent().show(); }*/ }, + editCurrentPhoto:function(){ + $.getJSON('ajax/currentphoto.php',{'id':this.id},function(jsondata){ + if(jsondata.status == 'success'){ + //alert(jsondata.data.page); + Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) + $('#edit_photo_dialog_img').html(jsondata.data.page); + } + else{ + OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); + } + }); + }, editPhoto:function(id, tmp_path){ //alert('editPhoto: ' + tmp_path); $.getJSON('ajax/cropphoto.php',{'tmp_path':tmp_path,'id':this.id},function(jsondata){ @@ -1119,6 +1193,7 @@ Contacts={ if(response != undefined && response.status == 'success'){ // load cropped photo. $('#contacts_details_photo_wrapper').html(response.data.page); + Contacts.UI.Card.loadPhotoHandlers(); }else{ OC.dialogs.alert(response.data.message, t('contacts', 'Error')); } @@ -1343,10 +1418,12 @@ $(document).ready(function(){ Contacts.UI.Card.editNew(); }); - /** - * Load the details view for a contact. - */ - $('#leftcontent li').live('click',function(){ + $('#contacts_deletecard').click(function(){ + Contacts.UI.Card.doDelete(); + }); + + // Load a contact. + $('#leftcontent li').click(function(){ var id = $(this).data('id'); $(this).addClass('active'); var oldid = $('#rightcontent').data('id'); @@ -1365,10 +1442,6 @@ $(document).ready(function(){ return false; }); - $('#contacts_deletecard').live('click',function(){ - Contacts.UI.Card.doDelete(); - }); - $('#contacts li').bind('inview', function(event, isInView, visiblePartX, visiblePartY) { if (isInView) { //NOTE: I've kept all conditions for future reference ;-) // element is now visible in the viewport @@ -1390,13 +1463,6 @@ $(document).ready(function(){ } }); - $('.button').tipsy(); - // Triggers invisible file input - $('#contacts_details_photo').live('click', function() { - $('#file_upload_start').trigger('click'); - return false; - }); - // NOTE: For some reason the selector doesn't work when I select by '.contacts_property' too... // I do the filtering in the event handler instead. //$('input[type="text"],input[type="checkbox"],input[type="email"],input[type="tel"],input[type="date"], select').live('change', function(){ @@ -1500,8 +1566,8 @@ $(document).ready(function(){ if (e.lengthComputable){ var _progress = Math.round((e.loaded * 100) / e.total); if (_progress != 100){ - $('#contacts_details_photo_progress').text(_progress + '%'); - $('#contacts_details_photo_progress').val(_progress); + //$('#contacts_details_photo_progress').text(_progress + '%'); + //$('#contacts_details_photo_progress').val(_progress); } } }; @@ -1517,12 +1583,12 @@ $(document).ready(function(){ xhr.send(file); } - $('body').live('click',function(e){ + $('body').click(function(e){ if(!$(e.target).is('#contacts_propertymenu_button')) { $('#contacts_propertymenu').hide(); } }); - $('#contacts_propertymenu_button').live('click',function(){ + $('#contacts_propertymenu_button').click(function(){ var menu = $('#contacts_propertymenu'); if(menu.is(':hidden')) { menu.show(); @@ -1531,7 +1597,7 @@ $(document).ready(function(){ menu.hide(); } }); - $('#contacts_propertymenu a').live('click',function(){ + $('#contacts_propertymenu a').click(function(){ var type = $(this).data('type'); Contacts.UI.Card.addProperty(type); $('#contacts_propertymenu').hide(); diff --git a/apps/contacts/templates/part.contact.php b/apps/contacts/templates/part.contact.php index c09c20fd4e4..b90fa92c2c5 100644 --- a/apps/contacts/templates/part.contact.php +++ b/apps/contacts/templates/part.contact.php @@ -23,10 +23,9 @@ $id = isset($_['id']) ? $_['id'] : '';
    - +
    - -
    +
    diff --git a/apps/contacts/templates/part.contactphoto.php b/apps/contacts/templates/part.contactphoto.php index bcb2f75815c..3c11e4d1582 100644 --- a/apps/contacts/templates/part.contactphoto.php +++ b/apps/contacts/templates/part.contactphoto.php @@ -2,8 +2,14 @@ $id = $_['id']; $wattr = isset($_['width'])?'width="'.$_['width'].'"':''; $hattr = isset($_['height'])?'height="'.$_['height'].'"':''; -$rand = isset($_['refresh'])?'&'.rand().'='.rand():''; +$rand = isset($_['refresh'])?'&refresh='.rand():''; ?> + src="?id=" /> -- GitLab From 43ee5cf2246964abb7b49ff1fd082c5072cbd526 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sun, 22 Apr 2012 21:12:44 +0200 Subject: [PATCH 231/430] remove old fullcalendar files --- 3rdparty/fullcalendar/GPL-LICENSE.txt | 278 - 3rdparty/fullcalendar/MIT-LICENSE.txt | 20 - 3rdparty/fullcalendar/changelog.txt | 313 - 3rdparty/fullcalendar/css/fullcalendar.css | 616 -- .../fullcalendar/css/fullcalendar.print.css | 59 - 3rdparty/fullcalendar/js/fullcalendar.js | 5210 ----------------- 3rdparty/fullcalendar/js/fullcalendar.min.js | 113 - 3rdparty/fullcalendar/js/gcal.js | 112 - 8 files changed, 6721 deletions(-) delete mode 100644 3rdparty/fullcalendar/GPL-LICENSE.txt delete mode 100644 3rdparty/fullcalendar/MIT-LICENSE.txt delete mode 100644 3rdparty/fullcalendar/changelog.txt delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.css delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.print.css delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.js delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.min.js delete mode 100644 3rdparty/fullcalendar/js/gcal.js diff --git a/3rdparty/fullcalendar/GPL-LICENSE.txt b/3rdparty/fullcalendar/GPL-LICENSE.txt deleted file mode 100644 index 11dddd00ef0..00000000000 --- a/3rdparty/fullcalendar/GPL-LICENSE.txt +++ /dev/null @@ -1,278 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. diff --git a/3rdparty/fullcalendar/MIT-LICENSE.txt b/3rdparty/fullcalendar/MIT-LICENSE.txt deleted file mode 100644 index 46d47544964..00000000000 --- a/3rdparty/fullcalendar/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Adam Shaw - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/3rdparty/fullcalendar/changelog.txt b/3rdparty/fullcalendar/changelog.txt deleted file mode 100644 index 50d0880fd7a..00000000000 --- a/3rdparty/fullcalendar/changelog.txt +++ /dev/null @@ -1,313 +0,0 @@ - -version 1.5.2 (8/21/11) - - correctly process UTC "Z" ISO8601 date strings (issue 750) - -version 1.5.1 (4/9/11) - - more flexible ISO8601 date parsing (issue 814) - - more flexible parsing of UNIX timestamps (issue 826) - - FullCalendar now buildable from source on a Mac (issue 795) - - FullCalendar QA'd in FF4 (issue 883) - - upgraded to jQuery 1.5.2 (which supports IE9) and jQuery UI 1.8.11 - -version 1.5 (3/19/11) - - slicker default styling for buttons - - reworked a lot of the calendar's HTML and accompanying CSS - (solves issues 327 and 395) - - more printer-friendly (fullcalendar-print.css) - - fullcalendar now inherits styles from jquery-ui themes differently. - styles for buttons are distinct from styles for calendar cells. - (solves issue 299) - - can now color events through FullCalendar options and Event-Object properties (issue 117) - THIS IS NOW THE PREFERRED METHOD OF COLORING EVENTS (as opposed to using className and CSS) - - FullCalendar options: - - eventColor (changes both background and border) - - eventBackgroundColor - - eventBorderColor - - eventTextColor - - Event-Object options: - - color (changes both background and border) - - backgroundColor - - borderColor - - textColor - - can now specify an event source as an *object* with a `url` property (json feed) or - an `events` property (function or array) with additional properties that will - be applied to the entire event source: - - color (changes both background and border) - - backgroudColor - - borderColor - - textColor - - className - - editable - - allDayDefault - - ignoreTimezone - - startParam (for a feed) - - endParam (for a feed) - - ANY OF THE JQUERY $.ajax OPTIONS - allows for easily changing from GET to POST and sending additional parameters (issue 386) - allows for easily attaching ajax handlers such as `error` (issue 754) - allows for turning caching on (issue 355) - - Google Calendar feeds are now specified differently: - - specify a simple string of your feed's URL - - specify an *object* with a `url` property of your feed's URL. - you can include any of the new Event-Source options in this object. - - the old `$.fullCalendar.gcalFeed` method still works - - no more IE7 SSL popup (issue 504) - - remove `cacheParam` - use json event source `cache` option instead - - latest jquery/jquery-ui - -version 1.4.11 (2/22/11) - - fixed rerenderEvents bug (issue 790) - - fixed bug with faulty dragging of events from all-day slot in agenda views - - bundled with jquery 1.5 and jquery-ui 1.8.9 - -version 1.4.10 (1/2/11) - - fixed bug with resizing event to different week in 5-day month view (issue 740) - - fixed bug with events not sticking after a removeEvents call (issue 757) - - fixed bug with underlying parseTime method, and other uses of parseInt (issue 688) - -version 1.4.9 (11/16/10) - - new algorithm for vertically stacking events (issue 111) - - resizing an event to a different week (issue 306) - - bug: some events not rendered with consecutive calls to addEventSource (issue 679) - -version 1.4.8 (10/16/10) - - ignoreTimezone option (set to `false` to process UTC offsets in ISO8601 dates) - - bugfixes - - event refetching not being called under certain conditions (issues 417, 554) - - event refetching being called multiple times under certain conditions (issues 586, 616) - - selection cannot be triggered by right mouse button (issue 558) - - agenda view left axis sized incorrectly (issue 465) - - IE js error when calendar is too narrow (issue 517) - - agenda view looks strange when no scrollbars (issue 235) - - improved parsing of ISO8601 dates with UTC offsets - - $.fullCalendar.version - - an internal refactor of the code, for easier future development and modularity - -version 1.4.7 (7/5/10) - - "dropping" external objects onto the calendar - - droppable (boolean, to turn on/off) - - dropAccept (to filter which events the calendar will accept) - - drop (trigger) - - selectable options can now be specified with a View Option Hash - - bugfixes - - dragged & reverted events having wrong time text (issue 406) - - bug rendering events that have an endtime with seconds, but no hours/minutes (issue 477) - - gotoDate date overflow bug (issue 429) - - wrong date reported when clicking on edge of last column in agenda views (412) - - support newlines in event titles - - select/unselect callbacks now passes native js event - -version 1.4.6 (5/31/10) - - "selecting" days or timeslots - - options: selectable, selectHelper, unselectAuto, unselectCancel - - callbacks: select, unselect - - methods: select, unselect - - when dragging an event, the highlighting reflects the duration of the event - - code compressing by Google Closure Compiler - - bundled with jQuery 1.4.2 and jQuery UI 1.8.1 - -version 1.4.5 (2/21/10) - - lazyFetching option, which can force the calendar to fetch events on every view/date change - - scroll state of agenda views are preserved when switching back to view - - bugfixes - - calling methods on an uninitialized fullcalendar throws error - - IE6/7 bug where an entire view becomes invisible (issue 320) - - error when rendering a hidden calendar (in jquery ui tabs for example) in IE (issue 340) - - interconnected bugs related to calendar resizing and scrollbars - - when switching views or clicking prev/next, calendar would "blink" (issue 333) - - liquid-width calendar's events shifted (depending on initial height of browser) (issue 341) - - more robust underlying algorithm for calendar resizing - -version 1.4.4 (2/3/10) - - optimized event rendering in all views (events render in 1/10 the time) - - gotoDate() does not force the calendar to unnecessarily rerender - - render() method now correctly readjusts height - -version 1.4.3 (12/22/09) - - added destroy method - - Google Calendar event pages respect currentTimezone - - caching now handled by jQuery's ajax - - protection from setting aspectRatio to zero - - bugfixes - - parseISO8601 and DST caused certain events to display day before - - button positioning problem in IE6 - - ajax event source removed after recently being added, events still displayed - - event not displayed when end is an empty string - - dynamically setting calendar height when no events have been fetched, throws error - -version 1.4.2 (12/02/09) - - eventAfterRender trigger - - getDate & getView methods - - height & contentHeight options (explicitly sets the pixel height) - - minTime & maxTime options (restricts shown hours in agenda view) - - getters [for all options] and setters [for height, contentHeight, and aspectRatio ONLY! stay tuned..] - - render method now readjusts calendar's size - - bugfixes - - lightbox scripts that use iframes (like fancybox) - - day-of-week classNames were off when firstDay=1 - - guaranteed space on right side of agenda events (even when stacked) - - accepts ISO8601 dates with a space (instead of 'T') - -version 1.4.1 (10/31/09) - - can exclude weekends with new 'weekends' option - - gcal feed 'currentTimezone' option - - bugfixes - - year/month/date option sometimes wouldn't set correctly (depending on current date) - - daylight savings issue caused agenda views to start at 1am (for BST users) - - cleanup of gcal.js code - -version 1.4 (10/19/09) - - agendaWeek and agendaDay views - - added some options for agenda views: - - allDaySlot - - allDayText - - firstHour - - slotMinutes - - defaultEventMinutes - - axisFormat - - modified some existing options/triggers to work with agenda views: - - dragOpacity and timeFormat can now accept a "View Hash" (a new concept) - - dayClick now has an allDay parameter - - eventDrop now has an an allDay parameter - (this will affect those who use revertFunc, adjust parameter list) - - added 'prevYear' and 'nextYear' for buttons in header - - minor change for theme users, ui-state-hover not applied to active/inactive buttons - - added event-color-changing example in docs - - better defaults for right-to-left themed button icons - -version 1.3.2 (10/13/09) - - Bugfixes (please upgrade from 1.3.1!) - - squashed potential infinite loop when addMonths and addDays - is called with an invalid date - - $.fullCalendar.parseDate() now correctly parses IETF format - - when switching views, the 'today' button sticks inactive, fixed - - gotoDate now can accept a single Date argument - - documentation for changes in 1.3.1 and 1.3.2 now on website - -version 1.3.1 (9/30/09) - - Important Bugfixes (please upgrade from 1.3!) - - When current date was late in the month, for long months, and prev/next buttons - were clicked in month-view, some months would be skipped/repeated - - In certain time zones, daylight savings time would cause certain days - to be misnumbered in month-view - - Subtle change in way week interval is chosen when switching from month to basicWeek/basicDay view - - Added 'allDayDefault' option - - Added 'changeView' and 'render' methods - -version 1.3 (9/21/09) - - different 'views': month/basicWeek/basicDay - - more flexible 'header' system for buttons - - themable by jQuery UI themes - - resizable events (require jQuery UI resizable plugin) - - rescoped & rewritten CSS, enhanced default look - - cleaner css & rendering techniques for right-to-left - - reworked options & API to support multiple views / be consistent with jQuery UI - - refactoring of entire codebase - - broken into different JS & CSS files, assembled w/ build scripts - - new test suite for new features, uses firebug-lite - - refactored docs - - Options - + date - + defaultView - + aspectRatio - + disableResizing - + monthNames (use instead of $.fullCalendar.monthNames) - + monthNamesShort (use instead of $.fullCalendar.monthAbbrevs) - + dayNames (use instead of $.fullCalendar.dayNames) - + dayNamesShort (use instead of $.fullCalendar.dayAbbrevs) - + theme - + buttonText - + buttonIcons - x draggable -> editable/disableDragging - x fixedWeeks -> weekMode - x abbrevDayHeadings -> columnFormat - x buttons/title -> header - x eventDragOpacity -> dragOpacity - x eventRevertDuration -> dragRevertDuration - x weekStart -> firstDay - x rightToLeft -> isRTL - x showTime (use 'allDay' CalEvent property instead) - - Triggered Actions - + eventResizeStart - + eventResizeStop - + eventResize - x monthDisplay -> viewDisplay - x resize -> windowResize - 'eventDrop' params changed, can revert if ajax cuts out - - CalEvent Properties - x showTime -> allDay - x draggable -> editable - 'end' is now INCLUSIVE when allDay=true - 'url' now produces a real tag, more native clicking/tab behavior - - Methods: - + renderEvent - x prevMonth -> prev - x nextMonth -> next - x prevYear/nextYear -> moveDate - x refresh -> rerenderEvents/refetchEvents - x removeEvent -> removeEvents - x getEventsByID -> clientEvents - - Utilities: - 'formatDate' format string completely changed (inspired by jQuery UI datepicker + datejs) - 'formatDates' added to support date-ranges - - Google Calendar Options: - x draggable -> editable - - Bugfixes - - gcal extension fetched 25 results max, now fetches all - -version 1.2.1 (6/29/09) - - bugfixes - - allows and corrects invalid end dates for events - - doesn't throw an error in IE while rendering when display:none - - fixed 'loading' callback when used w/ multiple addEventSource calls - - gcal className can now be an array - -version 1.2 (5/31/09) - - expanded API - - 'className' CalEvent attribute - - 'source' CalEvent attribute - - dynamically get/add/remove/update events of current month - - locale improvements: change month/day name text - - better date formatting ($.fullCalendar.formatDate) - - multiple 'event sources' allowed - - dynamically add/remove event sources - - options for prevYear and nextYear buttons - - docs have been reworked (include addition of Google Calendar docs) - - changed behavior of parseDate for number strings - (now interpets as unix timestamp, not MS times) - - bugfixes - - rightToLeft month start bug - - off-by-one errors with month formatting commands - - events from previous months sticking when clicking prev/next quickly - - Google Calendar API changed to work w/ multiple event sources - - can also provide 'className' and 'draggable' options - - date utilties moved from $ to $.fullCalendar - - more documentation in source code - - minified version of fullcalendar.js - - test suit (available from svn) - - top buttons now use
    " + - "" + - ""; - for (i=0; i"; // fc- needed for setDayID - } - s += - "" + - "" + - "" + - "" + - "" + - ""; - for (i=0; i" + // fc- needed for setDayID - "
    " + - "
    " + - "
     
    " + - "
    " + - "
    " + - ""; - } - s += - "
    " + - "" + - "" + - "
    , usually */ -.fc-widget-content { /* , usually */ - border: 1px solid #ccc; - } - -.fc-state-highlight { /* today cell */ /* TODO: add .fc-today to */ - background: #ffc; - } - -.fc-cell-overlay { /* semi-transparent rectangle while dragging */ - background: #9cf; - opacity: .2; - filter: alpha(opacity=20); /* for IE */ - } - - - -/* Buttons -------------------------------------------------------------------------*/ - -.fc-button { - position: relative; - display: inline-block; - cursor: pointer; - } - -.fc-state-default { /* non-theme */ - border-style: solid; - border-width: 1px 0; - } - -.fc-button-inner { - position: relative; - float: left; - overflow: hidden; - } - -.fc-state-default .fc-button-inner { /* non-theme */ - border-style: solid; - border-width: 0 1px; - } - -.fc-button-content { - position: relative; - float: left; - height: 1.9em; - line-height: 1.9em; - padding: 0 .6em; - white-space: nowrap; - } - -/* icon (for jquery ui) */ - -.fc-button-content .fc-icon-wrap { - position: relative; - float: left; - top: 50%; - } - -.fc-button-content .ui-icon { - position: relative; - float: left; - margin-top: -50%; - *margin-top: 0; - *top: -50%; - } - -/* gloss effect */ - -.fc-state-default .fc-button-effect { - position: absolute; - top: 50%; - left: 0; - } - -.fc-state-default .fc-button-effect span { - position: absolute; - top: -100px; - left: 0; - width: 500px; - height: 100px; - border-width: 100px 0 0 1px; - border-style: solid; - border-color: #fff; - background: #444; - opacity: .09; - filter: alpha(opacity=9); - } - -/* button states (determines colors) */ - -.fc-state-default, -.fc-state-default .fc-button-inner { - border-style: solid; - border-color: #ccc #bbb #aaa; - background: #F3F3F3; - color: #000; - } - -.fc-state-hover, -.fc-state-hover .fc-button-inner { - border-color: #999; - } - -.fc-state-down, -.fc-state-down .fc-button-inner { - border-color: #555; - background: #777; - } - -.fc-state-active, -.fc-state-active .fc-button-inner { - border-color: #555; - background: #777; - color: #fff; - } - -.fc-state-disabled, -.fc-state-disabled .fc-button-inner { - color: #999; - border-color: #ddd; - } - -.fc-state-disabled { - cursor: default; - } - -.fc-state-disabled .fc-button-effect { - display: none; - } - - - -/* Global Event Styles -------------------------------------------------------------------------*/ - -.fc-event { - border-style: solid; - border-width: 0; - font-size: .85em; - cursor: default; - } - -a.fc-event, -.fc-event-draggable { - cursor: pointer; - } - -a.fc-event { - text-decoration: none; - } - -.fc-rtl .fc-event { - text-align: right; - } - -.fc-event-skin { - border-color: #36c; /* default BORDER color */ - background-color: #36c; /* default BACKGROUND color */ - color: #fff; /* default TEXT color */ - } - -.fc-event-inner { - position: relative; - width: 100%; - height: 100%; - border-style: solid; - border-width: 0; - overflow: hidden; - } - -.fc-event-time, -.fc-event-title { - padding: 0 1px; - } - -.fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/ - display: block; - position: absolute; - z-index: 99999; - overflow: hidden; /* hacky spaces (IE6/7) */ - font-size: 300%; /* */ - line-height: 50%; /* */ - } - - - -/* Horizontal Events -------------------------------------------------------------------------*/ - -.fc-event-hori { - border-width: 1px 0; - margin-bottom: 1px; - } - -/* resizable */ - -.fc-event-hori .ui-resizable-e { - top: 0 !important; /* importants override pre jquery ui 1.7 styles */ - right: -3px !important; - width: 7px !important; - height: 100% !important; - cursor: e-resize; - } - -.fc-event-hori .ui-resizable-w { - top: 0 !important; - left: -3px !important; - width: 7px !important; - height: 100% !important; - cursor: w-resize; - } - -.fc-event-hori .ui-resizable-handle { - _padding-bottom: 14px; /* IE6 had 0 height */ - } - - - -/* Fake Rounded Corners (for buttons and events) -------------------------------------------------------------*/ - -.fc-corner-left { - margin-left: 1px; - } - -.fc-corner-left .fc-button-inner, -.fc-corner-left .fc-event-inner { - margin-left: -1px; - } - -.fc-corner-right { - margin-right: 1px; - } - -.fc-corner-right .fc-button-inner, -.fc-corner-right .fc-event-inner { - margin-right: -1px; - } - -.fc-corner-top { - margin-top: 1px; - } - -.fc-corner-top .fc-event-inner { - margin-top: -1px; - } - -.fc-corner-bottom { - margin-bottom: 1px; - } - -.fc-corner-bottom .fc-event-inner { - margin-bottom: -1px; - } - - - -/* Fake Rounded Corners SPECIFICALLY FOR EVENTS ------------------------------------------------------------------*/ - -.fc-corner-left .fc-event-inner { - border-left-width: 1px; - } - -.fc-corner-right .fc-event-inner { - border-right-width: 1px; - } - -.fc-corner-top .fc-event-inner { - border-top-width: 1px; - } - -.fc-corner-bottom .fc-event-inner { - border-bottom-width: 1px; - } - - - -/* Reusable Separate-border Table -------------------------------------------------------------*/ - -table.fc-border-separate { - border-collapse: separate; - } - -.fc-border-separate th, -.fc-border-separate td { - border-width: 1px 0 0 1px; - } - -.fc-border-separate th.fc-last, -.fc-border-separate td.fc-last { - border-right-width: 1px; - } - -.fc-border-separate tr.fc-last th, -.fc-border-separate tr.fc-last td { - border-bottom-width: 1px; - } - -.fc-border-separate tbody tr.fc-first td, -.fc-border-separate tbody tr.fc-first th { - border-top-width: 0; - } - - - -/* Month View, Basic Week View, Basic Day View -------------------------------------------------------------------------*/ - -.fc-grid th { - text-align: center; - } - -.fc-grid .fc-day-number { - float: right; - padding: 0 2px; - } - -.fc-grid .fc-other-month .fc-day-number { - opacity: 0.3; - filter: alpha(opacity=30); /* for IE */ - /* opacity with small font can sometimes look too faded - might want to set the 'color' property instead - making day-numbers bold also fixes the problem */ - } - -.fc-grid .fc-day-content { - clear: both; - padding: 2px 2px 1px; /* distance between events and day edges */ - } - -/* event styles */ - -.fc-grid .fc-event-time { - font-weight: bold; - } - -/* right-to-left */ - -.fc-rtl .fc-grid .fc-day-number { - float: left; - } - -.fc-rtl .fc-grid .fc-event-time { - float: right; - } - - - -/* Agenda Week View, Agenda Day View -------------------------------------------------------------------------*/ - -.fc-agenda table { - border-collapse: separate; - } - -.fc-agenda-days th { - text-align: center; - } - -.fc-agenda .fc-agenda-axis { - width: 50px; - padding: 0 4px; - vertical-align: middle; - text-align: right; - white-space: nowrap; - font-weight: normal; - } - -.fc-agenda .fc-day-content { - padding: 2px 2px 1px; - } - -/* make axis border take precedence */ - -.fc-agenda-days .fc-agenda-axis { - border-right-width: 1px; - } - -.fc-agenda-days .fc-col0 { - border-left-width: 0; - } - -/* all-day area */ - -.fc-agenda-allday th { - border-width: 0 1px; - } - -.fc-agenda-allday .fc-day-content { - min-height: 34px; /* TODO: doesnt work well in quirksmode */ - _height: 34px; - } - -/* divider (between all-day and slots) */ - -.fc-agenda-divider-inner { - height: 2px; - overflow: hidden; - } - -.fc-widget-header .fc-agenda-divider-inner { - background: #eee; - } - -/* slot rows */ - -.fc-agenda-slots th { - border-width: 1px 1px 0; - } - -.fc-agenda-slots td { - border-width: 1px 0 0; - background: none; - } - -.fc-agenda-slots td div { - height: 20px; - } - -.fc-agenda-slots tr.fc-slot0 th, -.fc-agenda-slots tr.fc-slot0 td { - border-top-width: 0; - } - -.fc-agenda-slots tr.fc-minor th, -.fc-agenda-slots tr.fc-minor td { - border-top-style: dotted; - } - -.fc-agenda-slots tr.fc-minor th.ui-widget-header { - *border-top-style: solid; /* doesn't work with background in IE6/7 */ - } - - - -/* Vertical Events -------------------------------------------------------------------------*/ - -.fc-event-vert { - border-width: 0 1px; - } - -.fc-event-vert .fc-event-head, -.fc-event-vert .fc-event-content { - position: relative; - z-index: 2; - width: 100%; - overflow: hidden; - } - -.fc-event-vert .fc-event-time { - white-space: nowrap; - font-size: 10px; - } - -.fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */ - position: absolute; - z-index: 1; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: #fff; - opacity: .3; - filter: alpha(opacity=30); - } - -.fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */ -.fc-select-helper .fc-event-bg { - display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */ - } - -/* resizable */ - -.fc-event-vert .ui-resizable-s { - bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */ - width: 100% !important; - height: 8px !important; - overflow: hidden !important; - line-height: 8px !important; - font-size: 11px !important; - font-family: monospace; - text-align: center; - cursor: s-resize; - } - -.fc-agenda .ui-resizable-resizing { /* TODO: better selector */ - _overflow: hidden; - } diff --git a/3rdparty/fullcalendar/css/fullcalendar.print.css b/3rdparty/fullcalendar/css/fullcalendar.print.css deleted file mode 100644 index 18c7c9b10af..00000000000 --- a/3rdparty/fullcalendar/css/fullcalendar.print.css +++ /dev/null @@ -1,59 +0,0 @@ -/* - * FullCalendar v1.5.2 Print Stylesheet - * - * Include this stylesheet on your page to get a more printer-friendly calendar. - * When including this stylesheet, use the media='print' attribute of the tag. - * Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css. - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - - - /* Events ------------------------------------------------------*/ - -.fc-event-skin { - background: none !important; - color: #000 !important; - } - -/* horizontal events */ - -.fc-event-hori { - border-width: 0 0 1px 0 !important; - border-bottom-style: dotted !important; - border-bottom-color: #000 !important; - padding: 1px 0 0 0 !important; - } - -.fc-event-hori .fc-event-inner { - border-width: 0 !important; - padding: 0 1px !important; - } - -/* vertical events */ - -.fc-event-vert { - border-width: 0 0 0 1px !important; - border-left-style: dotted !important; - border-left-color: #000 !important; - padding: 0 1px 0 0 !important; - } - -.fc-event-vert .fc-event-inner { - border-width: 0 !important; - padding: 1px 0 !important; - } - -.fc-event-bg { - display: none !important; - } - -.fc-event .ui-resizable-handle { - display: none !important; - } diff --git a/3rdparty/fullcalendar/js/fullcalendar.js b/3rdparty/fullcalendar/js/fullcalendar.js deleted file mode 100644 index fcdafbfca49..00000000000 --- a/3rdparty/fullcalendar/js/fullcalendar.js +++ /dev/null @@ -1,5210 +0,0 @@ -/** - * @preserve - * FullCalendar v1.5.2 - * http://arshaw.com/fullcalendar/ - * - * Use fullcalendar.css for basic styling. - * For event drag & drop, requires jQuery UI draggable. - * For event resizing, requires jQuery UI resizable. - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - -(function($, undefined) { - - -var defaults = { - - // display - defaultView: 'month', - aspectRatio: 1.35, - header: { - left: 'title', - center: '', - right: 'today prev,next' - }, - weekends: true, - - // editing - //editable: false, - //disableDragging: false, - //disableResizing: false, - - allDayDefault: true, - ignoreTimezone: true, - - // event ajax - lazyFetching: true, - startParam: 'start', - endParam: 'end', - - // time formats - titleFormat: { - month: 'MMMM yyyy', - week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", - day: 'dddd, MMM d, yyyy' - }, - columnFormat: { - month: 'ddd', - week: 'ddd M/d', - day: 'dddd M/d' - }, - timeFormat: { // for event elements - '': 'h(:mm)t' // default - }, - - // locale - isRTL: false, - firstDay: 0, - monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], - monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], - dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], - dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], - buttonText: { - prev: ' ◄ ', - next: ' ► ', - prevYear: ' << ', - nextYear: ' >> ', - today: 'today', - month: 'month', - week: 'week', - day: 'day' - }, - - // jquery-ui theming - theme: false, - buttonIcons: { - prev: 'circle-triangle-w', - next: 'circle-triangle-e' - }, - - //selectable: false, - unselectAuto: true, - - dropAccept: '*' - -}; - -// right-to-left defaults -var rtlDefaults = { - header: { - left: 'next,prev today', - center: '', - right: 'title' - }, - buttonText: { - prev: ' ► ', - next: ' ◄ ', - prevYear: ' >> ', - nextYear: ' << ' - }, - buttonIcons: { - prev: 'circle-triangle-e', - next: 'circle-triangle-w' - } -}; - - - -var fc = $.fullCalendar = { version: "1.5.2" }; -var fcViews = fc.views = {}; - - -$.fn.fullCalendar = function(options) { - - - // method calling - if (typeof options == 'string') { - var args = Array.prototype.slice.call(arguments, 1); - var res; - this.each(function() { - var calendar = $.data(this, 'fullCalendar'); - if (calendar && $.isFunction(calendar[options])) { - var r = calendar[options].apply(calendar, args); - if (res === undefined) { - res = r; - } - if (options == 'destroy') { - $.removeData(this, 'fullCalendar'); - } - } - }); - if (res !== undefined) { - return res; - } - return this; - } - - - // would like to have this logic in EventManager, but needs to happen before options are recursively extended - var eventSources = options.eventSources || []; - delete options.eventSources; - if (options.events) { - eventSources.push(options.events); - delete options.events; - } - - - options = $.extend(true, {}, - defaults, - (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, - options - ); - - - this.each(function(i, _element) { - var element = $(_element); - var calendar = new Calendar(element, options, eventSources); - element.data('fullCalendar', calendar); // TODO: look into memory leak implications - calendar.render(); - }); - - - return this; - -}; - - -// function for adding/overriding defaults -function setDefaults(d) { - $.extend(true, defaults, d); -} - - - - -function Calendar(element, options, eventSources) { - var t = this; - - - // exports - t.options = options; - t.render = render; - t.destroy = destroy; - t.refetchEvents = refetchEvents; - t.reportEvents = reportEvents; - t.reportEventChange = reportEventChange; - t.rerenderEvents = rerenderEvents; - t.changeView = changeView; - t.select = select; - t.unselect = unselect; - t.prev = prev; - t.next = next; - t.prevYear = prevYear; - t.nextYear = nextYear; - t.today = today; - t.gotoDate = gotoDate; - t.incrementDate = incrementDate; - t.formatDate = function(format, date) { return formatDate(format, date, options) }; - t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; - t.getDate = getDate; - t.getView = getView; - t.option = option; - t.trigger = trigger; - - - // imports - EventManager.call(t, options, eventSources); - var isFetchNeeded = t.isFetchNeeded; - var fetchEvents = t.fetchEvents; - - - // locals - var _element = element[0]; - var header; - var headerElement; - var content; - var tm; // for making theme classes - var currentView; - var viewInstances = {}; - var elementOuterWidth; - var suggestedViewHeight; - var absoluteViewElement; - var resizeUID = 0; - var ignoreWindowResize = 0; - var date = new Date(); - var events = []; - var _dragElement; - - - - /* Main Rendering - -----------------------------------------------------------------------------*/ - - - setYMD(date, options.year, options.month, options.date); - - - function render(inc) { - if (!content) { - initialRender(); - }else{ - calcSize(); - markSizesDirty(); - markEventsDirty(); - renderView(inc); - } - } - - - function initialRender() { - tm = options.theme ? 'ui' : 'fc'; - element.addClass('fc'); - if (options.isRTL) { - element.addClass('fc-rtl'); - } - if (options.theme) { - element.addClass('ui-widget'); - } - content = $("
    ") - .prependTo(element); - header = new Header(t, options); - headerElement = header.render(); - if (headerElement) { - element.prepend(headerElement); - } - changeView(options.defaultView); - $(window).resize(windowResize); - // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize - if (!bodyVisible()) { - lateRender(); - } - } - - - // called when we know the calendar couldn't be rendered when it was initialized, - // but we think it's ready now - function lateRender() { - setTimeout(function() { // IE7 needs this so dimensions are calculated correctly - if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once - renderView(); - } - },0); - } - - - function destroy() { - $(window).unbind('resize', windowResize); - header.destroy(); - content.remove(); - element.removeClass('fc fc-rtl ui-widget'); - } - - - - function elementVisible() { - return _element.offsetWidth !== 0; - } - - - function bodyVisible() { - return $('body')[0].offsetWidth !== 0; - } - - - - /* View Rendering - -----------------------------------------------------------------------------*/ - - // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) - - function changeView(newViewName) { - if (!currentView || newViewName != currentView.name) { - ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached - - unselect(); - - var oldView = currentView; - var newViewElement; - - if (oldView) { - (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) - setMinHeight(content, content.height()); - oldView.element.hide(); - }else{ - setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated - } - content.css('overflow', 'hidden'); - - currentView = viewInstances[newViewName]; - if (currentView) { - currentView.element.show(); - }else{ - currentView = viewInstances[newViewName] = new fcViews[newViewName]( - newViewElement = absoluteViewElement = - $("
    ") - .appendTo(content), - t // the calendar object - ); - } - - if (oldView) { - header.deactivateButton(oldView.name); - } - header.activateButton(newViewName); - - renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null - - content.css('overflow', ''); - if (oldView) { - setMinHeight(content, 1); - } - - if (!newViewElement) { - (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) - } - - ignoreWindowResize--; - } - } - - - - function renderView(inc) { - if (elementVisible()) { - ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached - - unselect(); - - if (suggestedViewHeight === undefined) { - calcSize(); - } - - var forceEventRender = false; - if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { - // view must render an entire new date range (and refetch/render events) - currentView.render(date, inc || 0); // responsible for clearing events - setSize(true); - forceEventRender = true; - } - else if (currentView.sizeDirty) { - // view must resize (and rerender events) - currentView.clearEvents(); - setSize(); - forceEventRender = true; - } - else if (currentView.eventsDirty) { - currentView.clearEvents(); - forceEventRender = true; - } - currentView.sizeDirty = false; - currentView.eventsDirty = false; - updateEvents(forceEventRender); - - elementOuterWidth = element.outerWidth(); - - header.updateTitle(currentView.title); - var today = new Date(); - if (today >= currentView.start && today < currentView.end) { - header.disableButton('today'); - }else{ - header.enableButton('today'); - } - - ignoreWindowResize--; - currentView.trigger('viewDisplay', _element); - } - } - - - - /* Resizing - -----------------------------------------------------------------------------*/ - - - function updateSize() { - markSizesDirty(); - if (elementVisible()) { - calcSize(); - setSize(); - unselect(); - currentView.clearEvents(); - currentView.renderEvents(events); - currentView.sizeDirty = false; - } - } - - - function markSizesDirty() { - $.each(viewInstances, function(i, inst) { - inst.sizeDirty = true; - }); - } - - - function calcSize() { - if (options.contentHeight) { - suggestedViewHeight = options.contentHeight; - } - else if (options.height) { - suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); - } - else { - suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); - } - } - - - function setSize(dateChanged) { // todo: dateChanged? - ignoreWindowResize++; - currentView.setHeight(suggestedViewHeight, dateChanged); - if (absoluteViewElement) { - absoluteViewElement.css('position', 'relative'); - absoluteViewElement = null; - } - currentView.setWidth(content.width(), dateChanged); - ignoreWindowResize--; - } - - - function windowResize() { - if (!ignoreWindowResize) { - if (currentView.start) { // view has already been rendered - var uid = ++resizeUID; - setTimeout(function() { // add a delay - if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { - if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { - ignoreWindowResize++; // in case the windowResize callback changes the height - updateSize(); - currentView.trigger('windowResize', _element); - ignoreWindowResize--; - } - } - }, 200); - }else{ - // calendar must have been initialized in a 0x0 iframe that has just been resized - lateRender(); - } - } - } - - - - /* Event Fetching/Rendering - -----------------------------------------------------------------------------*/ - - - // fetches events if necessary, rerenders events if necessary (or if forced) - function updateEvents(forceRender) { - if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { - refetchEvents(); - } - else if (forceRender) { - rerenderEvents(); - } - } - - - function refetchEvents() { - fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents - } - - - // called when event data arrives - function reportEvents(_events) { - events = _events; - rerenderEvents(); - } - - - // called when a single event's data has been changed - function reportEventChange(eventID) { - rerenderEvents(eventID); - } - - - // attempts to rerenderEvents - function rerenderEvents(modifiedEventID) { - markEventsDirty(); - if (elementVisible()) { - currentView.clearEvents(); - currentView.renderEvents(events, modifiedEventID); - currentView.eventsDirty = false; - } - } - - - function markEventsDirty() { - $.each(viewInstances, function(i, inst) { - inst.eventsDirty = true; - }); - } - - - - /* Selection - -----------------------------------------------------------------------------*/ - - - function select(start, end, allDay) { - currentView.select(start, end, allDay===undefined ? true : allDay); - } - - - function unselect() { // safe to be called before renderView - if (currentView) { - currentView.unselect(); - } - } - - - - /* Date - -----------------------------------------------------------------------------*/ - - - function prev() { - renderView(-1); - } - - - function next() { - renderView(1); - } - - - function prevYear() { - addYears(date, -1); - renderView(); - } - - - function nextYear() { - addYears(date, 1); - renderView(); - } - - - function today() { - date = new Date(); - renderView(); - } - - - function gotoDate(year, month, dateOfMonth) { - if (year instanceof Date) { - date = cloneDate(year); // provided 1 argument, a Date - }else{ - setYMD(date, year, month, dateOfMonth); - } - renderView(); - } - - - function incrementDate(years, months, days) { - if (years !== undefined) { - addYears(date, years); - } - if (months !== undefined) { - addMonths(date, months); - } - if (days !== undefined) { - addDays(date, days); - } - renderView(); - } - - - function getDate() { - return cloneDate(date); - } - - - - /* Misc - -----------------------------------------------------------------------------*/ - - - function getView() { - return currentView; - } - - - function option(name, value) { - if (value === undefined) { - return options[name]; - } - if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { - options[name] = value; - updateSize(); - } - } - - - function trigger(name, thisObj) { - if (options[name]) { - return options[name].apply( - thisObj || _element, - Array.prototype.slice.call(arguments, 2) - ); - } - } - - - - /* External Dragging - ------------------------------------------------------------------------*/ - - if (options.droppable) { - $(document) - .bind('dragstart', function(ev, ui) { - var _e = ev.target; - var e = $(_e); - if (!e.parents('.fc').length) { // not already inside a calendar - var accept = options.dropAccept; - if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { - _dragElement = _e; - currentView.dragStart(_dragElement, ev, ui); - } - } - }) - .bind('dragstop', function(ev, ui) { - if (_dragElement) { - currentView.dragStop(_dragElement, ev, ui); - _dragElement = null; - } - }); - } - - -} - -function Header(calendar, options) { - var t = this; - - - // exports - t.render = render; - t.destroy = destroy; - t.updateTitle = updateTitle; - t.activateButton = activateButton; - t.deactivateButton = deactivateButton; - t.disableButton = disableButton; - t.enableButton = enableButton; - - - // locals - var element = $([]); - var tm; - - - - function render() { - tm = options.theme ? 'ui' : 'fc'; - var sections = options.header; - if (sections) { - element = $("") - .append( - $("") - .append(renderSection('left')) - .append(renderSection('center')) - .append(renderSection('right')) - ); - return element; - } - } - - - function destroy() { - element.remove(); - } - - - function renderSection(position) { - var e = $("" + - ""; - for (i=0; i"; // need fc- for setDayID - } - s += - "" + - "" + - ""; - for (i=0; i"; - for (j=0; j" + // need fc- for setDayID - "
    " + - (showNumbers ? - "
    " : - '' - ) + - "
    " + - "
     
    " + - "
    " + - "
    " + - ""; - } - s += - ""; - } - s += - "
    " + - "
    "); - var buttonStr = options.header[position]; - if (buttonStr) { - $.each(buttonStr.split(' '), function(i) { - if (i > 0) { - e.append(""); - } - var prevButton; - $.each(this.split(','), function(j, buttonName) { - if (buttonName == 'title') { - e.append("

     

    "); - if (prevButton) { - prevButton.addClass(tm + '-corner-right'); - } - prevButton = null; - }else{ - var buttonClick; - if (calendar[buttonName]) { - buttonClick = calendar[buttonName]; // calendar method - } - else if (fcViews[buttonName]) { - buttonClick = function() { - button.removeClass(tm + '-state-hover'); // forget why - calendar.changeView(buttonName); - }; - } - if (buttonClick) { - var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? - var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? - var button = $( - "" + - "" + - "" + - (icon ? - "" + - "" + - "" : - text - ) + - "" + - "" + - "" + - "" - ); - if (button) { - button - .click(function() { - if (!button.hasClass(tm + '-state-disabled')) { - buttonClick(); - } - }) - .mousedown(function() { - button - .not('.' + tm + '-state-active') - .not('.' + tm + '-state-disabled') - .addClass(tm + '-state-down'); - }) - .mouseup(function() { - button.removeClass(tm + '-state-down'); - }) - .hover( - function() { - button - .not('.' + tm + '-state-active') - .not('.' + tm + '-state-disabled') - .addClass(tm + '-state-hover'); - }, - function() { - button - .removeClass(tm + '-state-hover') - .removeClass(tm + '-state-down'); - } - ) - .appendTo(e); - if (!prevButton) { - button.addClass(tm + '-corner-left'); - } - prevButton = button; - } - } - } - }); - if (prevButton) { - prevButton.addClass(tm + '-corner-right'); - } - }); - } - return e; - } - - - function updateTitle(html) { - element.find('h2') - .html(html); - } - - - function activateButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .addClass(tm + '-state-active'); - } - - - function deactivateButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .removeClass(tm + '-state-active'); - } - - - function disableButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .addClass(tm + '-state-disabled'); - } - - - function enableButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .removeClass(tm + '-state-disabled'); - } - - -} - -fc.sourceNormalizers = []; -fc.sourceFetchers = []; - -var ajaxDefaults = { - dataType: 'json', - cache: false -}; - -var eventGUID = 1; - - -function EventManager(options, _sources) { - var t = this; - - - // exports - t.isFetchNeeded = isFetchNeeded; - t.fetchEvents = fetchEvents; - t.addEventSource = addEventSource; - t.removeEventSource = removeEventSource; - t.updateEvent = updateEvent; - t.renderEvent = renderEvent; - t.removeEvents = removeEvents; - t.clientEvents = clientEvents; - t.normalizeEvent = normalizeEvent; - - - // imports - var trigger = t.trigger; - var getView = t.getView; - var reportEvents = t.reportEvents; - - - // locals - var stickySource = { events: [] }; - var sources = [ stickySource ]; - var rangeStart, rangeEnd; - var currentFetchID = 0; - var pendingSourceCnt = 0; - var loadingLevel = 0; - var cache = []; - - - for (var i=0; i<_sources.length; i++) { - _addEventSource(_sources[i]); - } - - - - /* Fetching - -----------------------------------------------------------------------------*/ - - - function isFetchNeeded(start, end) { - return !rangeStart || start < rangeStart || end > rangeEnd; - } - - - function fetchEvents(start, end) { - rangeStart = start; - rangeEnd = end; - cache = []; - var fetchID = ++currentFetchID; - var len = sources.length; - pendingSourceCnt = len; - for (var i=0; i)), return null instead - return null; -} - - -function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false - // derived from http://delete.me.uk/2005/03/iso8601.html - // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html - var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); - if (!m) { - return null; - } - var date = new Date(m[1], 0, 1); - if (ignoreTimezone || !m[13]) { - var check = new Date(m[1], 0, 1, 9, 0); - if (m[3]) { - date.setMonth(m[3] - 1); - check.setMonth(m[3] - 1); - } - if (m[5]) { - date.setDate(m[5]); - check.setDate(m[5]); - } - fixDate(date, check); - if (m[7]) { - date.setHours(m[7]); - } - if (m[8]) { - date.setMinutes(m[8]); - } - if (m[10]) { - date.setSeconds(m[10]); - } - if (m[12]) { - date.setMilliseconds(Number("0." + m[12]) * 1000); - } - fixDate(date, check); - }else{ - date.setUTCFullYear( - m[1], - m[3] ? m[3] - 1 : 0, - m[5] || 1 - ); - date.setUTCHours( - m[7] || 0, - m[8] || 0, - m[10] || 0, - m[12] ? Number("0." + m[12]) * 1000 : 0 - ); - if (m[14]) { - var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); - offset *= m[15] == '-' ? 1 : -1; - date = new Date(+date + (offset * 60 * 1000)); - } - } - return date; -} - - -function parseTime(s) { // returns minutes since start of day - if (typeof s == 'number') { // an hour - return s * 60; - } - if (typeof s == 'object') { // a Date object - return s.getHours() * 60 + s.getMinutes(); - } - var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); - if (m) { - var h = parseInt(m[1], 10); - if (m[3]) { - h %= 12; - if (m[3].toLowerCase().charAt(0) == 'p') { - h += 12; - } - } - return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); - } -} - - - -/* Date Formatting ------------------------------------------------------------------------------*/ -// TODO: use same function formatDate(date, [date2], format, [options]) - - -function formatDate(date, format, options) { - return formatDates(date, null, format, options); -} - - -function formatDates(date1, date2, format, options) { - options = options || defaults; - var date = date1, - otherDate = date2, - i, len = format.length, c, - i2, formatter, - res = ''; - for (i=0; ii; i2--) { - if (formatter = dateFormatters[format.substring(i, i2)]) { - if (date) { - res += formatter(date, options); - } - i = i2 - 1; - break; - } - } - if (i2 == i) { - if (date) { - res += c; - } - } - } - } - return res; -}; - - -var dateFormatters = { - s : function(d) { return d.getSeconds() }, - ss : function(d) { return zeroPad(d.getSeconds()) }, - m : function(d) { return d.getMinutes() }, - mm : function(d) { return zeroPad(d.getMinutes()) }, - h : function(d) { return d.getHours() % 12 || 12 }, - hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, - H : function(d) { return d.getHours() }, - HH : function(d) { return zeroPad(d.getHours()) }, - d : function(d) { return d.getDate() }, - dd : function(d) { return zeroPad(d.getDate()) }, - ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, - dddd: function(d,o) { return o.dayNames[d.getDay()] }, - M : function(d) { return d.getMonth() + 1 }, - MM : function(d) { return zeroPad(d.getMonth() + 1) }, - MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, - MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, - yy : function(d) { return (d.getFullYear()+'').substring(2) }, - yyyy: function(d) { return d.getFullYear() }, - t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, - tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, - T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, - TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, - u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, - S : function(d) { - var date = d.getDate(); - if (date > 10 && date < 20) { - return 'th'; - } - return ['st', 'nd', 'rd'][date%10-1] || 'th'; - } -}; - - - -fc.applyAll = applyAll; - - -/* Event Date Math ------------------------------------------------------------------------------*/ - - -function exclEndDay(event) { - if (event.end) { - return _exclEndDay(event.end, event.allDay); - }else{ - return addDays(cloneDate(event.start), 1); - } -} - - -function _exclEndDay(end, allDay) { - end = cloneDate(end); - return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); -} - - -function segCmp(a, b) { - return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); -} - - -function segsCollide(seg1, seg2) { - return seg1.end > seg2.start && seg1.start < seg2.end; -} - - - -/* Event Sorting ------------------------------------------------------------------------------*/ - - -// event rendering utilities -function sliceSegs(events, visEventEnds, start, end) { - var segs = [], - i, len=events.length, event, - eventStart, eventEnd, - segStart, segEnd, - isStart, isEnd; - for (i=0; i start && eventStart < end) { - if (eventStart < start) { - segStart = cloneDate(start); - isStart = false; - }else{ - segStart = eventStart; - isStart = true; - } - if (eventEnd > end) { - segEnd = cloneDate(end); - isEnd = false; - }else{ - segEnd = eventEnd; - isEnd = true; - } - segs.push({ - event: event, - start: segStart, - end: segEnd, - isStart: isStart, - isEnd: isEnd, - msLength: segEnd - segStart - }); - } - } - return segs.sort(segCmp); -} - - -// event rendering calculation utilities -function stackSegs(segs) { - var levels = [], - i, len = segs.length, seg, - j, collide, k; - for (i=0; i=0; i--) { - res = obj[parts[i].toLowerCase()]; - if (res !== undefined) { - return res; - } - } - return obj['']; -} - - -function htmlEscape(s) { - return s.replace(/&/g, '&') - .replace(//g, '>') - .replace(/'/g, ''') - .replace(/"/g, '"') - .replace(/\n/g, '
    '); -} - - -function cssKey(_element) { - return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); -} - - -function disableTextSelection(element) { - element - .attr('unselectable', 'on') - .css('MozUserSelect', 'none') - .bind('selectstart.ui', function() { return false; }); -} - - -/* -function enableTextSelection(element) { - element - .attr('unselectable', 'off') - .css('MozUserSelect', '') - .unbind('selectstart.ui'); -} -*/ - - -function markFirstLast(e) { - e.children() - .removeClass('fc-first fc-last') - .filter(':first-child') - .addClass('fc-first') - .end() - .filter(':last-child') - .addClass('fc-last'); -} - - -function setDayID(cell, date) { - cell.each(function(i, _cell) { - _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); - // TODO: make a way that doesn't rely on order of classes - }); -} - - -function getSkinCss(event, opt) { - var source = event.source || {}; - var eventColor = event.color; - var sourceColor = source.color; - var optionColor = opt('eventColor'); - var backgroundColor = - event.backgroundColor || - eventColor || - source.backgroundColor || - sourceColor || - opt('eventBackgroundColor') || - optionColor; - var borderColor = - event.borderColor || - eventColor || - source.borderColor || - sourceColor || - opt('eventBorderColor') || - optionColor; - var textColor = - event.textColor || - source.textColor || - opt('eventTextColor'); - var statements = []; - if (backgroundColor) { - statements.push('background-color:' + backgroundColor); - } - if (borderColor) { - statements.push('border-color:' + borderColor); - } - if (textColor) { - statements.push('color:' + textColor); - } - return statements.join(';'); -} - - -function applyAll(functions, thisObj, args) { - if ($.isFunction(functions)) { - functions = [ functions ]; - } - if (functions) { - var i; - var ret; - for (i=0; i" + - "
    "; - table = $(s).appendTo(element); - - head = table.find('thead'); - headCells = head.find('th'); - body = table.find('tbody'); - bodyRows = body.find('tr'); - bodyCells = body.find('td'); - bodyFirstCells = bodyCells.filter(':first-child'); - bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div'); - - markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's - markFirstLast(bodyRows); // marks first+last td's - bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells - - dayBind(bodyCells); - - daySegmentContainer = - $("
    ") - .appendTo(element); - } - - - - function updateCells(firstTime) { - var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? - var month = t.start.getMonth(); - var today = clearTime(new Date()); - var cell; - var date; - var row; - - if (dowDirty) { - headCells.each(function(i, _cell) { - cell = $(_cell); - date = indexDate(i); - cell.html(formatDate(date, colFormat)); - setDayID(cell, date); - }); - } - - bodyCells.each(function(i, _cell) { - cell = $(_cell); - date = indexDate(i); - if (date.getMonth() == month) { - cell.removeClass('fc-other-month'); - }else{ - cell.addClass('fc-other-month'); - } - if (+date == +today) { - cell.addClass(tm + '-state-highlight fc-today'); - }else{ - cell.removeClass(tm + '-state-highlight fc-today'); - } - cell.find('div.fc-day-number').text(date.getDate()); - if (dowDirty) { - setDayID(cell, date); - } - }); - - bodyRows.each(function(i, _row) { - row = $(_row); - if (i < rowCnt) { - row.show(); - if (i == rowCnt-1) { - row.addClass('fc-last'); - }else{ - row.removeClass('fc-last'); - } - }else{ - row.hide(); - } - }); - } - - - - function setHeight(height) { - viewHeight = height; - - var bodyHeight = viewHeight - head.height(); - var rowHeight; - var rowHeightLast; - var cell; - - if (opt('weekMode') == 'variable') { - rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); - }else{ - rowHeight = Math.floor(bodyHeight / rowCnt); - rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); - } - - bodyFirstCells.each(function(i, _cell) { - if (i < rowCnt) { - cell = $(_cell); - setMinHeight( - cell.find('> div'), - (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) - ); - } - }); - - } - - - function setWidth(width) { - viewWidth = width; - colContentPositions.clear(); - colWidth = Math.floor(viewWidth / colCnt); - setOuterWidth(headCells.slice(0, -1), colWidth); - } - - - - /* Day clicking and binding - -----------------------------------------------------------*/ - - - function dayBind(days) { - days.click(dayClick) - .mousedown(daySelectionMousedown); - } - - - function dayClick(ev) { - if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick - var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data - var date = indexDate(index); - trigger('dayClick', this, date, true, ev); - } - } - - - - /* Semi-transparent Overlay Helpers - ------------------------------------------------------*/ - - - function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive - if (refreshCoordinateGrid) { - coordinateGrid.build(); - } - var rowStart = cloneDate(t.visStart); - var rowEnd = addDays(cloneDate(rowStart), colCnt); - for (var i=0; i" + - "
      
      
    "; - dayTable = $(s).appendTo(element); - dayHead = dayTable.find('thead'); - dayHeadCells = dayHead.find('th').slice(1, -1); - dayBody = dayTable.find('tbody'); - dayBodyCells = dayBody.find('td').slice(0, -1); - dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); - dayBodyFirstCell = dayBodyCells.eq(0); - dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); - - markFirstLast(dayHead.add(dayHead.find('tr'))); - markFirstLast(dayBody.add(dayBody.find('tr'))); - - axisFirstCells = dayHead.find('th:first'); - gutterCells = dayTable.find('.fc-agenda-gutter'); - - slotLayer = - $("
    ") - .appendTo(element); - - if (opt('allDaySlot')) { - - daySegmentContainer = - $("
    ") - .appendTo(slotLayer); - - s = - "" + - "" + - "" + - "" + - "" + - "" + - "
    " + opt('allDayText') + "" + - "
    " + - "
     
    "; - allDayTable = $(s).appendTo(slotLayer); - allDayRow = allDayTable.find('tr'); - - dayBind(allDayRow.find('td')); - - axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); - gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); - - slotLayer.append( - "
    " + - "
    " + - "
    " - ); - - }else{ - - daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() - - } - - slotScroller = - $("
    ") - .appendTo(slotLayer); - - slotContent = - $("
    ") - .appendTo(slotScroller); - - slotSegmentContainer = - $("
    ") - .appendTo(slotContent); - - s = - "" + - ""; - d = zeroDate(); - maxd = addMinutes(cloneDate(d), maxMinute); - addMinutes(d, minMinute); - slotCnt = 0; - for (i=0; d < maxd; i++) { - minutes = d.getMinutes(); - s += - "" + - "" + - "" + - ""; - addMinutes(d, opt('slotMinutes')); - slotCnt++; - } - s += - "" + - "
    " + - ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') + - "" + - "
     
    " + - "
    "; - slotTable = $(s).appendTo(slotContent); - slotTableFirstInner = slotTable.find('div:first'); - - slotBind(slotTable.find('td')); - - axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); - } - - - - function updateCells() { - var i; - var headCell; - var bodyCell; - var date; - var today = clearTime(new Date()); - for (i=0; i= 0) { - addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); - } - return d; - } - - - function colDate(col) { // returns dates with 00:00:00 - return addDays(cloneDate(t.visStart), col*dis+dit); - } - - - function cellIsAllDay(cell) { - return opt('allDaySlot') && !cell.row; - } - - - function dayOfWeekCol(dayOfWeek) { - return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; - } - - - - - // get the Y coordinate of the given time on the given day (both Date objects) - function timePosition(day, time) { // both date objects. day holds 00:00 of current day - day = cloneDate(day, true); - if (time < addMinutes(cloneDate(day), minMinute)) { - return 0; - } - if (time >= addMinutes(cloneDate(day), maxMinute)) { - return slotTable.height(); - } - var slotMinutes = opt('slotMinutes'), - minutes = time.getHours()*60 + time.getMinutes() - minMinute, - slotI = Math.floor(minutes / slotMinutes), - slotTop = slotTopCache[slotI]; - if (slotTop === undefined) { - slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? - } - return Math.max(0, Math.round( - slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) - )); - } - - - function allDayBounds() { - return { - left: axisWidth, - right: viewWidth - gutterWidth - } - } - - - function getAllDayRow(index) { - return allDayRow; - } - - - function defaultEventEnd(event) { - var start = cloneDate(event.start); - if (event.allDay) { - return start; - } - return addMinutes(start, opt('defaultEventMinutes')); - } - - - - /* Selection - ---------------------------------------------------------------------------------*/ - - - function defaultSelectionEnd(startDate, allDay) { - if (allDay) { - return cloneDate(startDate); - } - return addMinutes(cloneDate(startDate), opt('slotMinutes')); - } - - - function renderSelection(startDate, endDate, allDay) { // only for all-day - if (allDay) { - if (opt('allDaySlot')) { - renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); - } - }else{ - renderSlotSelection(startDate, endDate); - } - } - - - function renderSlotSelection(startDate, endDate) { - var helperOption = opt('selectHelper'); - coordinateGrid.build(); - if (helperOption) { - var col = dayDiff(startDate, t.visStart) * dis + dit; - if (col >= 0 && col < colCnt) { // only works when times are on same day - var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords - var top = timePosition(startDate, startDate); - var bottom = timePosition(startDate, endDate); - if (bottom > top) { // protect against selections that are entirely before or after visible range - rect.top = top; - rect.height = bottom - top; - rect.left += 2; - rect.width -= 5; - if ($.isFunction(helperOption)) { - var helperRes = helperOption(startDate, endDate); - if (helperRes) { - rect.position = 'absolute'; - rect.zIndex = 8; - selectionHelper = $(helperRes) - .css(rect) - .appendTo(slotContent); - } - }else{ - rect.isStart = true; // conside rect a "seg" now - rect.isEnd = true; // - selectionHelper = $(slotSegHtml( - { - title: '', - start: startDate, - end: endDate, - className: ['fc-select-helper'], - editable: false - }, - rect - )); - selectionHelper.css('opacity', opt('dragOpacity')); - } - if (selectionHelper) { - slotBind(selectionHelper); - slotContent.append(selectionHelper); - setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended - setOuterHeight(selectionHelper, rect.height, true); - } - } - } - }else{ - renderSlotOverlay(startDate, endDate); - } - } - - - function clearSelection() { - clearOverlays(); - if (selectionHelper) { - selectionHelper.remove(); - selectionHelper = null; - } - } - - - function slotSelectionMousedown(ev) { - if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button - unselect(ev); - var dates; - hoverListener.start(function(cell, origCell) { - clearSelection(); - if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { - var d1 = cellDate(origCell); - var d2 = cellDate(cell); - dates = [ - d1, - addMinutes(cloneDate(d1), opt('slotMinutes')), - d2, - addMinutes(cloneDate(d2), opt('slotMinutes')) - ].sort(cmp); - renderSlotSelection(dates[0], dates[3]); - }else{ - dates = null; - } - }, ev); - $(document).one('mouseup', function(ev) { - hoverListener.stop(); - if (dates) { - if (+dates[0] == +dates[1]) { - reportDayClick(dates[0], false, ev); - } - reportSelection(dates[0], dates[3], false, ev); - } - }); - } - } - - - function reportDayClick(date, allDay, ev) { - trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); - } - - - - /* External Dragging - --------------------------------------------------------------------------------*/ - - - function dragStart(_dragElement, ev, ui) { - hoverListener.start(function(cell) { - clearOverlays(); - if (cell) { - if (cellIsAllDay(cell)) { - renderCellOverlay(cell.row, cell.col, cell.row, cell.col); - }else{ - var d1 = cellDate(cell); - var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); - renderSlotOverlay(d1, d2); - } - } - }, ev); - } - - - function dragStop(_dragElement, ev, ui) { - var cell = hoverListener.stop(); - clearOverlays(); - if (cell) { - trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); - } - } - - -} - -function AgendaEventRenderer() { - var t = this; - - - // exports - t.renderEvents = renderEvents; - t.compileDaySegs = compileDaySegs; // for DayEventRenderer - t.clearEvents = clearEvents; - t.slotSegHtml = slotSegHtml; - t.bindDaySeg = bindDaySeg; - - - // imports - DayEventRenderer.call(t); - var opt = t.opt; - var trigger = t.trigger; - //var setOverflowHidden = t.setOverflowHidden; - var isEventDraggable = t.isEventDraggable; - var isEventResizable = t.isEventResizable; - var eventEnd = t.eventEnd; - var reportEvents = t.reportEvents; - var reportEventClear = t.reportEventClear; - var eventElementHandlers = t.eventElementHandlers; - var setHeight = t.setHeight; - var getDaySegmentContainer = t.getDaySegmentContainer; - var getSlotSegmentContainer = t.getSlotSegmentContainer; - var getHoverListener = t.getHoverListener; - var getMaxMinute = t.getMaxMinute; - var getMinMinute = t.getMinMinute; - var timePosition = t.timePosition; - var colContentLeft = t.colContentLeft; - var colContentRight = t.colContentRight; - var renderDaySegs = t.renderDaySegs; - var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture - var getColCnt = t.getColCnt; - var getColWidth = t.getColWidth; - var getSlotHeight = t.getSlotHeight; - var getBodyContent = t.getBodyContent; - var reportEventElement = t.reportEventElement; - var showEvents = t.showEvents; - var hideEvents = t.hideEvents; - var eventDrop = t.eventDrop; - var eventResize = t.eventResize; - var renderDayOverlay = t.renderDayOverlay; - var clearOverlays = t.clearOverlays; - var calendar = t.calendar; - var formatDate = calendar.formatDate; - var formatDates = calendar.formatDates; - - - - /* Rendering - ----------------------------------------------------------------------------*/ - - - function renderEvents(events, modifiedEventId) { - reportEvents(events); - var i, len=events.length, - dayEvents=[], - slotEvents=[]; - for (i=0; i" + - "
    " + - "
    " + - "
    " + - htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + - "
    " + - "
    " + - "
    " + - "
    " + - htmlEscape(event.title) + - "
    " + - "
    " + - "
    " + - "
    "; // close inner - if (seg.isEnd && isEventResizable(event)) { - html += - "
    =
    "; - } - html += - ""; - return html; - } - - - function bindDaySeg(event, eventElement, seg) { - if (isEventDraggable(event)) { - draggableDayEvent(event, eventElement, seg.isStart); - } - if (seg.isEnd && isEventResizable(event)) { - resizableDayEvent(event, eventElement, seg); - } - eventElementHandlers(event, eventElement); - // needs to be after, because resizableDayEvent might stopImmediatePropagation on click - } - - - function bindSlotSeg(event, eventElement, seg) { - var timeElement = eventElement.find('div.fc-event-time'); - if (isEventDraggable(event)) { - draggableSlotEvent(event, eventElement, timeElement); - } - if (seg.isEnd && isEventResizable(event)) { - resizableSlotEvent(event, eventElement, timeElement); - } - eventElementHandlers(event, eventElement); - } - - - - /* Dragging - -----------------------------------------------------------------------------------*/ - - - // when event starts out FULL-DAY - - function draggableDayEvent(event, eventElement, isStart) { - var origWidth; - var revert; - var allDay=true; - var dayDelta; - var dis = opt('isRTL') ? -1 : 1; - var hoverListener = getHoverListener(); - var colWidth = getColWidth(); - var slotHeight = getSlotHeight(); - var minMinute = getMinMinute(); - eventElement.draggable({ - zIndex: 9, - opacity: opt('dragOpacity', 'month'), // use whatever the month view was using - revertDuration: opt('dragRevertDuration'), - start: function(ev, ui) { - trigger('eventDragStart', eventElement, event, ev, ui); - hideEvents(event, eventElement); - origWidth = eventElement.width(); - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - clearOverlays(); - if (cell) { - //setOverflowHidden(true); - revert = false; - dayDelta = colDelta * dis; - if (!cell.row) { - // on full-days - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - resetElement(); - }else{ - // mouse is over bottom slots - if (isStart) { - if (allDay) { - // convert event to temporary slot-event - eventElement.width(colWidth - 10); // don't use entire width - setOuterHeight( - eventElement, - slotHeight * Math.round( - (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) - / opt('slotMinutes') - ) - ); - eventElement.draggable('option', 'grid', [colWidth, 1]); - allDay = false; - } - }else{ - revert = true; - } - } - revert = revert || (allDay && !dayDelta); - }else{ - resetElement(); - //setOverflowHidden(false); - revert = true; - } - eventElement.draggable('option', 'revert', revert); - }, ev, 'drag'); - }, - stop: function(ev, ui) { - hoverListener.stop(); - clearOverlays(); - trigger('eventDragStop', eventElement, event, ev, ui); - if (revert) { - // hasn't moved or is out of bounds (draggable has already reverted) - resetElement(); - eventElement.css('filter', ''); // clear IE opacity side-effects - showEvents(event, eventElement); - }else{ - // changed! - var minuteDelta = 0; - if (!allDay) { - minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) - * opt('slotMinutes') - + minMinute - - (event.start.getHours() * 60 + event.start.getMinutes()); - } - eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); - } - //setOverflowHidden(false); - } - }); - function resetElement() { - if (!allDay) { - eventElement - .width(origWidth) - .height('') - .draggable('option', 'grid', null); - allDay = true; - } - } - } - - - // when event starts out IN TIMESLOTS - - function draggableSlotEvent(event, eventElement, timeElement) { - var origPosition; - var allDay=false; - var dayDelta; - var minuteDelta; - var prevMinuteDelta; - var dis = opt('isRTL') ? -1 : 1; - var hoverListener = getHoverListener(); - var colCnt = getColCnt(); - var colWidth = getColWidth(); - var slotHeight = getSlotHeight(); - eventElement.draggable({ - zIndex: 9, - scroll: false, - grid: [colWidth, slotHeight], - axis: colCnt==1 ? 'y' : false, - opacity: opt('dragOpacity'), - revertDuration: opt('dragRevertDuration'), - start: function(ev, ui) { - trigger('eventDragStart', eventElement, event, ev, ui); - hideEvents(event, eventElement); - origPosition = eventElement.position(); - minuteDelta = prevMinuteDelta = 0; - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - eventElement.draggable('option', 'revert', !cell); - clearOverlays(); - if (cell) { - dayDelta = colDelta * dis; - if (opt('allDaySlot') && !cell.row) { - // over full days - if (!allDay) { - // convert to temporary all-day event - allDay = true; - timeElement.hide(); - eventElement.draggable('option', 'grid', null); - } - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - }else{ - // on slots - resetElement(); - } - } - }, ev, 'drag'); - }, - drag: function(ev, ui) { - minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); - if (minuteDelta != prevMinuteDelta) { - if (!allDay) { - updateTimeText(minuteDelta); - } - prevMinuteDelta = minuteDelta; - } - }, - stop: function(ev, ui) { - var cell = hoverListener.stop(); - clearOverlays(); - trigger('eventDragStop', eventElement, event, ev, ui); - if (cell && (dayDelta || minuteDelta || allDay)) { - // changed! - eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); - }else{ - // either no change or out-of-bounds (draggable has already reverted) - resetElement(); - eventElement.css('filter', ''); // clear IE opacity side-effects - eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position - updateTimeText(0); - showEvents(event, eventElement); - } - } - }); - function updateTimeText(minuteDelta) { - var newStart = addMinutes(cloneDate(event.start), minuteDelta); - var newEnd; - if (event.end) { - newEnd = addMinutes(cloneDate(event.end), minuteDelta); - } - timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); - } - function resetElement() { - // convert back to original slot-event - if (allDay) { - timeElement.css('display', ''); // show() was causing display=inline - eventElement.draggable('option', 'grid', [colWidth, slotHeight]); - allDay = false; - } - } - } - - - - /* Resizing - --------------------------------------------------------------------------------------*/ - - - function resizableSlotEvent(event, eventElement, timeElement) { - var slotDelta, prevSlotDelta; - var slotHeight = getSlotHeight(); - eventElement.resizable({ - handles: { - s: 'div.ui-resizable-s' - }, - grid: slotHeight, - start: function(ev, ui) { - slotDelta = prevSlotDelta = 0; - hideEvents(event, eventElement); - eventElement.css('z-index', 9); - trigger('eventResizeStart', this, event, ev, ui); - }, - resize: function(ev, ui) { - // don't rely on ui.size.height, doesn't take grid into account - slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); - if (slotDelta != prevSlotDelta) { - timeElement.text( - formatDates( - event.start, - (!slotDelta && !event.end) ? null : // no change, so don't display time range - addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), - opt('timeFormat') - ) - ); - prevSlotDelta = slotDelta; - } - }, - stop: function(ev, ui) { - trigger('eventResizeStop', this, event, ev, ui); - if (slotDelta) { - eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); - }else{ - eventElement.css('z-index', 8); - showEvents(event, eventElement); - // BUG: if event was really short, need to put title back in span - } - } - }); - } - - -} - - -function countForwardSegs(levels) { - var i, j, k, level, segForward, segBack; - for (i=levels.length-1; i>0; i--) { - level = levels[i]; - for (j=0; j"); - var elements; - var segmentContainer = getDaySegmentContainer(); - var i; - var segCnt = segs.length; - var element; - tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() - elements = tempContainer.children(); - segmentContainer.append(elements); - daySegElementResolve(segs, elements); - daySegCalcHSides(segs); - daySegSetWidths(segs); - daySegCalcHeights(segs); - daySegSetTops(segs, getRowTops(getRowDivs())); - elements = []; - for (i=0; i" + - ""; - if (!event.allDay && seg.isStart) { - html += - "" + - htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + - ""; - } - html += - "" + htmlEscape(event.title) + "" + - "
    "; - if (seg.isEnd && isEventResizable(event)) { - html += - "
    " + - "   " + // makes hit area a lot better for IE6/7 - "
    "; - } - html += - ""; - seg.left = left; - seg.outerWidth = right - left; - seg.startCol = leftCol; - seg.endCol = rightCol + 1; // needs to be exclusive - } - return html; - } - - - function daySegElementResolve(segs, elements) { // sets seg.element - var i; - var segCnt = segs.length; - var seg; - var event; - var element; - var triggerRes; - for (i=0; i div'); // optimal selector? - } - return rowDivs; - } - - - function getRowTops(rowDivs) { - var i; - var rowCnt = rowDivs.length; - var tops = []; - for (i=0; i selection for IE - element - .mousedown(function(ev) { // prevent native
    selection for others - ev.preventDefault(); - }) - .click(function(ev) { - if (isResizing) { - ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) - ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called - // (eventElementHandlers needs to be bound after resizableDayEvent) - } - }); - - handle.mousedown(function(ev) { - if (ev.which != 1) { - return; // needs to be left mouse button - } - isResizing = true; - var hoverListener = t.getHoverListener(); - var rowCnt = getRowCnt(); - var colCnt = getColCnt(); - var dis = rtl ? -1 : 1; - var dit = rtl ? colCnt-1 : 0; - var elementTop = element.css('top'); - var dayDelta; - var helpers; - var eventCopy = $.extend({}, event); - var minCell = dateCell(event.start); - clearSelection(); - $('body') - .css('cursor', direction + '-resize') - .one('mouseup', mouseup); - trigger('eventResizeStart', this, event, ev); - hoverListener.start(function(cell, origCell) { - if (cell) { - var r = Math.max(minCell.row, cell.row); - var c = cell.col; - if (rowCnt == 1) { - r = 0; // hack for all-day area in agenda views - } - if (r == minCell.row) { - if (rtl) { - c = Math.min(minCell.col, c); - }else{ - c = Math.max(minCell.col, c); - } - } - dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); - var newEnd = addDays(eventEnd(event), dayDelta, true); - if (dayDelta) { - eventCopy.end = newEnd; - var oldHelpers = helpers; - helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); - helpers.find('*').css('cursor', direction + '-resize'); - if (oldHelpers) { - oldHelpers.remove(); - } - hideEvents(event); - }else{ - if (helpers) { - showEvents(event); - helpers.remove(); - helpers = null; - } - } - clearOverlays(); - renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start - } - }, ev); - - function mouseup(ev) { - trigger('eventResizeStop', this, event, ev); - $('body').css('cursor', ''); - hoverListener.stop(); - clearOverlays(); - if (dayDelta) { - eventResize(this, event, dayDelta, 0, ev); - // event redraw will clear helpers - } - // otherwise, the drag handler already restored the old events - - setTimeout(function() { // make this happen after the element's click event - isResizing = false; - },0); - } - - }); - } - - -} - -//BUG: unselect needs to be triggered when events are dragged+dropped - -function SelectionManager() { - var t = this; - - - // exports - t.select = select; - t.unselect = unselect; - t.reportSelection = reportSelection; - t.daySelectionMousedown = daySelectionMousedown; - - - // imports - var opt = t.opt; - var trigger = t.trigger; - var defaultSelectionEnd = t.defaultSelectionEnd; - var renderSelection = t.renderSelection; - var clearSelection = t.clearSelection; - - - // locals - var selected = false; - - - - // unselectAuto - if (opt('selectable') && opt('unselectAuto')) { - $(document).mousedown(function(ev) { - var ignore = opt('unselectCancel'); - if (ignore) { - if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match - return; - } - } - unselect(ev); - }); - } - - - function select(startDate, endDate, allDay) { - unselect(); - if (!endDate) { - endDate = defaultSelectionEnd(startDate, allDay); - } - renderSelection(startDate, endDate, allDay); - reportSelection(startDate, endDate, allDay); - } - - - function unselect(ev) { - if (selected) { - selected = false; - clearSelection(); - trigger('unselect', null, ev); - } - } - - - function reportSelection(startDate, endDate, allDay, ev) { - selected = true; - trigger('select', null, startDate, endDate, allDay, ev); - } - - - function daySelectionMousedown(ev) { // not really a generic manager method, oh well - var cellDate = t.cellDate; - var cellIsAllDay = t.cellIsAllDay; - var hoverListener = t.getHoverListener(); - var reportDayClick = t.reportDayClick; // this is hacky and sort of weird - if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button - unselect(ev); - var _mousedownElement = this; - var dates; - hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell - clearSelection(); - if (cell && cellIsAllDay(cell)) { - dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); - renderSelection(dates[0], dates[1], true); - }else{ - dates = null; - } - }, ev); - $(document).one('mouseup', function(ev) { - hoverListener.stop(); - if (dates) { - if (+dates[0] == +dates[1]) { - reportDayClick(dates[0], true, ev); - } - reportSelection(dates[0], dates[1], true, ev); - } - }); - } - } - - -} - -function OverlayManager() { - var t = this; - - - // exports - t.renderOverlay = renderOverlay; - t.clearOverlays = clearOverlays; - - - // locals - var usedOverlays = []; - var unusedOverlays = []; - - - function renderOverlay(rect, parent) { - var e = unusedOverlays.shift(); - if (!e) { - e = $("
    "); - } - if (e[0].parentNode != parent[0]) { - e.appendTo(parent); - } - usedOverlays.push(e.css(rect).show()); - return e; - } - - - function clearOverlays() { - var e; - while (e = usedOverlays.shift()) { - unusedOverlays.push(e.hide().unbind()); - } - } - - -} - -function CoordinateGrid(buildFunc) { - - var t = this; - var rows; - var cols; - - - t.build = function() { - rows = []; - cols = []; - buildFunc(rows, cols); - }; - - - t.cell = function(x, y) { - var rowCnt = rows.length; - var colCnt = cols.length; - var i, r=-1, c=-1; - for (i=0; i= rows[i][0] && y < rows[i][1]) { - r = i; - break; - } - } - for (i=0; i= cols[i][0] && x < cols[i][1]) { - c = i; - break; - } - } - return (r>=0 && c>=0) ? { row:r, col:c } : null; - }; - - - t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive - var origin = originElement.offset(); - return { - top: rows[row0][0] - origin.top, - left: cols[col0][0] - origin.left, - width: cols[col1][1] - cols[col0][0], - height: rows[row1][1] - rows[row0][0] - }; - }; - -} - -function HoverListener(coordinateGrid) { - - - var t = this; - var bindType; - var change; - var firstCell; - var cell; - - - t.start = function(_change, ev, _bindType) { - change = _change; - firstCell = cell = null; - coordinateGrid.build(); - mouse(ev); - bindType = _bindType || 'mousemove'; - $(document).bind(bindType, mouse); - }; - - - function mouse(ev) { - var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); - if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) { - if (newCell) { - if (!firstCell) { - firstCell = newCell; - } - change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); - }else{ - change(newCell, firstCell); - } - cell = newCell; - } - } - - - t.stop = function() { - $(document).unbind(bindType, mouse); - return cell; - }; - - -} - -function HorizontalPositionCache(getElement) { - - var t = this, - elements = {}, - lefts = {}, - rights = {}; - - function e(i) { - return elements[i] = elements[i] || getElement(i); - } - - t.left = function(i) { - return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i]; - }; - - t.right = function(i) { - return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]; - }; - - t.clear = function() { - elements = {}; - lefts = {}; - rights = {}; - }; - -} - -})(jQuery); diff --git a/3rdparty/fullcalendar/js/fullcalendar.min.js b/3rdparty/fullcalendar/js/fullcalendar.min.js deleted file mode 100644 index fc06a89a610..00000000000 --- a/3rdparty/fullcalendar/js/fullcalendar.min.js +++ /dev/null @@ -1,113 +0,0 @@ -/* - - FullCalendar v1.5.2 - http://arshaw.com/fullcalendar/ - - Use fullcalendar.css for basic styling. - For event drag & drop, requires jQuery UI draggable. - For event resizing, requires jQuery UI resizable. - - Copyright (c) 2011 Adam Shaw - Dual licensed under the MIT and GPL licenses, located in - MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - - Date: Sun Aug 21 22:06:09 2011 -0700 - -*/ -(function(m,oa){function wb(a){m.extend(true,Ya,a)}function Yb(a,b,e){function d(k){if(E){u();q();ma();S(k)}else f()}function f(){B=b.theme?"ui":"fc";a.addClass("fc");b.isRTL&&a.addClass("fc-rtl");b.theme&&a.addClass("ui-widget");E=m("
    ").prependTo(a);C=new Zb(X,b);(P=C.render())&&a.prepend(P);y(b.defaultView);m(window).resize(na);t()||g()}function g(){setTimeout(function(){!n.start&&t()&&S()},0)}function l(){m(window).unbind("resize",na);C.destroy(); -E.remove();a.removeClass("fc fc-rtl ui-widget")}function j(){return i.offsetWidth!==0}function t(){return m("body")[0].offsetWidth!==0}function y(k){if(!n||k!=n.name){F++;pa();var D=n,Z;if(D){(D.beforeHide||xb)();Za(E,E.height());D.element.hide()}else Za(E,1);E.css("overflow","hidden");if(n=Y[k])n.element.show();else n=Y[k]=new Ja[k](Z=s=m("
    ").appendTo(E),X);D&&C.deactivateButton(D.name);C.activateButton(k);S();E.css("overflow","");D&& -Za(E,1);Z||(n.afterShow||xb)();F--}}function S(k){if(j()){F++;pa();o===oa&&u();var D=false;if(!n.start||k||r=n.end){n.render(r,k||0);fa(true);D=true}else if(n.sizeDirty){n.clearEvents();fa();D=true}else if(n.eventsDirty){n.clearEvents();D=true}n.sizeDirty=false;n.eventsDirty=false;ga(D);W=a.outerWidth();C.updateTitle(n.title);k=new Date;k>=n.start&&k").append(m("
    ");(u=b.header[u])&&m.each(u.split(" "),function(na){na>0&&fa.append("");var ga; -m.each(this.split(","),function(ra,sa){if(sa=="title"){fa.append("

     

    ");ga&&ga.addClass(q+"-corner-right");ga=null}else{var ha;if(a[sa])ha=a[sa];else if(Ja[sa])ha=function(){ma.removeClass(q+"-state-hover");a.changeView(sa)};if(ha){ra=b.theme?jb(b.buttonIcons,sa):null;var da=jb(b.buttonText,sa),ma=m(""+(ra?"":da)+"");if(ma){ma.click(function(){ma.hasClass(q+"-state-disabled")||ha()}).mousedown(function(){ma.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-down")}).mouseup(function(){ma.removeClass(q+"-state-down")}).hover(function(){ma.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-hover")},function(){ma.removeClass(q+"-state-hover").removeClass(q+"-state-down")}).appendTo(fa); -ga||ma.addClass(q+"-corner-left");ga=ma}}}});ga&&ga.addClass(q+"-corner-right")});return fa}function g(u){Q.find("h2").html(u)}function l(u){Q.find("span.fc-button-"+u).addClass(q+"-state-active")}function j(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-active")}function t(u){Q.find("span.fc-button-"+u).addClass(q+"-state-disabled")}function y(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-disabled")}var S=this;S.render=e;S.destroy=d;S.updateTitle=g;S.activateButton=l;S.deactivateButton= -j;S.disableButton=t;S.enableButton=y;var Q=m([]),q}function $b(a,b){function e(c,z){return!ca||cka}function d(c,z){ca=c;ka=z;L=[];c=++qa;G=z=U.length;for(var H=0;Hl;y--)if(S=dc[e.substring(l,y)]){if(f)Q+=S(f,d);l=y-1;break}if(y==l)if(f)Q+=t}}return Q}function Ua(a){return a.end?ec(a.end,a.allDay):ba(N(a.start),1)}function ec(a,b){a=N(a);return b||a.getHours()||a.getMinutes()?ba(a,1):Ka(a)}function fc(a,b){return(b.msLength-a.msLength)*100+(a.event.start-b.event.start)}function Cb(a,b){return a.end>b.start&&a.starte&&td){y=N(d);Q=false}else{y=y;Q=true}f.push({event:j,start:t,end:y,isStart:S,isEnd:Q,msLength:y-t})}}return f.sort(fc)}function ob(a){var b=[],e,d=a.length,f,g,l,j;for(e=0;e=0;e--){d=a[b[e].toLowerCase()];if(d!== -oa)return d}return a[""]}function Qa(a){return a.replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g,"
    ")}function Ib(a){return a.id+"/"+a.className+"/"+a.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig,"")}function qb(a){a.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})}function ab(a){a.children().removeClass("fc-first fc-last").filter(":first-child").addClass("fc-first").end().filter(":last-child").addClass("fc-last")} -function rb(a,b){a.each(function(e,d){d.className=d.className.replace(/^fc-\w*/,"fc-"+lc[b.getDay()])})}function Jb(a,b){var e=a.source||{},d=a.color,f=e.color,g=b("eventColor"),l=a.backgroundColor||d||e.backgroundColor||f||b("eventBackgroundColor")||g;d=a.borderColor||d||e.borderColor||f||b("eventBorderColor")||g;a=a.textColor||e.textColor||b("eventTextColor");b=[];l&&b.push("background-color:"+l);d&&b.push("border-color:"+d);a&&b.push("color:"+a);return b.join(";")}function $a(a,b,e){if(m.isFunction(a))a= -[a];if(a){var d,f;for(d=0;d
    ";w= -m(R).appendTo(a);K=w.find("thead");i=K.find("th");C=w.find("tbody");P=C.find("tr");E=C.find("td");B=E.filter(":first-child");n=P.eq(0).find("div.fc-day-content div");ab(K.add(K.find("tr")));ab(P);P.eq(0).addClass("fc-first");y(E);Y=m("
    ").appendTo(a)}function l(w){var I=w||v==1,R=p.start.getMonth(),V=Ka(new Date),ea,aa,va;I&&i.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);ea.html(ya(aa,$));rb(ea,aa)});E.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);aa.getMonth()== -R?ea.removeClass("fc-other-month"):ea.addClass("fc-other-month");+aa==+V?ea.addClass(la+"-state-highlight fc-today"):ea.removeClass(la+"-state-highlight fc-today");ea.find("div.fc-day-number").text(aa.getDate());I&&rb(ea,aa)});P.each(function(wa,Ga){va=m(Ga);if(wa div"),(ea==v-1?R:I)-Sa(V))}})}function t(w){W=w;M.clear();s=Math.floor(W/F);Va(i.slice(0,-1),s)}function y(w){w.click(S).mousedown(X)}function S(w){if(!L("selectable")){var I=parseInt(this.className.match(/fc\-day(\d+)/)[1]);I=ca(I);c("dayClick",this,I,true,w)}}function Q(w,I,R){R&&r.build();R=N(p.visStart);for(var V=ba(N(R),F),ea=0;ea ";for(A=0;A";x+="  ";for(A=0;A
     
    ";x+=" ";v=m(x).appendTo(a);F=v.find("thead");r=F.find("th").slice(1,-1);J=v.find("tbody");M=J.find("td").slice(0,-1);k=M.find("div.fc-day-content div");D=M.eq(0);Z=D.find("> div");ab(F.add(F.find("tr")));ab(J.add(J.find("tr")));aa=F.find("th:first");va=v.find(".fc-agenda-gutter");ja=m("
    ").appendTo(a); -if(i("allDaySlot")){ia=m("
    ").appendTo(ja);x="
    "+i("allDayText")+"
     
    ";la=m(x).appendTo(ja);$=la.find("tr");q($.find("td"));aa=aa.add(la.find("th:first"));va=va.add(la.find("th.fc-agenda-gutter"));ja.append("
    ")}else ia=m([]);w=m("
    ").appendTo(ja);I=m("
    ").appendTo(w);R=m("
    ").appendTo(I);x="";ta=zb();za=xa(N(ta),bb);xa(ta,La);for(A=tb=0;ta";xa(ta,i("slotMinutes"));tb++}x+="
    "+(!Ea||!Da?s(ta,i("axisFormat")):" ")+"
     
    ";V=m(x).appendTo(I);ea=V.find("div:first");u(V.find("td"));aa=aa.add(V.find("th:first"))}function l(){var h,O,x,A,ta=Ka(new Date);for(h=0;h=0&&xa(O,La+h*i("slotMinutes"));return O}function ua(h){return ba(N(K.visStart),h*Ha+Ia)}function pa(h){return i("allDaySlot")&&!h.row}function U(h){return(h-Math.max(Tb,Sb)+Ba)%Ba*Ha+Ia}function ca(h,O){h=N(h,true);if(O=xa(N(h),bb))return V.height(); -h=i("slotMinutes");O=O.getHours()*60+O.getMinutes()-La;var x=Math.floor(O/h),A=ub[x];if(A===oa)A=ub[x]=V.find("tr:eq("+x+") td div")[0].offsetTop;return Math.max(0,Math.round(A-1+Xa*(O%h/h)))}function ka(){return{left:Ma,right:Ga-vb}}function qa(){return $}function G(h){var O=N(h.start);if(h.allDay)return O;return xa(O,i("defaultEventMinutes"))}function p(h,O){if(O)return N(h);return xa(N(h),i("slotMinutes"))}function L(h,O,x){if(x)i("allDaySlot")&&na(h,ba(N(O),1),true);else c(h,O)}function c(h,O){var x= -i("selectHelper");Na.build();if(x){var A=Ca(h,K.visStart)*Ha+Ia;if(A>=0&&Ata){A.top=ta;A.height=za-ta;A.left+=2;A.width-=5;if(m.isFunction(x)){if(h=x(h,O)){A.position="absolute";A.zIndex=8;wa=m(h).css(A).appendTo(I)}}else{A.isStart=true;A.isEnd=true;wa=m(o({title:"",start:h,end:O,className:["fc-select-helper"],editable:false},A));wa.css("opacity",i("dragOpacity"))}if(wa){u(wa);I.append(wa);Va(wa,A.width,true);Eb(wa,A.height,true)}}}}else ra(h, -O)}function z(){B();if(wa){wa.remove();wa=null}}function H(h){if(h.which==1&&i("selectable")){Y(h);var O;Ra.start(function(x,A){z();if(x&&x.col==A.col&&!pa(x)){A=ma(A);x=ma(x);O=[A,xa(N(A),i("slotMinutes")),x,xa(N(x),i("slotMinutes"))].sort(Gb);c(O[0],O[3])}else O=null},h);m(document).one("mouseup",function(x){Ra.stop();if(O){+O[0]==+O[1]&&T(O[0],false,x);n(O[0],O[3],false,x)}})}}function T(h,O,x){C("dayClick",M[U(h.getDay())],h,O,x)}function X(h,O){Ra.start(function(x){B();if(x)if(pa(x))ga(x.row, -x.col,x.row,x.col);else{x=ma(x);var A=xa(N(x),i("defaultEventMinutes"));ra(x,A)}},O)}function ya(h,O,x){var A=Ra.stop();B();A&&C("drop",h,ma(A),pa(A),O,x)}var K=this;K.renderAgenda=d;K.setWidth=t;K.setHeight=j;K.beforeHide=S;K.afterShow=Q;K.defaultEventEnd=G;K.timePosition=ca;K.dayOfWeekCol=U;K.dateCell=da;K.cellDate=ma;K.cellIsAllDay=pa;K.allDayRow=qa;K.allDayBounds=ka;K.getHoverListener=function(){return Ra};K.colContentLeft=sa;K.colContentRight=ha;K.getDaySegmentContainer=function(){return ia}; -K.getSlotSegmentContainer=function(){return R};K.getMinMinute=function(){return La};K.getMaxMinute=function(){return bb};K.getBodyContent=function(){return I};K.getRowCnt=function(){return 1};K.getColCnt=function(){return Ba};K.getColWidth=function(){return db};K.getSlotHeight=function(){return Xa};K.defaultSelectionEnd=p;K.renderDayOverlay=na;K.renderSelection=L;K.clearSelection=z;K.reportDayClick=T;K.dragStart=X;K.dragStop=ya;Kb.call(K,a,b,e);Lb.call(K);Mb.call(K);sc.call(K);var i=K.opt,C=K.trigger, -P=K.clearEvents,E=K.renderOverlay,B=K.clearOverlays,n=K.reportSelection,Y=K.unselect,W=K.daySelectionMousedown,o=K.slotSegHtml,s=b.formatDate,v,F,r,J,M,k,D,Z,ja,ia,la,$,w,I,R,V,ea,aa,va,wa,Ga,Wb,Ma,db,vb,Xa,Xb,Ba,tb,Na,Ra,cb,ub={},Wa,Tb,Sb,Ub,Ha,Ia,La,bb,Vb;qb(a.addClass("fc-agenda"));Na=new Nb(function(h,O){function x(eb){return Math.max(Ea,Math.min(tc,eb))}var A,ta,za;r.each(function(eb,uc){A=m(uc);ta=A.offset().left;if(eb)za[1]=ta;za=[ta];O[eb]=za});za[1]=ta+A.outerWidth();if(i("allDaySlot")){A= -$;ta=A.offset().top;h[0]=[ta,ta+A.outerHeight()]}for(var Da=I.offset().top,Ea=w.offset().top,tc=Ea+w.outerHeight(),fb=0;fb
    "+Qa(W(o.start,o.end,u("timeFormat")))+"
    "+Qa(o.title)+"
    ";if(s.isEnd&&ga(o))v+="
    =
    "; -v+="";return v}function j(o,s,v){na(o)&&y(o,s,v.isStart);v.isEnd&&ga(o)&&c(o,s,v);da(o,s)}function t(o,s,v){var F=s.find("div.fc-event-time");na(o)&&S(o,s,F);v.isEnd&&ga(o)&&Q(o,s,F);da(o,s)}function y(o,s,v){function F(){if(!M){s.width(r).height("").draggable("option","grid",null);M=true}}var r,J,M=true,k,D=u("isRTL")?-1:1,Z=U(),ja=H(),ia=T(),la=ka();s.draggable({zIndex:9,opacity:u("dragOpacity","month"),revertDuration:u("dragRevertDuration"),start:function($,w){fa("eventDragStart", -s,o,$,w);i(o,s);r=s.width();Z.start(function(I,R,V,ea){B();if(I){J=false;k=ea*D;if(I.row)if(v){if(M){s.width(ja-10);Eb(s,ia*Math.round((o.end?(o.end-o.start)/wc:u("defaultEventMinutes"))/u("slotMinutes")));s.draggable("option","grid",[ja,1]);M=false}}else J=true;else{E(ba(N(o.start),k),ba(Ua(o),k));F()}J=J||M&&!k}else{F();J=true}s.draggable("option","revert",J)},$,"drag")},stop:function($,w){Z.stop();B();fa("eventDragStop",s,o,$,w);if(J){F();s.css("filter","");K(o,s)}else{var I=0;M||(I=Math.round((s.offset().top- -X().offset().top)/ia)*u("slotMinutes")+la-(o.start.getHours()*60+o.start.getMinutes()));C(this,o,k,I,M,$,w)}}})}function S(o,s,v){function F(I){var R=xa(N(o.start),I),V;if(o.end)V=xa(N(o.end),I);v.text(W(R,V,u("timeFormat")))}function r(){if(M){v.css("display","");s.draggable("option","grid",[$,w]);M=false}}var J,M=false,k,D,Z,ja=u("isRTL")?-1:1,ia=U(),la=z(),$=H(),w=T();s.draggable({zIndex:9,scroll:false,grid:[$,w],axis:la==1?"y":false,opacity:u("dragOpacity"),revertDuration:u("dragRevertDuration"), -start:function(I,R){fa("eventDragStart",s,o,I,R);i(o,s);J=s.position();D=Z=0;ia.start(function(V,ea,aa,va){s.draggable("option","revert",!V);B();if(V){k=va*ja;if(u("allDaySlot")&&!V.row){if(!M){M=true;v.hide();s.draggable("option","grid",null)}E(ba(N(o.start),k),ba(Ua(o),k))}else r()}},I,"drag")},drag:function(I,R){D=Math.round((R.position.top-J.top)/w)*u("slotMinutes");if(D!=Z){M||F(D);Z=D}},stop:function(I,R){var V=ia.stop();B();fa("eventDragStop",s,o,I,R);if(V&&(k||D||M))C(this,o,k,M?0:D,M,I,R); -else{r();s.css("filter","");s.css(J);F(0);K(o,s)}}})}function Q(o,s,v){var F,r,J=T();s.resizable({handles:{s:"div.ui-resizable-s"},grid:J,start:function(M,k){F=r=0;i(o,s);s.css("z-index",9);fa("eventResizeStart",this,o,M,k)},resize:function(M,k){F=Math.round((Math.max(J,s.height())-k.originalSize.height)/J);if(F!=r){v.text(W(o.start,!F&&!o.end?null:xa(ra(o),u("slotMinutes")*F),u("timeFormat")));r=F}},stop:function(M,k){fa("eventResizeStop",this,o,M,k);if(F)P(this,o,0,u("slotMinutes")*F,M,k);else{s.css("z-index", -8);K(o,s)}}})}var q=this;q.renderEvents=a;q.compileDaySegs=e;q.clearEvents=b;q.slotSegHtml=l;q.bindDaySeg=j;Qb.call(q);var u=q.opt,fa=q.trigger,na=q.isEventDraggable,ga=q.isEventResizable,ra=q.eventEnd,sa=q.reportEvents,ha=q.reportEventClear,da=q.eventElementHandlers,ma=q.setHeight,ua=q.getDaySegmentContainer,pa=q.getSlotSegmentContainer,U=q.getHoverListener,ca=q.getMaxMinute,ka=q.getMinMinute,qa=q.timePosition,G=q.colContentLeft,p=q.colContentRight,L=q.renderDaySegs,c=q.resizableDayEvent,z=q.getColCnt, -H=q.getColWidth,T=q.getSlotHeight,X=q.getBodyContent,ya=q.reportEventElement,K=q.showEvents,i=q.hideEvents,C=q.eventDrop,P=q.eventResize,E=q.renderDayOverlay,B=q.clearOverlays,n=q.calendar,Y=n.formatDate,W=n.formatDates}function vc(a){var b,e,d,f,g,l;for(b=a.length-1;b>0;b--){f=a[b];for(e=0;e"),B=z(),n=i.length,Y;E[0].innerHTML=e(i);E=E.children();B.append(E);d(i,E);l(i);j(i);t(i);Q(i,S(y()));E=[];for(B=0;B
    ";if(!n.allDay&&B.isStart)k+=""+Qa(T(n.start,n.end,fa("timeFormat")))+"";k+=""+Qa(n.title)+"
    ";if(B.isEnd&&ra(n))k+="
       
    ";k+="";B.left=r;B.outerWidth=J-r;B.startCol=v;B.endCol=F+1}return k}function d(i,C){var P,E=i.length,B,n,Y;for(P=0;P div");return P}function S(i){var C,P=i.length,E=[];for(C=0;C"));j[0].parentNode!=l[0]&&j.appendTo(l);d.push(j.css(g).show());return j}function b(){for(var g;g=d.shift();)f.push(g.hide().unbind())}var e=this;e.renderOverlay=a;e.clearOverlays=b;var d=[],f=[]}function Nb(a){var b=this,e,d;b.build=function(){e=[];d=[];a(e,d)};b.cell=function(f,g){var l=e.length,j=d.length, -t,y=-1,S=-1;for(t=0;t=e[t][0]&&g=d[t][0]&&f=0&&S>=0?{row:y,col:S}:null};b.rect=function(f,g,l,j,t){t=t.offset();return{top:e[f][0]-t.top,left:d[g][0]-t.left,width:d[j][1]-d[g][0],height:e[l][1]-e[f][0]}}}function Ob(a){function b(j){j=a.cell(j.pageX,j.pageY);if(!j!=!l||j&&(j.row!=l.row||j.col!=l.col)){if(j){g||(g=j);f(j,g,j.row-g.row,j.col-g.col)}else f(j,g);l=j}}var e=this,d,f,g,l;e.start=function(j,t,y){f=j;g=l=null; -a.build();b(t);d=y||"mousemove";m(document).bind(d,b)};e.stop=function(){m(document).unbind(d,b);return l}}function Pb(a){function b(l){return d[l]=d[l]||a(l)}var e=this,d={},f={},g={};e.left=function(l){return f[l]=f[l]===oa?b(l).position().left:f[l]};e.right=function(l){return g[l]=g[l]===oa?e.left(l)+b(l).width():g[l]};e.clear=function(){d={};f={};g={}}}var Ya={defaultView:"month",aspectRatio:1.35,header:{left:"title",center:"",right:"today prev,next"},weekends:true,allDayDefault:true,ignoreTimezone:true, -lazyFetching:true,startParam:"start",endParam:"end",titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '—'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},columnFormat:{month:"ddd",week:"ddd M/d",day:"dddd M/d"},timeFormat:{"":"h(:mm)t"},isRTL:false,firstDay:0,monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday", -"Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],buttonText:{prev:" ◄ ",next:" ► ",prevYear:" << ",nextYear:" >> ",today:"today",month:"month",week:"week",day:"day"},theme:false,buttonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e"},unselectAuto:true,dropAccept:"*"},xc={header:{left:"next,prev today",center:"",right:"title"},buttonText:{prev:" ► ",next:" ◄ ", -prevYear:" >> ",nextYear:" << "},buttonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w"}},Aa=m.fullCalendar={version:"1.5.2"},Ja=Aa.views={};m.fn.fullCalendar=function(a){if(typeof a=="string"){var b=Array.prototype.slice.call(arguments,1),e;this.each(function(){var f=m.data(this,"fullCalendar");if(f&&m.isFunction(f[a])){f=f[a].apply(f,b);if(e===oa)e=f;a=="destroy"&&m.removeData(this,"fullCalendar")}});if(e!==oa)return e;return this}var d=a.eventSources||[]; -delete a.eventSources;if(a.events){d.push(a.events);delete a.events}a=m.extend(true,{},Ya,a.isRTL||a.isRTL===oa&&Ya.isRTL?xc:{},a);this.each(function(f,g){f=m(g);g=new Yb(f,a,d);f.data("fullCalendar",g);g.render()});return this};Aa.sourceNormalizers=[];Aa.sourceFetchers=[];var ac={dataType:"json",cache:false},bc=1;Aa.addDays=ba;Aa.cloneDate=N;Aa.parseDate=kb;Aa.parseISO8601=Bb;Aa.parseTime=mb;Aa.formatDate=Oa;Aa.formatDates=ib;var lc=["sun","mon","tue","wed","thu","fri","sat"],Ab=864E5,cc=36E5,wc= -6E4,dc={s:function(a){return a.getSeconds()},ss:function(a){return Pa(a.getSeconds())},m:function(a){return a.getMinutes()},mm:function(a){return Pa(a.getMinutes())},h:function(a){return a.getHours()%12||12},hh:function(a){return Pa(a.getHours()%12||12)},H:function(a){return a.getHours()},HH:function(a){return Pa(a.getHours())},d:function(a){return a.getDate()},dd:function(a){return Pa(a.getDate())},ddd:function(a,b){return b.dayNamesShort[a.getDay()]},dddd:function(a,b){return b.dayNames[a.getDay()]}, -M:function(a){return a.getMonth()+1},MM:function(a){return Pa(a.getMonth()+1)},MMM:function(a,b){return b.monthNamesShort[a.getMonth()]},MMMM:function(a,b){return b.monthNames[a.getMonth()]},yy:function(a){return(a.getFullYear()+"").substring(2)},yyyy:function(a){return a.getFullYear()},t:function(a){return a.getHours()<12?"a":"p"},tt:function(a){return a.getHours()<12?"am":"pm"},T:function(a){return a.getHours()<12?"A":"P"},TT:function(a){return a.getHours()<12?"AM":"PM"},u:function(a){return Oa(a, -"yyyy-MM-dd'T'HH:mm:ss'Z'")},S:function(a){a=a.getDate();if(a>10&&a<20)return"th";return["st","nd","rd"][a%10-1]||"th"}};Aa.applyAll=$a;Ja.month=mc;Ja.basicWeek=nc;Ja.basicDay=oc;wb({weekMode:"fixed"});Ja.agendaWeek=qc;Ja.agendaDay=rc;wb({allDaySlot:true,allDayText:"all-day",firstHour:6,slotMinutes:30,defaultEventMinutes:120,axisFormat:"h(:mm)tt",timeFormat:{agenda:"h:mm{ - h:mm}"},dragOpacity:{agenda:0.5},minTime:0,maxTime:24})})(jQuery); diff --git a/3rdparty/fullcalendar/js/gcal.js b/3rdparty/fullcalendar/js/gcal.js deleted file mode 100644 index 709e25cb262..00000000000 --- a/3rdparty/fullcalendar/js/gcal.js +++ /dev/null @@ -1,112 +0,0 @@ -/* - * FullCalendar v1.5.2 Google Calendar Plugin - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - -(function($) { - - -var fc = $.fullCalendar; -var formatDate = fc.formatDate; -var parseISO8601 = fc.parseISO8601; -var addDays = fc.addDays; -var applyAll = fc.applyAll; - - -fc.sourceNormalizers.push(function(sourceOptions) { - if (sourceOptions.dataType == 'gcal' || - sourceOptions.dataType === undefined && - (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { - sourceOptions.dataType = 'gcal'; - if (sourceOptions.editable === undefined) { - sourceOptions.editable = false; - } - } -}); - - -fc.sourceFetchers.push(function(sourceOptions, start, end) { - if (sourceOptions.dataType == 'gcal') { - return transformOptions(sourceOptions, start, end); - } -}); - - -function transformOptions(sourceOptions, start, end) { - - var success = sourceOptions.success; - var data = $.extend({}, sourceOptions.data || {}, { - 'start-min': formatDate(start, 'u'), - 'start-max': formatDate(end, 'u'), - 'singleevents': true, - 'max-results': 9999 - }); - - var ctz = sourceOptions.currentTimezone; - if (ctz) { - data.ctz = ctz = ctz.replace(' ', '_'); - } - - return $.extend({}, sourceOptions, { - url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', - dataType: 'jsonp', - data: data, - startParam: false, - endParam: false, - success: function(data) { - var events = []; - if (data.feed.entry) { - $.each(data.feed.entry, function(i, entry) { - var startStr = entry['gd$when'][0]['startTime']; - var start = parseISO8601(startStr, true); - var end = parseISO8601(entry['gd$when'][0]['endTime'], true); - var allDay = startStr.indexOf('T') == -1; - var url; - $.each(entry.link, function(i, link) { - if (link.type == 'text/html') { - url = link.href; - if (ctz) { - url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; - } - } - }); - if (allDay) { - addDays(end, -1); // make inclusive - } - events.push({ - id: entry['gCal$uid']['value'], - title: entry['title']['$t'], - url: url, - start: start, - end: end, - allDay: allDay, - location: entry['gd$where'][0]['valueString'], - description: entry['content']['$t'] - }); - }); - } - var args = [events].concat(Array.prototype.slice.call(arguments, 1)); - var res = applyAll(success, this, args); - if ($.isArray(res)) { - return res; - } - return events; - } - }); - -} - - -// legacy -fc.gcalFeed = function(url, sourceOptions) { - return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); -}; - - -})(jQuery); -- GitLab From c77fa4214306ad399e9d54b2e017354dcdcc2849 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sun, 22 Apr 2012 21:14:06 +0200 Subject: [PATCH 232/430] add new files of fullcalendar 1.5.3 --- 3rdparty/fullcalendar/GPL-LICENSE.txt | 278 + 3rdparty/fullcalendar/MIT-LICENSE.txt | 20 + 3rdparty/fullcalendar/fullcalendar.css | 618 +++ 3rdparty/fullcalendar/fullcalendar.js | 5224 ++++++++++++++++++ 3rdparty/fullcalendar/fullcalendar.min.js | 114 + 3rdparty/fullcalendar/fullcalendar.print.css | 61 + 3rdparty/fullcalendar/gcal.js | 112 + 7 files changed, 6427 insertions(+) create mode 100644 3rdparty/fullcalendar/GPL-LICENSE.txt create mode 100644 3rdparty/fullcalendar/MIT-LICENSE.txt create mode 100644 3rdparty/fullcalendar/fullcalendar.css create mode 100644 3rdparty/fullcalendar/fullcalendar.js create mode 100644 3rdparty/fullcalendar/fullcalendar.min.js create mode 100644 3rdparty/fullcalendar/fullcalendar.print.css create mode 100644 3rdparty/fullcalendar/gcal.js diff --git a/3rdparty/fullcalendar/GPL-LICENSE.txt b/3rdparty/fullcalendar/GPL-LICENSE.txt new file mode 100644 index 00000000000..11dddd00ef0 --- /dev/null +++ b/3rdparty/fullcalendar/GPL-LICENSE.txt @@ -0,0 +1,278 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. diff --git a/3rdparty/fullcalendar/MIT-LICENSE.txt b/3rdparty/fullcalendar/MIT-LICENSE.txt new file mode 100644 index 00000000000..46d47544964 --- /dev/null +++ b/3rdparty/fullcalendar/MIT-LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2009 Adam Shaw + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/3rdparty/fullcalendar/fullcalendar.css b/3rdparty/fullcalendar/fullcalendar.css new file mode 100644 index 00000000000..04f118493a4 --- /dev/null +++ b/3rdparty/fullcalendar/fullcalendar.css @@ -0,0 +1,618 @@ +/* + * FullCalendar v1.5.3 Stylesheet + * + * Copyright (c) 2011 Adam Shaw + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Mon Feb 6 22:40:40 2012 -0800 + * + */ + + +.fc { + direction: ltr; + text-align: left; + } + +.fc table { + border-collapse: collapse; + border-spacing: 0; + } + +html .fc, +.fc table { + font-size: 1em; + } + +.fc td, +.fc th { + padding: 0; + vertical-align: top; + } + + + +/* Header +------------------------------------------------------------------------*/ + +.fc-header td { + white-space: nowrap; + } + +.fc-header-left { + width: 25%; + text-align: left; + } + +.fc-header-center { + text-align: center; + } + +.fc-header-right { + width: 25%; + text-align: right; + } + +.fc-header-title { + display: inline-block; + vertical-align: top; + } + +.fc-header-title h2 { + margin-top: 0; + white-space: nowrap; + } + +.fc .fc-header-space { + padding-left: 10px; + } + +.fc-header .fc-button { + margin-bottom: 1em; + vertical-align: top; + } + +/* buttons edges butting together */ + +.fc-header .fc-button { + margin-right: -1px; + } + +.fc-header .fc-corner-right { + margin-right: 1px; /* back to normal */ + } + +.fc-header .ui-corner-right { + margin-right: 0; /* back to normal */ + } + +/* button layering (for border precedence) */ + +.fc-header .fc-state-hover, +.fc-header .ui-state-hover { + z-index: 2; + } + +.fc-header .fc-state-down { + z-index: 3; + } + +.fc-header .fc-state-active, +.fc-header .ui-state-active { + z-index: 4; + } + + + +/* Content +------------------------------------------------------------------------*/ + +.fc-content { + clear: both; + } + +.fc-view { + width: 100%; /* needed for view switching (when view is absolute) */ + overflow: hidden; + } + + + +/* Cell Styles +------------------------------------------------------------------------*/ + +.fc-widget-header, /* , usually */ +.fc-widget-content { /* , usually */ + border: 1px solid #ccc; + } + +.fc-state-highlight { /* today cell */ /* TODO: add .fc-today to */ + background: #ffc; + } + +.fc-cell-overlay { /* semi-transparent rectangle while dragging */ + background: #9cf; + opacity: .2; + filter: alpha(opacity=20); /* for IE */ + } + + + +/* Buttons +------------------------------------------------------------------------*/ + +.fc-button { + position: relative; + display: inline-block; + cursor: pointer; + } + +.fc-state-default { /* non-theme */ + border-style: solid; + border-width: 1px 0; + } + +.fc-button-inner { + position: relative; + float: left; + overflow: hidden; + } + +.fc-state-default .fc-button-inner { /* non-theme */ + border-style: solid; + border-width: 0 1px; + } + +.fc-button-content { + position: relative; + float: left; + height: 1.9em; + line-height: 1.9em; + padding: 0 .6em; + white-space: nowrap; + } + +/* icon (for jquery ui) */ + +.fc-button-content .fc-icon-wrap { + position: relative; + float: left; + top: 50%; + } + +.fc-button-content .ui-icon { + position: relative; + float: left; + margin-top: -50%; + *margin-top: 0; + *top: -50%; + } + +/* gloss effect */ + +.fc-state-default .fc-button-effect { + position: absolute; + top: 50%; + left: 0; + } + +.fc-state-default .fc-button-effect span { + position: absolute; + top: -100px; + left: 0; + width: 500px; + height: 100px; + border-width: 100px 0 0 1px; + border-style: solid; + border-color: #fff; + background: #444; + opacity: .09; + filter: alpha(opacity=9); + } + +/* button states (determines colors) */ + +.fc-state-default, +.fc-state-default .fc-button-inner { + border-style: solid; + border-color: #ccc #bbb #aaa; + background: #F3F3F3; + color: #000; + } + +.fc-state-hover, +.fc-state-hover .fc-button-inner { + border-color: #999; + } + +.fc-state-down, +.fc-state-down .fc-button-inner { + border-color: #555; + background: #777; + } + +.fc-state-active, +.fc-state-active .fc-button-inner { + border-color: #555; + background: #777; + color: #fff; + } + +.fc-state-disabled, +.fc-state-disabled .fc-button-inner { + color: #999; + border-color: #ddd; + } + +.fc-state-disabled { + cursor: default; + } + +.fc-state-disabled .fc-button-effect { + display: none; + } + + + +/* Global Event Styles +------------------------------------------------------------------------*/ + +.fc-event { + border-style: solid; + border-width: 0; + font-size: .85em; + cursor: default; + } + +a.fc-event, +.fc-event-draggable { + cursor: pointer; + } + +a.fc-event { + text-decoration: none; + } + +.fc-rtl .fc-event { + text-align: right; + } + +.fc-event-skin { + border-color: #36c; /* default BORDER color */ + background-color: #36c; /* default BACKGROUND color */ + color: #fff; /* default TEXT color */ + } + +.fc-event-inner { + position: relative; + width: 100%; + height: 100%; + border-style: solid; + border-width: 0; + overflow: hidden; + } + +.fc-event-time, +.fc-event-title { + padding: 0 1px; + } + +.fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/ + display: block; + position: absolute; + z-index: 99999; + overflow: hidden; /* hacky spaces (IE6/7) */ + font-size: 300%; /* */ + line-height: 50%; /* */ + } + + + +/* Horizontal Events +------------------------------------------------------------------------*/ + +.fc-event-hori { + border-width: 1px 0; + margin-bottom: 1px; + } + +/* resizable */ + +.fc-event-hori .ui-resizable-e { + top: 0 !important; /* importants override pre jquery ui 1.7 styles */ + right: -3px !important; + width: 7px !important; + height: 100% !important; + cursor: e-resize; + } + +.fc-event-hori .ui-resizable-w { + top: 0 !important; + left: -3px !important; + width: 7px !important; + height: 100% !important; + cursor: w-resize; + } + +.fc-event-hori .ui-resizable-handle { + _padding-bottom: 14px; /* IE6 had 0 height */ + } + + + +/* Fake Rounded Corners (for buttons and events) +------------------------------------------------------------*/ + +.fc-corner-left { + margin-left: 1px; + } + +.fc-corner-left .fc-button-inner, +.fc-corner-left .fc-event-inner { + margin-left: -1px; + } + +.fc-corner-right { + margin-right: 1px; + } + +.fc-corner-right .fc-button-inner, +.fc-corner-right .fc-event-inner { + margin-right: -1px; + } + +.fc-corner-top { + margin-top: 1px; + } + +.fc-corner-top .fc-event-inner { + margin-top: -1px; + } + +.fc-corner-bottom { + margin-bottom: 1px; + } + +.fc-corner-bottom .fc-event-inner { + margin-bottom: -1px; + } + + + +/* Fake Rounded Corners SPECIFICALLY FOR EVENTS +-----------------------------------------------------------------*/ + +.fc-corner-left .fc-event-inner { + border-left-width: 1px; + } + +.fc-corner-right .fc-event-inner { + border-right-width: 1px; + } + +.fc-corner-top .fc-event-inner { + border-top-width: 1px; + } + +.fc-corner-bottom .fc-event-inner { + border-bottom-width: 1px; + } + + + +/* Reusable Separate-border Table +------------------------------------------------------------*/ + +table.fc-border-separate { + border-collapse: separate; + } + +.fc-border-separate th, +.fc-border-separate td { + border-width: 1px 0 0 1px; + } + +.fc-border-separate th.fc-last, +.fc-border-separate td.fc-last { + border-right-width: 1px; + } + +.fc-border-separate tr.fc-last th, +.fc-border-separate tr.fc-last td { + border-bottom-width: 1px; + } + +.fc-border-separate tbody tr.fc-first td, +.fc-border-separate tbody tr.fc-first th { + border-top-width: 0; + } + + + +/* Month View, Basic Week View, Basic Day View +------------------------------------------------------------------------*/ + +.fc-grid th { + text-align: center; + } + +.fc-grid .fc-day-number { + float: right; + padding: 0 2px; + } + +.fc-grid .fc-other-month .fc-day-number { + opacity: 0.3; + filter: alpha(opacity=30); /* for IE */ + /* opacity with small font can sometimes look too faded + might want to set the 'color' property instead + making day-numbers bold also fixes the problem */ + } + +.fc-grid .fc-day-content { + clear: both; + padding: 2px 2px 1px; /* distance between events and day edges */ + } + +/* event styles */ + +.fc-grid .fc-event-time { + font-weight: bold; + } + +/* right-to-left */ + +.fc-rtl .fc-grid .fc-day-number { + float: left; + } + +.fc-rtl .fc-grid .fc-event-time { + float: right; + } + + + +/* Agenda Week View, Agenda Day View +------------------------------------------------------------------------*/ + +.fc-agenda table { + border-collapse: separate; + } + +.fc-agenda-days th { + text-align: center; + } + +.fc-agenda .fc-agenda-axis { + width: 50px; + padding: 0 4px; + vertical-align: middle; + text-align: right; + white-space: nowrap; + font-weight: normal; + } + +.fc-agenda .fc-day-content { + padding: 2px 2px 1px; + } + +/* make axis border take precedence */ + +.fc-agenda-days .fc-agenda-axis { + border-right-width: 1px; + } + +.fc-agenda-days .fc-col0 { + border-left-width: 0; + } + +/* all-day area */ + +.fc-agenda-allday th { + border-width: 0 1px; + } + +.fc-agenda-allday .fc-day-content { + min-height: 34px; /* TODO: doesnt work well in quirksmode */ + _height: 34px; + } + +/* divider (between all-day and slots) */ + +.fc-agenda-divider-inner { + height: 2px; + overflow: hidden; + } + +.fc-widget-header .fc-agenda-divider-inner { + background: #eee; + } + +/* slot rows */ + +.fc-agenda-slots th { + border-width: 1px 1px 0; + } + +.fc-agenda-slots td { + border-width: 1px 0 0; + background: none; + } + +.fc-agenda-slots td div { + height: 20px; + } + +.fc-agenda-slots tr.fc-slot0 th, +.fc-agenda-slots tr.fc-slot0 td { + border-top-width: 0; + } + +.fc-agenda-slots tr.fc-minor th, +.fc-agenda-slots tr.fc-minor td { + border-top-style: dotted; + } + +.fc-agenda-slots tr.fc-minor th.ui-widget-header { + *border-top-style: solid; /* doesn't work with background in IE6/7 */ + } + + + +/* Vertical Events +------------------------------------------------------------------------*/ + +.fc-event-vert { + border-width: 0 1px; + } + +.fc-event-vert .fc-event-head, +.fc-event-vert .fc-event-content { + position: relative; + z-index: 2; + width: 100%; + overflow: hidden; + } + +.fc-event-vert .fc-event-time { + white-space: nowrap; + font-size: 10px; + } + +.fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */ + position: absolute; + z-index: 1; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: #fff; + opacity: .3; + filter: alpha(opacity=30); + } + +.fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */ +.fc-select-helper .fc-event-bg { + display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */ + } + +/* resizable */ + +.fc-event-vert .ui-resizable-s { + bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */ + width: 100% !important; + height: 8px !important; + overflow: hidden !important; + line-height: 8px !important; + font-size: 11px !important; + font-family: monospace; + text-align: center; + cursor: s-resize; + } + +.fc-agenda .ui-resizable-resizing { /* TODO: better selector */ + _overflow: hidden; + } + + diff --git a/3rdparty/fullcalendar/fullcalendar.js b/3rdparty/fullcalendar/fullcalendar.js new file mode 100644 index 00000000000..779a313c761 --- /dev/null +++ b/3rdparty/fullcalendar/fullcalendar.js @@ -0,0 +1,5224 @@ +/** + * @preserve + * FullCalendar v1.5.3 + * http://arshaw.com/fullcalendar/ + * + * Use fullcalendar.css for basic styling. + * For event drag & drop, requires jQuery UI draggable. + * For event resizing, requires jQuery UI resizable. + * + * Copyright (c) 2011 Adam Shaw + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Mon Feb 6 22:40:40 2012 -0800 + * + */ + +(function($, undefined) { + + +var defaults = { + + // display + defaultView: 'month', + aspectRatio: 1.35, + header: { + left: 'title', + center: '', + right: 'today prev,next' + }, + weekends: true, + + // editing + //editable: false, + //disableDragging: false, + //disableResizing: false, + + allDayDefault: true, + ignoreTimezone: true, + + // event ajax + lazyFetching: true, + startParam: 'start', + endParam: 'end', + + // time formats + titleFormat: { + month: 'MMMM yyyy', + week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", + day: 'dddd, MMM d, yyyy' + }, + columnFormat: { + month: 'ddd', + week: 'ddd M/d', + day: 'dddd M/d' + }, + timeFormat: { // for event elements + '': 'h(:mm)t' // default + }, + + // locale + isRTL: false, + firstDay: 0, + monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], + monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], + dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], + dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], + buttonText: { + prev: ' ◄ ', + next: ' ► ', + prevYear: ' << ', + nextYear: ' >> ', + today: 'today', + month: 'month', + week: 'week', + day: 'day' + }, + + // jquery-ui theming + theme: false, + buttonIcons: { + prev: 'circle-triangle-w', + next: 'circle-triangle-e' + }, + + //selectable: false, + unselectAuto: true, + + dropAccept: '*' + +}; + +// right-to-left defaults +var rtlDefaults = { + header: { + left: 'next,prev today', + center: '', + right: 'title' + }, + buttonText: { + prev: ' ► ', + next: ' ◄ ', + prevYear: ' >> ', + nextYear: ' << ' + }, + buttonIcons: { + prev: 'circle-triangle-e', + next: 'circle-triangle-w' + } +}; + + + +var fc = $.fullCalendar = { version: "1.5.3" }; +var fcViews = fc.views = {}; + + +$.fn.fullCalendar = function(options) { + + + // method calling + if (typeof options == 'string') { + var args = Array.prototype.slice.call(arguments, 1); + var res; + this.each(function() { + var calendar = $.data(this, 'fullCalendar'); + if (calendar && $.isFunction(calendar[options])) { + var r = calendar[options].apply(calendar, args); + if (res === undefined) { + res = r; + } + if (options == 'destroy') { + $.removeData(this, 'fullCalendar'); + } + } + }); + if (res !== undefined) { + return res; + } + return this; + } + + + // would like to have this logic in EventManager, but needs to happen before options are recursively extended + var eventSources = options.eventSources || []; + delete options.eventSources; + if (options.events) { + eventSources.push(options.events); + delete options.events; + } + + + options = $.extend(true, {}, + defaults, + (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, + options + ); + + + this.each(function(i, _element) { + var element = $(_element); + var calendar = new Calendar(element, options, eventSources); + element.data('fullCalendar', calendar); // TODO: look into memory leak implications + calendar.render(); + }); + + + return this; + +}; + + +// function for adding/overriding defaults +function setDefaults(d) { + $.extend(true, defaults, d); +} + + + + +function Calendar(element, options, eventSources) { + var t = this; + + + // exports + t.options = options; + t.render = render; + t.destroy = destroy; + t.refetchEvents = refetchEvents; + t.reportEvents = reportEvents; + t.reportEventChange = reportEventChange; + t.rerenderEvents = rerenderEvents; + t.changeView = changeView; + t.select = select; + t.unselect = unselect; + t.prev = prev; + t.next = next; + t.prevYear = prevYear; + t.nextYear = nextYear; + t.today = today; + t.gotoDate = gotoDate; + t.incrementDate = incrementDate; + t.formatDate = function(format, date) { return formatDate(format, date, options) }; + t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; + t.getDate = getDate; + t.getView = getView; + t.option = option; + t.trigger = trigger; + + + // imports + EventManager.call(t, options, eventSources); + var isFetchNeeded = t.isFetchNeeded; + var fetchEvents = t.fetchEvents; + + + // locals + var _element = element[0]; + var header; + var headerElement; + var content; + var tm; // for making theme classes + var currentView; + var viewInstances = {}; + var elementOuterWidth; + var suggestedViewHeight; + var absoluteViewElement; + var resizeUID = 0; + var ignoreWindowResize = 0; + var date = new Date(); + var events = []; + var _dragElement; + + + + /* Main Rendering + -----------------------------------------------------------------------------*/ + + + setYMD(date, options.year, options.month, options.date); + + + function render(inc) { + if (!content) { + initialRender(); + }else{ + calcSize(); + markSizesDirty(); + markEventsDirty(); + renderView(inc); + } + } + + + function initialRender() { + tm = options.theme ? 'ui' : 'fc'; + element.addClass('fc'); + if (options.isRTL) { + element.addClass('fc-rtl'); + } + if (options.theme) { + element.addClass('ui-widget'); + } + content = $("
    ") + .prependTo(element); + header = new Header(t, options); + headerElement = header.render(); + if (headerElement) { + element.prepend(headerElement); + } + changeView(options.defaultView); + $(window).resize(windowResize); + // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize + if (!bodyVisible()) { + lateRender(); + } + } + + + // called when we know the calendar couldn't be rendered when it was initialized, + // but we think it's ready now + function lateRender() { + setTimeout(function() { // IE7 needs this so dimensions are calculated correctly + if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once + renderView(); + } + },0); + } + + + function destroy() { + $(window).unbind('resize', windowResize); + header.destroy(); + content.remove(); + element.removeClass('fc fc-rtl ui-widget'); + } + + + + function elementVisible() { + return _element.offsetWidth !== 0; + } + + + function bodyVisible() { + return $('body')[0].offsetWidth !== 0; + } + + + + /* View Rendering + -----------------------------------------------------------------------------*/ + + // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) + + function changeView(newViewName) { + if (!currentView || newViewName != currentView.name) { + ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached + + unselect(); + + var oldView = currentView; + var newViewElement; + + if (oldView) { + (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) + setMinHeight(content, content.height()); + oldView.element.hide(); + }else{ + setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated + } + content.css('overflow', 'hidden'); + + currentView = viewInstances[newViewName]; + if (currentView) { + currentView.element.show(); + }else{ + currentView = viewInstances[newViewName] = new fcViews[newViewName]( + newViewElement = absoluteViewElement = + $("
    ") + .appendTo(content), + t // the calendar object + ); + } + + if (oldView) { + header.deactivateButton(oldView.name); + } + header.activateButton(newViewName); + + renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null + + content.css('overflow', ''); + if (oldView) { + setMinHeight(content, 1); + } + + if (!newViewElement) { + (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) + } + + ignoreWindowResize--; + } + } + + + + function renderView(inc) { + if (elementVisible()) { + ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached + + unselect(); + + if (suggestedViewHeight === undefined) { + calcSize(); + } + + var forceEventRender = false; + if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { + // view must render an entire new date range (and refetch/render events) + currentView.render(date, inc || 0); // responsible for clearing events + setSize(true); + forceEventRender = true; + } + else if (currentView.sizeDirty) { + // view must resize (and rerender events) + currentView.clearEvents(); + setSize(); + forceEventRender = true; + } + else if (currentView.eventsDirty) { + currentView.clearEvents(); + forceEventRender = true; + } + currentView.sizeDirty = false; + currentView.eventsDirty = false; + updateEvents(forceEventRender); + + elementOuterWidth = element.outerWidth(); + + header.updateTitle(currentView.title); + var today = new Date(); + if (today >= currentView.start && today < currentView.end) { + header.disableButton('today'); + }else{ + header.enableButton('today'); + } + + ignoreWindowResize--; + currentView.trigger('viewDisplay', _element); + } + } + + + + /* Resizing + -----------------------------------------------------------------------------*/ + + + function updateSize() { + markSizesDirty(); + if (elementVisible()) { + calcSize(); + setSize(); + unselect(); + currentView.clearEvents(); + currentView.renderEvents(events); + currentView.sizeDirty = false; + } + } + + + function markSizesDirty() { + $.each(viewInstances, function(i, inst) { + inst.sizeDirty = true; + }); + } + + + function calcSize() { + if (options.contentHeight) { + suggestedViewHeight = options.contentHeight; + } + else if (options.height) { + suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); + } + else { + suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); + } + } + + + function setSize(dateChanged) { // todo: dateChanged? + ignoreWindowResize++; + currentView.setHeight(suggestedViewHeight, dateChanged); + if (absoluteViewElement) { + absoluteViewElement.css('position', 'relative'); + absoluteViewElement = null; + } + currentView.setWidth(content.width(), dateChanged); + ignoreWindowResize--; + } + + + function windowResize() { + if (!ignoreWindowResize) { + if (currentView.start) { // view has already been rendered + var uid = ++resizeUID; + setTimeout(function() { // add a delay + if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { + if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { + ignoreWindowResize++; // in case the windowResize callback changes the height + updateSize(); + currentView.trigger('windowResize', _element); + ignoreWindowResize--; + } + } + }, 200); + }else{ + // calendar must have been initialized in a 0x0 iframe that has just been resized + lateRender(); + } + } + } + + + + /* Event Fetching/Rendering + -----------------------------------------------------------------------------*/ + + + // fetches events if necessary, rerenders events if necessary (or if forced) + function updateEvents(forceRender) { + if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { + refetchEvents(); + } + else if (forceRender) { + rerenderEvents(); + } + } + + + function refetchEvents() { + fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents + } + + + // called when event data arrives + function reportEvents(_events) { + events = _events; + rerenderEvents(); + } + + + // called when a single event's data has been changed + function reportEventChange(eventID) { + rerenderEvents(eventID); + } + + + // attempts to rerenderEvents + function rerenderEvents(modifiedEventID) { + markEventsDirty(); + if (elementVisible()) { + currentView.clearEvents(); + currentView.renderEvents(events, modifiedEventID); + currentView.eventsDirty = false; + } + } + + + function markEventsDirty() { + $.each(viewInstances, function(i, inst) { + inst.eventsDirty = true; + }); + } + + + + /* Selection + -----------------------------------------------------------------------------*/ + + + function select(start, end, allDay) { + currentView.select(start, end, allDay===undefined ? true : allDay); + } + + + function unselect() { // safe to be called before renderView + if (currentView) { + currentView.unselect(); + } + } + + + + /* Date + -----------------------------------------------------------------------------*/ + + + function prev() { + renderView(-1); + } + + + function next() { + renderView(1); + } + + + function prevYear() { + addYears(date, -1); + renderView(); + } + + + function nextYear() { + addYears(date, 1); + renderView(); + } + + + function today() { + date = new Date(); + renderView(); + } + + + function gotoDate(year, month, dateOfMonth) { + if (year instanceof Date) { + date = cloneDate(year); // provided 1 argument, a Date + }else{ + setYMD(date, year, month, dateOfMonth); + } + renderView(); + } + + + function incrementDate(years, months, days) { + if (years !== undefined) { + addYears(date, years); + } + if (months !== undefined) { + addMonths(date, months); + } + if (days !== undefined) { + addDays(date, days); + } + renderView(); + } + + + function getDate() { + return cloneDate(date); + } + + + + /* Misc + -----------------------------------------------------------------------------*/ + + + function getView() { + return currentView; + } + + + function option(name, value) { + if (value === undefined) { + return options[name]; + } + if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { + options[name] = value; + updateSize(); + } + } + + + function trigger(name, thisObj) { + if (options[name]) { + return options[name].apply( + thisObj || _element, + Array.prototype.slice.call(arguments, 2) + ); + } + } + + + + /* External Dragging + ------------------------------------------------------------------------*/ + + if (options.droppable) { + $(document) + .bind('dragstart', function(ev, ui) { + var _e = ev.target; + var e = $(_e); + if (!e.parents('.fc').length) { // not already inside a calendar + var accept = options.dropAccept; + if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { + _dragElement = _e; + currentView.dragStart(_dragElement, ev, ui); + } + } + }) + .bind('dragstop', function(ev, ui) { + if (_dragElement) { + currentView.dragStop(_dragElement, ev, ui); + _dragElement = null; + } + }); + } + + +} + +function Header(calendar, options) { + var t = this; + + + // exports + t.render = render; + t.destroy = destroy; + t.updateTitle = updateTitle; + t.activateButton = activateButton; + t.deactivateButton = deactivateButton; + t.disableButton = disableButton; + t.enableButton = enableButton; + + + // locals + var element = $([]); + var tm; + + + + function render() { + tm = options.theme ? 'ui' : 'fc'; + var sections = options.header; + if (sections) { + element = $("") + .append( + $("") + .append(renderSection('left')) + .append(renderSection('center')) + .append(renderSection('right')) + ); + return element; + } + } + + + function destroy() { + element.remove(); + } + + + function renderSection(position) { + var e = $("" + + ""; + for (i=0; i"; // need fc- for setDayID + } + s += + "" + + "" + + ""; + for (i=0; i"; + for (j=0; j" + // need fc- for setDayID + "
    " + + (showNumbers ? + "
    " : + '' + ) + + "
    " + + "
     
    " + + "
    " + + "
    " + + ""; + } + s += + ""; + } + s += + "
    " + + "
    "); + var buttonStr = options.header[position]; + if (buttonStr) { + $.each(buttonStr.split(' '), function(i) { + if (i > 0) { + e.append(""); + } + var prevButton; + $.each(this.split(','), function(j, buttonName) { + if (buttonName == 'title') { + e.append("

     

    "); + if (prevButton) { + prevButton.addClass(tm + '-corner-right'); + } + prevButton = null; + }else{ + var buttonClick; + if (calendar[buttonName]) { + buttonClick = calendar[buttonName]; // calendar method + } + else if (fcViews[buttonName]) { + buttonClick = function() { + button.removeClass(tm + '-state-hover'); // forget why + calendar.changeView(buttonName); + }; + } + if (buttonClick) { + var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? + var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? + var button = $( + "" + + "" + + "" + + (icon ? + "" + + "" + + "" : + text + ) + + "" + + "" + + "" + + "" + ); + if (button) { + button + .click(function() { + if (!button.hasClass(tm + '-state-disabled')) { + buttonClick(); + } + }) + .mousedown(function() { + button + .not('.' + tm + '-state-active') + .not('.' + tm + '-state-disabled') + .addClass(tm + '-state-down'); + }) + .mouseup(function() { + button.removeClass(tm + '-state-down'); + }) + .hover( + function() { + button + .not('.' + tm + '-state-active') + .not('.' + tm + '-state-disabled') + .addClass(tm + '-state-hover'); + }, + function() { + button + .removeClass(tm + '-state-hover') + .removeClass(tm + '-state-down'); + } + ) + .appendTo(e); + if (!prevButton) { + button.addClass(tm + '-corner-left'); + } + prevButton = button; + } + } + } + }); + if (prevButton) { + prevButton.addClass(tm + '-corner-right'); + } + }); + } + return e; + } + + + function updateTitle(html) { + element.find('h2') + .html(html); + } + + + function activateButton(buttonName) { + element.find('span.fc-button-' + buttonName) + .addClass(tm + '-state-active'); + } + + + function deactivateButton(buttonName) { + element.find('span.fc-button-' + buttonName) + .removeClass(tm + '-state-active'); + } + + + function disableButton(buttonName) { + element.find('span.fc-button-' + buttonName) + .addClass(tm + '-state-disabled'); + } + + + function enableButton(buttonName) { + element.find('span.fc-button-' + buttonName) + .removeClass(tm + '-state-disabled'); + } + + +} + +fc.sourceNormalizers = []; +fc.sourceFetchers = []; + +var ajaxDefaults = { + dataType: 'json', + cache: false +}; + +var eventGUID = 1; + + +function EventManager(options, _sources) { + var t = this; + + + // exports + t.isFetchNeeded = isFetchNeeded; + t.fetchEvents = fetchEvents; + t.addEventSource = addEventSource; + t.removeEventSource = removeEventSource; + t.updateEvent = updateEvent; + t.renderEvent = renderEvent; + t.removeEvents = removeEvents; + t.clientEvents = clientEvents; + t.normalizeEvent = normalizeEvent; + + + // imports + var trigger = t.trigger; + var getView = t.getView; + var reportEvents = t.reportEvents; + + + // locals + var stickySource = { events: [] }; + var sources = [ stickySource ]; + var rangeStart, rangeEnd; + var currentFetchID = 0; + var pendingSourceCnt = 0; + var loadingLevel = 0; + var cache = []; + + + for (var i=0; i<_sources.length; i++) { + _addEventSource(_sources[i]); + } + + + + /* Fetching + -----------------------------------------------------------------------------*/ + + + function isFetchNeeded(start, end) { + return !rangeStart || start < rangeStart || end > rangeEnd; + } + + + function fetchEvents(start, end) { + rangeStart = start; + rangeEnd = end; + cache = []; + var fetchID = ++currentFetchID; + var len = sources.length; + pendingSourceCnt = len; + for (var i=0; i)), return null instead + return null; +} + + +function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false + // derived from http://delete.me.uk/2005/03/iso8601.html + // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html + var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); + if (!m) { + return null; + } + var date = new Date(m[1], 0, 1); + if (ignoreTimezone || !m[13]) { + var check = new Date(m[1], 0, 1, 9, 0); + if (m[3]) { + date.setMonth(m[3] - 1); + check.setMonth(m[3] - 1); + } + if (m[5]) { + date.setDate(m[5]); + check.setDate(m[5]); + } + fixDate(date, check); + if (m[7]) { + date.setHours(m[7]); + } + if (m[8]) { + date.setMinutes(m[8]); + } + if (m[10]) { + date.setSeconds(m[10]); + } + if (m[12]) { + date.setMilliseconds(Number("0." + m[12]) * 1000); + } + fixDate(date, check); + }else{ + date.setUTCFullYear( + m[1], + m[3] ? m[3] - 1 : 0, + m[5] || 1 + ); + date.setUTCHours( + m[7] || 0, + m[8] || 0, + m[10] || 0, + m[12] ? Number("0." + m[12]) * 1000 : 0 + ); + if (m[14]) { + var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); + offset *= m[15] == '-' ? 1 : -1; + date = new Date(+date + (offset * 60 * 1000)); + } + } + return date; +} + + +function parseTime(s) { // returns minutes since start of day + if (typeof s == 'number') { // an hour + return s * 60; + } + if (typeof s == 'object') { // a Date object + return s.getHours() * 60 + s.getMinutes(); + } + var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); + if (m) { + var h = parseInt(m[1], 10); + if (m[3]) { + h %= 12; + if (m[3].toLowerCase().charAt(0) == 'p') { + h += 12; + } + } + return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); + } +} + + + +/* Date Formatting +-----------------------------------------------------------------------------*/ +// TODO: use same function formatDate(date, [date2], format, [options]) + + +function formatDate(date, format, options) { + return formatDates(date, null, format, options); +} + + +function formatDates(date1, date2, format, options) { + options = options || defaults; + var date = date1, + otherDate = date2, + i, len = format.length, c, + i2, formatter, + res = ''; + for (i=0; ii; i2--) { + if (formatter = dateFormatters[format.substring(i, i2)]) { + if (date) { + res += formatter(date, options); + } + i = i2 - 1; + break; + } + } + if (i2 == i) { + if (date) { + res += c; + } + } + } + } + return res; +}; + + +var dateFormatters = { + s : function(d) { return d.getSeconds() }, + ss : function(d) { return zeroPad(d.getSeconds()) }, + m : function(d) { return d.getMinutes() }, + mm : function(d) { return zeroPad(d.getMinutes()) }, + h : function(d) { return d.getHours() % 12 || 12 }, + hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, + H : function(d) { return d.getHours() }, + HH : function(d) { return zeroPad(d.getHours()) }, + d : function(d) { return d.getDate() }, + dd : function(d) { return zeroPad(d.getDate()) }, + ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, + dddd: function(d,o) { return o.dayNames[d.getDay()] }, + M : function(d) { return d.getMonth() + 1 }, + MM : function(d) { return zeroPad(d.getMonth() + 1) }, + MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, + MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, + yy : function(d) { return (d.getFullYear()+'').substring(2) }, + yyyy: function(d) { return d.getFullYear() }, + t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, + tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, + T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, + TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, + u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, + S : function(d) { + var date = d.getDate(); + if (date > 10 && date < 20) { + return 'th'; + } + return ['st', 'nd', 'rd'][date%10-1] || 'th'; + } +}; + + + +fc.applyAll = applyAll; + + +/* Event Date Math +-----------------------------------------------------------------------------*/ + + +function exclEndDay(event) { + if (event.end) { + return _exclEndDay(event.end, event.allDay); + }else{ + return addDays(cloneDate(event.start), 1); + } +} + + +function _exclEndDay(end, allDay) { + end = cloneDate(end); + return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); +} + + +function segCmp(a, b) { + return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); +} + + +function segsCollide(seg1, seg2) { + return seg1.end > seg2.start && seg1.start < seg2.end; +} + + + +/* Event Sorting +-----------------------------------------------------------------------------*/ + + +// event rendering utilities +function sliceSegs(events, visEventEnds, start, end) { + var segs = [], + i, len=events.length, event, + eventStart, eventEnd, + segStart, segEnd, + isStart, isEnd; + for (i=0; i start && eventStart < end) { + if (eventStart < start) { + segStart = cloneDate(start); + isStart = false; + }else{ + segStart = eventStart; + isStart = true; + } + if (eventEnd > end) { + segEnd = cloneDate(end); + isEnd = false; + }else{ + segEnd = eventEnd; + isEnd = true; + } + segs.push({ + event: event, + start: segStart, + end: segEnd, + isStart: isStart, + isEnd: isEnd, + msLength: segEnd - segStart + }); + } + } + return segs.sort(segCmp); +} + + +// event rendering calculation utilities +function stackSegs(segs) { + var levels = [], + i, len = segs.length, seg, + j, collide, k; + for (i=0; i=0; i--) { + res = obj[parts[i].toLowerCase()]; + if (res !== undefined) { + return res; + } + } + return obj['']; +} + + +function htmlEscape(s) { + return s.replace(/&/g, '&') + .replace(//g, '>') + .replace(/'/g, ''') + .replace(/"/g, '"') + .replace(/\n/g, '
    '); +} + + +function cssKey(_element) { + return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); +} + + +function disableTextSelection(element) { + element + .attr('unselectable', 'on') + .css('MozUserSelect', 'none') + .bind('selectstart.ui', function() { return false; }); +} + + +/* +function enableTextSelection(element) { + element + .attr('unselectable', 'off') + .css('MozUserSelect', '') + .unbind('selectstart.ui'); +} +*/ + + +function markFirstLast(e) { + e.children() + .removeClass('fc-first fc-last') + .filter(':first-child') + .addClass('fc-first') + .end() + .filter(':last-child') + .addClass('fc-last'); +} + + +function setDayID(cell, date) { + cell.each(function(i, _cell) { + _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); + // TODO: make a way that doesn't rely on order of classes + }); +} + + +function getSkinCss(event, opt) { + var source = event.source || {}; + var eventColor = event.color; + var sourceColor = source.color; + var optionColor = opt('eventColor'); + var backgroundColor = + event.backgroundColor || + eventColor || + source.backgroundColor || + sourceColor || + opt('eventBackgroundColor') || + optionColor; + var borderColor = + event.borderColor || + eventColor || + source.borderColor || + sourceColor || + opt('eventBorderColor') || + optionColor; + var textColor = + event.textColor || + source.textColor || + opt('eventTextColor'); + var statements = []; + if (backgroundColor) { + statements.push('background-color:' + backgroundColor); + } + if (borderColor) { + statements.push('border-color:' + borderColor); + } + if (textColor) { + statements.push('color:' + textColor); + } + return statements.join(';'); +} + + +function applyAll(functions, thisObj, args) { + if ($.isFunction(functions)) { + functions = [ functions ]; + } + if (functions) { + var i; + var ret; + for (i=0; i" + + "
    "; + table = $(s).appendTo(element); + + head = table.find('thead'); + headCells = head.find('th'); + body = table.find('tbody'); + bodyRows = body.find('tr'); + bodyCells = body.find('td'); + bodyFirstCells = bodyCells.filter(':first-child'); + bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div'); + + markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's + markFirstLast(bodyRows); // marks first+last td's + bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells + + dayBind(bodyCells); + + daySegmentContainer = + $("
    ") + .appendTo(element); + } + + + + function updateCells(firstTime) { + var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? + var month = t.start.getMonth(); + var today = clearTime(new Date()); + var cell; + var date; + var row; + + if (dowDirty) { + headCells.each(function(i, _cell) { + cell = $(_cell); + date = indexDate(i); + cell.html(formatDate(date, colFormat)); + setDayID(cell, date); + }); + } + + bodyCells.each(function(i, _cell) { + cell = $(_cell); + date = indexDate(i); + if (date.getMonth() == month) { + cell.removeClass('fc-other-month'); + }else{ + cell.addClass('fc-other-month'); + } + if (+date == +today) { + cell.addClass(tm + '-state-highlight fc-today'); + }else{ + cell.removeClass(tm + '-state-highlight fc-today'); + } + cell.find('div.fc-day-number').text(date.getDate()); + if (dowDirty) { + setDayID(cell, date); + } + }); + + bodyRows.each(function(i, _row) { + row = $(_row); + if (i < rowCnt) { + row.show(); + if (i == rowCnt-1) { + row.addClass('fc-last'); + }else{ + row.removeClass('fc-last'); + } + }else{ + row.hide(); + } + }); + } + + + + function setHeight(height) { + viewHeight = height; + + var bodyHeight = viewHeight - head.height(); + var rowHeight; + var rowHeightLast; + var cell; + + if (opt('weekMode') == 'variable') { + rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); + }else{ + rowHeight = Math.floor(bodyHeight / rowCnt); + rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); + } + + bodyFirstCells.each(function(i, _cell) { + if (i < rowCnt) { + cell = $(_cell); + setMinHeight( + cell.find('> div'), + (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) + ); + } + }); + + } + + + function setWidth(width) { + viewWidth = width; + colContentPositions.clear(); + colWidth = Math.floor(viewWidth / colCnt); + setOuterWidth(headCells.slice(0, -1), colWidth); + } + + + + /* Day clicking and binding + -----------------------------------------------------------*/ + + + function dayBind(days) { + days.click(dayClick) + .mousedown(daySelectionMousedown); + } + + + function dayClick(ev) { + if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick + var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data + var date = indexDate(index); + trigger('dayClick', this, date, true, ev); + } + } + + + + /* Semi-transparent Overlay Helpers + ------------------------------------------------------*/ + + + function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive + if (refreshCoordinateGrid) { + coordinateGrid.build(); + } + var rowStart = cloneDate(t.visStart); + var rowEnd = addDays(cloneDate(rowStart), colCnt); + for (var i=0; i" + + "" + + "" + + " "; + for (i=0; i"; // fc- needed for setDayID + } + s += + " " + + "" + + "" + + "" + + "" + + " "; + for (i=0; i" + // fc- needed for setDayID + "
    " + + "
    " + + "
     
    " + + "
    " + + "
    " + + ""; + } + s += + " " + + "" + + "" + + ""; + dayTable = $(s).appendTo(element); + dayHead = dayTable.find('thead'); + dayHeadCells = dayHead.find('th').slice(1, -1); + dayBody = dayTable.find('tbody'); + dayBodyCells = dayBody.find('td').slice(0, -1); + dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); + dayBodyFirstCell = dayBodyCells.eq(0); + dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); + + markFirstLast(dayHead.add(dayHead.find('tr'))); + markFirstLast(dayBody.add(dayBody.find('tr'))); + + axisFirstCells = dayHead.find('th:first'); + gutterCells = dayTable.find('.fc-agenda-gutter'); + + slotLayer = + $("
    ") + .appendTo(element); + + if (opt('allDaySlot')) { + + daySegmentContainer = + $("
    ") + .appendTo(slotLayer); + + s = + "" + + "" + + "" + + "" + + "" + + "" + + "
    " + opt('allDayText') + "" + + "
    " + + "
     
    "; + allDayTable = $(s).appendTo(slotLayer); + allDayRow = allDayTable.find('tr'); + + dayBind(allDayRow.find('td')); + + axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); + gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); + + slotLayer.append( + "
    " + + "
    " + + "
    " + ); + + }else{ + + daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() + + } + + slotScroller = + $("
    ") + .appendTo(slotLayer); + + slotContent = + $("
    ") + .appendTo(slotScroller); + + slotSegmentContainer = + $("
    ") + .appendTo(slotContent); + + s = + "" + + ""; + d = zeroDate(); + maxd = addMinutes(cloneDate(d), maxMinute); + addMinutes(d, minMinute); + slotCnt = 0; + for (i=0; d < maxd; i++) { + minutes = d.getMinutes(); + s += + "" + + "" + + "" + + ""; + addMinutes(d, opt('slotMinutes')); + slotCnt++; + } + s += + "" + + "
    " + + ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') + + "" + + "
     
    " + + "
    "; + slotTable = $(s).appendTo(slotContent); + slotTableFirstInner = slotTable.find('div:first'); + + slotBind(slotTable.find('td')); + + axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); + } + + + + function updateCells() { + var i; + var headCell; + var bodyCell; + var date; + var today = clearTime(new Date()); + for (i=0; i= 0) { + addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); + } + return d; + } + + + function colDate(col) { // returns dates with 00:00:00 + return addDays(cloneDate(t.visStart), col*dis+dit); + } + + + function cellIsAllDay(cell) { + return opt('allDaySlot') && !cell.row; + } + + + function dayOfWeekCol(dayOfWeek) { + return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; + } + + + + + // get the Y coordinate of the given time on the given day (both Date objects) + function timePosition(day, time) { // both date objects. day holds 00:00 of current day + day = cloneDate(day, true); + if (time < addMinutes(cloneDate(day), minMinute)) { + return 0; + } + if (time >= addMinutes(cloneDate(day), maxMinute)) { + return slotTable.height(); + } + var slotMinutes = opt('slotMinutes'), + minutes = time.getHours()*60 + time.getMinutes() - minMinute, + slotI = Math.floor(minutes / slotMinutes), + slotTop = slotTopCache[slotI]; + if (slotTop === undefined) { + slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? + } + return Math.max(0, Math.round( + slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) + )); + } + + + function allDayBounds() { + return { + left: axisWidth, + right: viewWidth - gutterWidth + } + } + + + function getAllDayRow(index) { + return allDayRow; + } + + + function defaultEventEnd(event) { + var start = cloneDate(event.start); + if (event.allDay) { + return start; + } + return addMinutes(start, opt('defaultEventMinutes')); + } + + + + /* Selection + ---------------------------------------------------------------------------------*/ + + + function defaultSelectionEnd(startDate, allDay) { + if (allDay) { + return cloneDate(startDate); + } + return addMinutes(cloneDate(startDate), opt('slotMinutes')); + } + + + function renderSelection(startDate, endDate, allDay) { // only for all-day + if (allDay) { + if (opt('allDaySlot')) { + renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); + } + }else{ + renderSlotSelection(startDate, endDate); + } + } + + + function renderSlotSelection(startDate, endDate) { + var helperOption = opt('selectHelper'); + coordinateGrid.build(); + if (helperOption) { + var col = dayDiff(startDate, t.visStart) * dis + dit; + if (col >= 0 && col < colCnt) { // only works when times are on same day + var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords + var top = timePosition(startDate, startDate); + var bottom = timePosition(startDate, endDate); + if (bottom > top) { // protect against selections that are entirely before or after visible range + rect.top = top; + rect.height = bottom - top; + rect.left += 2; + rect.width -= 5; + if ($.isFunction(helperOption)) { + var helperRes = helperOption(startDate, endDate); + if (helperRes) { + rect.position = 'absolute'; + rect.zIndex = 8; + selectionHelper = $(helperRes) + .css(rect) + .appendTo(slotContent); + } + }else{ + rect.isStart = true; // conside rect a "seg" now + rect.isEnd = true; // + selectionHelper = $(slotSegHtml( + { + title: '', + start: startDate, + end: endDate, + className: ['fc-select-helper'], + editable: false + }, + rect + )); + selectionHelper.css('opacity', opt('dragOpacity')); + } + if (selectionHelper) { + slotBind(selectionHelper); + slotContent.append(selectionHelper); + setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended + setOuterHeight(selectionHelper, rect.height, true); + } + } + } + }else{ + renderSlotOverlay(startDate, endDate); + } + } + + + function clearSelection() { + clearOverlays(); + if (selectionHelper) { + selectionHelper.remove(); + selectionHelper = null; + } + } + + + function slotSelectionMousedown(ev) { + if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button + unselect(ev); + var dates; + hoverListener.start(function(cell, origCell) { + clearSelection(); + if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { + var d1 = cellDate(origCell); + var d2 = cellDate(cell); + dates = [ + d1, + addMinutes(cloneDate(d1), opt('slotMinutes')), + d2, + addMinutes(cloneDate(d2), opt('slotMinutes')) + ].sort(cmp); + renderSlotSelection(dates[0], dates[3]); + }else{ + dates = null; + } + }, ev); + $(document).one('mouseup', function(ev) { + hoverListener.stop(); + if (dates) { + if (+dates[0] == +dates[1]) { + reportDayClick(dates[0], false, ev); + } + reportSelection(dates[0], dates[3], false, ev); + } + }); + } + } + + + function reportDayClick(date, allDay, ev) { + trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); + } + + + + /* External Dragging + --------------------------------------------------------------------------------*/ + + + function dragStart(_dragElement, ev, ui) { + hoverListener.start(function(cell) { + clearOverlays(); + if (cell) { + if (cellIsAllDay(cell)) { + renderCellOverlay(cell.row, cell.col, cell.row, cell.col); + }else{ + var d1 = cellDate(cell); + var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); + renderSlotOverlay(d1, d2); + } + } + }, ev); + } + + + function dragStop(_dragElement, ev, ui) { + var cell = hoverListener.stop(); + clearOverlays(); + if (cell) { + trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); + } + } + + +} + +function AgendaEventRenderer() { + var t = this; + + + // exports + t.renderEvents = renderEvents; + t.compileDaySegs = compileDaySegs; // for DayEventRenderer + t.clearEvents = clearEvents; + t.slotSegHtml = slotSegHtml; + t.bindDaySeg = bindDaySeg; + + + // imports + DayEventRenderer.call(t); + var opt = t.opt; + var trigger = t.trigger; + //var setOverflowHidden = t.setOverflowHidden; + var isEventDraggable = t.isEventDraggable; + var isEventResizable = t.isEventResizable; + var eventEnd = t.eventEnd; + var reportEvents = t.reportEvents; + var reportEventClear = t.reportEventClear; + var eventElementHandlers = t.eventElementHandlers; + var setHeight = t.setHeight; + var getDaySegmentContainer = t.getDaySegmentContainer; + var getSlotSegmentContainer = t.getSlotSegmentContainer; + var getHoverListener = t.getHoverListener; + var getMaxMinute = t.getMaxMinute; + var getMinMinute = t.getMinMinute; + var timePosition = t.timePosition; + var colContentLeft = t.colContentLeft; + var colContentRight = t.colContentRight; + var renderDaySegs = t.renderDaySegs; + var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture + var getColCnt = t.getColCnt; + var getColWidth = t.getColWidth; + var getSlotHeight = t.getSlotHeight; + var getBodyContent = t.getBodyContent; + var reportEventElement = t.reportEventElement; + var showEvents = t.showEvents; + var hideEvents = t.hideEvents; + var eventDrop = t.eventDrop; + var eventResize = t.eventResize; + var renderDayOverlay = t.renderDayOverlay; + var clearOverlays = t.clearOverlays; + var calendar = t.calendar; + var formatDate = calendar.formatDate; + var formatDates = calendar.formatDates; + + + + /* Rendering + ----------------------------------------------------------------------------*/ + + + function renderEvents(events, modifiedEventId) { + reportEvents(events); + var i, len=events.length, + dayEvents=[], + slotEvents=[]; + for (i=0; i" + + "
    " + + "
    " + + "
    " + + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + + "
    " + + "
    " + + "
    " + + "
    " + + htmlEscape(event.title) + + "
    " + + "
    " + + "
    " + + "
    "; // close inner + if (seg.isEnd && isEventResizable(event)) { + html += + "
    =
    "; + } + html += + ""; + return html; + } + + + function bindDaySeg(event, eventElement, seg) { + if (isEventDraggable(event)) { + draggableDayEvent(event, eventElement, seg.isStart); + } + if (seg.isEnd && isEventResizable(event)) { + resizableDayEvent(event, eventElement, seg); + } + eventElementHandlers(event, eventElement); + // needs to be after, because resizableDayEvent might stopImmediatePropagation on click + } + + + function bindSlotSeg(event, eventElement, seg) { + var timeElement = eventElement.find('div.fc-event-time'); + if (isEventDraggable(event)) { + draggableSlotEvent(event, eventElement, timeElement); + } + if (seg.isEnd && isEventResizable(event)) { + resizableSlotEvent(event, eventElement, timeElement); + } + eventElementHandlers(event, eventElement); + } + + + + /* Dragging + -----------------------------------------------------------------------------------*/ + + + // when event starts out FULL-DAY + + function draggableDayEvent(event, eventElement, isStart) { + var origWidth; + var revert; + var allDay=true; + var dayDelta; + var dis = opt('isRTL') ? -1 : 1; + var hoverListener = getHoverListener(); + var colWidth = getColWidth(); + var slotHeight = getSlotHeight(); + var minMinute = getMinMinute(); + eventElement.draggable({ + zIndex: 9, + opacity: opt('dragOpacity', 'month'), // use whatever the month view was using + revertDuration: opt('dragRevertDuration'), + start: function(ev, ui) { + trigger('eventDragStart', eventElement, event, ev, ui); + hideEvents(event, eventElement); + origWidth = eventElement.width(); + hoverListener.start(function(cell, origCell, rowDelta, colDelta) { + clearOverlays(); + if (cell) { + //setOverflowHidden(true); + revert = false; + dayDelta = colDelta * dis; + if (!cell.row) { + // on full-days + renderDayOverlay( + addDays(cloneDate(event.start), dayDelta), + addDays(exclEndDay(event), dayDelta) + ); + resetElement(); + }else{ + // mouse is over bottom slots + if (isStart) { + if (allDay) { + // convert event to temporary slot-event + eventElement.width(colWidth - 10); // don't use entire width + setOuterHeight( + eventElement, + slotHeight * Math.round( + (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) + / opt('slotMinutes') + ) + ); + eventElement.draggable('option', 'grid', [colWidth, 1]); + allDay = false; + } + }else{ + revert = true; + } + } + revert = revert || (allDay && !dayDelta); + }else{ + resetElement(); + //setOverflowHidden(false); + revert = true; + } + eventElement.draggable('option', 'revert', revert); + }, ev, 'drag'); + }, + stop: function(ev, ui) { + hoverListener.stop(); + clearOverlays(); + trigger('eventDragStop', eventElement, event, ev, ui); + if (revert) { + // hasn't moved or is out of bounds (draggable has already reverted) + resetElement(); + eventElement.css('filter', ''); // clear IE opacity side-effects + showEvents(event, eventElement); + }else{ + // changed! + var minuteDelta = 0; + if (!allDay) { + minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) + * opt('slotMinutes') + + minMinute + - (event.start.getHours() * 60 + event.start.getMinutes()); + } + eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); + } + //setOverflowHidden(false); + } + }); + function resetElement() { + if (!allDay) { + eventElement + .width(origWidth) + .height('') + .draggable('option', 'grid', null); + allDay = true; + } + } + } + + + // when event starts out IN TIMESLOTS + + function draggableSlotEvent(event, eventElement, timeElement) { + var origPosition; + var allDay=false; + var dayDelta; + var minuteDelta; + var prevMinuteDelta; + var dis = opt('isRTL') ? -1 : 1; + var hoverListener = getHoverListener(); + var colCnt = getColCnt(); + var colWidth = getColWidth(); + var slotHeight = getSlotHeight(); + eventElement.draggable({ + zIndex: 9, + scroll: false, + grid: [colWidth, slotHeight], + axis: colCnt==1 ? 'y' : false, + opacity: opt('dragOpacity'), + revertDuration: opt('dragRevertDuration'), + start: function(ev, ui) { + trigger('eventDragStart', eventElement, event, ev, ui); + hideEvents(event, eventElement); + origPosition = eventElement.position(); + minuteDelta = prevMinuteDelta = 0; + hoverListener.start(function(cell, origCell, rowDelta, colDelta) { + eventElement.draggable('option', 'revert', !cell); + clearOverlays(); + if (cell) { + dayDelta = colDelta * dis; + if (opt('allDaySlot') && !cell.row) { + // over full days + if (!allDay) { + // convert to temporary all-day event + allDay = true; + timeElement.hide(); + eventElement.draggable('option', 'grid', null); + } + renderDayOverlay( + addDays(cloneDate(event.start), dayDelta), + addDays(exclEndDay(event), dayDelta) + ); + }else{ + // on slots + resetElement(); + } + } + }, ev, 'drag'); + }, + drag: function(ev, ui) { + minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); + if (minuteDelta != prevMinuteDelta) { + if (!allDay) { + updateTimeText(minuteDelta); + } + prevMinuteDelta = minuteDelta; + } + }, + stop: function(ev, ui) { + var cell = hoverListener.stop(); + clearOverlays(); + trigger('eventDragStop', eventElement, event, ev, ui); + if (cell && (dayDelta || minuteDelta || allDay)) { + // changed! + eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); + }else{ + // either no change or out-of-bounds (draggable has already reverted) + resetElement(); + eventElement.css('filter', ''); // clear IE opacity side-effects + eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position + updateTimeText(0); + showEvents(event, eventElement); + } + } + }); + function updateTimeText(minuteDelta) { + var newStart = addMinutes(cloneDate(event.start), minuteDelta); + var newEnd; + if (event.end) { + newEnd = addMinutes(cloneDate(event.end), minuteDelta); + } + timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); + } + function resetElement() { + // convert back to original slot-event + if (allDay) { + timeElement.css('display', ''); // show() was causing display=inline + eventElement.draggable('option', 'grid', [colWidth, slotHeight]); + allDay = false; + } + } + } + + + + /* Resizing + --------------------------------------------------------------------------------------*/ + + + function resizableSlotEvent(event, eventElement, timeElement) { + var slotDelta, prevSlotDelta; + var slotHeight = getSlotHeight(); + eventElement.resizable({ + handles: { + s: 'div.ui-resizable-s' + }, + grid: slotHeight, + start: function(ev, ui) { + slotDelta = prevSlotDelta = 0; + hideEvents(event, eventElement); + eventElement.css('z-index', 9); + trigger('eventResizeStart', this, event, ev, ui); + }, + resize: function(ev, ui) { + // don't rely on ui.size.height, doesn't take grid into account + slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); + if (slotDelta != prevSlotDelta) { + timeElement.text( + formatDates( + event.start, + (!slotDelta && !event.end) ? null : // no change, so don't display time range + addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), + opt('timeFormat') + ) + ); + prevSlotDelta = slotDelta; + } + }, + stop: function(ev, ui) { + trigger('eventResizeStop', this, event, ev, ui); + if (slotDelta) { + eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); + }else{ + eventElement.css('z-index', 8); + showEvents(event, eventElement); + // BUG: if event was really short, need to put title back in span + } + } + }); + } + + +} + + +function countForwardSegs(levels) { + var i, j, k, level, segForward, segBack; + for (i=levels.length-1; i>0; i--) { + level = levels[i]; + for (j=0; j"); + var elements; + var segmentContainer = getDaySegmentContainer(); + var i; + var segCnt = segs.length; + var element; + tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() + elements = tempContainer.children(); + segmentContainer.append(elements); + daySegElementResolve(segs, elements); + daySegCalcHSides(segs); + daySegSetWidths(segs); + daySegCalcHeights(segs); + daySegSetTops(segs, getRowTops(getRowDivs())); + elements = []; + for (i=0; i" + + ""; + if (!event.allDay && seg.isStart) { + html += + "" + + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + + ""; + } + html += + "" + htmlEscape(event.title) + "" + + "
    "; + if (seg.isEnd && isEventResizable(event)) { + html += + "
    " + + "   " + // makes hit area a lot better for IE6/7 + "
    "; + } + html += + ""; + seg.left = left; + seg.outerWidth = right - left; + seg.startCol = leftCol; + seg.endCol = rightCol + 1; // needs to be exclusive + } + return html; + } + + + function daySegElementResolve(segs, elements) { // sets seg.element + var i; + var segCnt = segs.length; + var seg; + var event; + var element; + var triggerRes; + for (i=0; i div'); // optimal selector? + } + return rowDivs; + } + + + function getRowTops(rowDivs) { + var i; + var rowCnt = rowDivs.length; + var tops = []; + for (i=0; i selection for IE + element + .mousedown(function(ev) { // prevent native selection for others + ev.preventDefault(); + }) + .click(function(ev) { + if (isResizing) { + ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) + ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called + // (eventElementHandlers needs to be bound after resizableDayEvent) + } + }); + + handle.mousedown(function(ev) { + if (ev.which != 1) { + return; // needs to be left mouse button + } + isResizing = true; + var hoverListener = t.getHoverListener(); + var rowCnt = getRowCnt(); + var colCnt = getColCnt(); + var dis = rtl ? -1 : 1; + var dit = rtl ? colCnt-1 : 0; + var elementTop = element.css('top'); + var dayDelta; + var helpers; + var eventCopy = $.extend({}, event); + var minCell = dateCell(event.start); + clearSelection(); + $('body') + .css('cursor', direction + '-resize') + .one('mouseup', mouseup); + trigger('eventResizeStart', this, event, ev); + hoverListener.start(function(cell, origCell) { + if (cell) { + var r = Math.max(minCell.row, cell.row); + var c = cell.col; + if (rowCnt == 1) { + r = 0; // hack for all-day area in agenda views + } + if (r == minCell.row) { + if (rtl) { + c = Math.min(minCell.col, c); + }else{ + c = Math.max(minCell.col, c); + } + } + dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); + var newEnd = addDays(eventEnd(event), dayDelta, true); + if (dayDelta) { + eventCopy.end = newEnd; + var oldHelpers = helpers; + helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); + helpers.find('*').css('cursor', direction + '-resize'); + if (oldHelpers) { + oldHelpers.remove(); + } + hideEvents(event); + }else{ + if (helpers) { + showEvents(event); + helpers.remove(); + helpers = null; + } + } + clearOverlays(); + renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start + } + }, ev); + + function mouseup(ev) { + trigger('eventResizeStop', this, event, ev); + $('body').css('cursor', ''); + hoverListener.stop(); + clearOverlays(); + if (dayDelta) { + eventResize(this, event, dayDelta, 0, ev); + // event redraw will clear helpers + } + // otherwise, the drag handler already restored the old events + + setTimeout(function() { // make this happen after the element's click event + isResizing = false; + },0); + } + + }); + } + + +} + +//BUG: unselect needs to be triggered when events are dragged+dropped + +function SelectionManager() { + var t = this; + + + // exports + t.select = select; + t.unselect = unselect; + t.reportSelection = reportSelection; + t.daySelectionMousedown = daySelectionMousedown; + + + // imports + var opt = t.opt; + var trigger = t.trigger; + var defaultSelectionEnd = t.defaultSelectionEnd; + var renderSelection = t.renderSelection; + var clearSelection = t.clearSelection; + + + // locals + var selected = false; + + + + // unselectAuto + if (opt('selectable') && opt('unselectAuto')) { + $(document).mousedown(function(ev) { + var ignore = opt('unselectCancel'); + if (ignore) { + if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match + return; + } + } + unselect(ev); + }); + } + + + function select(startDate, endDate, allDay) { + unselect(); + if (!endDate) { + endDate = defaultSelectionEnd(startDate, allDay); + } + renderSelection(startDate, endDate, allDay); + reportSelection(startDate, endDate, allDay); + } + + + function unselect(ev) { + if (selected) { + selected = false; + clearSelection(); + trigger('unselect', null, ev); + } + } + + + function reportSelection(startDate, endDate, allDay, ev) { + selected = true; + trigger('select', null, startDate, endDate, allDay, ev); + } + + + function daySelectionMousedown(ev) { // not really a generic manager method, oh well + var cellDate = t.cellDate; + var cellIsAllDay = t.cellIsAllDay; + var hoverListener = t.getHoverListener(); + var reportDayClick = t.reportDayClick; // this is hacky and sort of weird + if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button + unselect(ev); + var _mousedownElement = this; + var dates; + hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell + clearSelection(); + if (cell && cellIsAllDay(cell)) { + dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); + renderSelection(dates[0], dates[1], true); + }else{ + dates = null; + } + }, ev); + $(document).one('mouseup', function(ev) { + hoverListener.stop(); + if (dates) { + if (+dates[0] == +dates[1]) { + reportDayClick(dates[0], true, ev); + } + reportSelection(dates[0], dates[1], true, ev); + } + }); + } + } + + +} + +function OverlayManager() { + var t = this; + + + // exports + t.renderOverlay = renderOverlay; + t.clearOverlays = clearOverlays; + + + // locals + var usedOverlays = []; + var unusedOverlays = []; + + + function renderOverlay(rect, parent) { + var e = unusedOverlays.shift(); + if (!e) { + e = $("
    "); + } + if (e[0].parentNode != parent[0]) { + e.appendTo(parent); + } + usedOverlays.push(e.css(rect).show()); + return e; + } + + + function clearOverlays() { + var e; + while (e = usedOverlays.shift()) { + unusedOverlays.push(e.hide().unbind()); + } + } + + +} + +function CoordinateGrid(buildFunc) { + + var t = this; + var rows; + var cols; + + + t.build = function() { + rows = []; + cols = []; + buildFunc(rows, cols); + }; + + + t.cell = function(x, y) { + var rowCnt = rows.length; + var colCnt = cols.length; + var i, r=-1, c=-1; + for (i=0; i= rows[i][0] && y < rows[i][1]) { + r = i; + break; + } + } + for (i=0; i= cols[i][0] && x < cols[i][1]) { + c = i; + break; + } + } + return (r>=0 && c>=0) ? { row:r, col:c } : null; + }; + + + t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive + var origin = originElement.offset(); + return { + top: rows[row0][0] - origin.top, + left: cols[col0][0] - origin.left, + width: cols[col1][1] - cols[col0][0], + height: rows[row1][1] - rows[row0][0] + }; + }; + +} + +function HoverListener(coordinateGrid) { + + + var t = this; + var bindType; + var change; + var firstCell; + var cell; + + + t.start = function(_change, ev, _bindType) { + change = _change; + firstCell = cell = null; + coordinateGrid.build(); + mouse(ev); + bindType = _bindType || 'mousemove'; + $(document).bind(bindType, mouse); + }; + + + function mouse(ev) { + _fixUIEvent(ev); // see below + var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); + if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) { + if (newCell) { + if (!firstCell) { + firstCell = newCell; + } + change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); + }else{ + change(newCell, firstCell); + } + cell = newCell; + } + } + + + t.stop = function() { + $(document).unbind(bindType, mouse); + return cell; + }; + + +} + + + +// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1) +// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem +// but keep this in here for 1.8.16 users +// and maybe remove it down the line + +function _fixUIEvent(event) { // for issue 1168 + if (event.pageX === undefined) { + event.pageX = event.originalEvent.pageX; + event.pageY = event.originalEvent.pageY; + } +} +function HorizontalPositionCache(getElement) { + + var t = this, + elements = {}, + lefts = {}, + rights = {}; + + function e(i) { + return elements[i] = elements[i] || getElement(i); + } + + t.left = function(i) { + return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i]; + }; + + t.right = function(i) { + return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]; + }; + + t.clear = function() { + elements = {}; + lefts = {}; + rights = {}; + }; + +} + +})(jQuery); diff --git a/3rdparty/fullcalendar/fullcalendar.min.js b/3rdparty/fullcalendar/fullcalendar.min.js new file mode 100644 index 00000000000..df37bdfd803 --- /dev/null +++ b/3rdparty/fullcalendar/fullcalendar.min.js @@ -0,0 +1,114 @@ +/* + + FullCalendar v1.5.3 + http://arshaw.com/fullcalendar/ + + Use fullcalendar.css for basic styling. + For event drag & drop, requires jQuery UI draggable. + For event resizing, requires jQuery UI resizable. + + Copyright (c) 2011 Adam Shaw + Dual licensed under the MIT and GPL licenses, located in + MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + + Date: Mon Feb 6 22:40:40 2012 -0800 + +*/ +(function(m,ma){function wb(a){m.extend(true,Ya,a)}function Yb(a,b,e){function d(k){if(E){u();q();na();S(k)}else f()}function f(){B=b.theme?"ui":"fc";a.addClass("fc");b.isRTL&&a.addClass("fc-rtl");b.theme&&a.addClass("ui-widget");E=m("
    ").prependTo(a);C=new Zb(X,b);(P=C.render())&&a.prepend(P);y(b.defaultView);m(window).resize(oa);t()||g()}function g(){setTimeout(function(){!n.start&&t()&&S()},0)}function l(){m(window).unbind("resize",oa);C.destroy(); +E.remove();a.removeClass("fc fc-rtl ui-widget")}function j(){return i.offsetWidth!==0}function t(){return m("body")[0].offsetWidth!==0}function y(k){if(!n||k!=n.name){F++;pa();var D=n,Z;if(D){(D.beforeHide||xb)();Za(E,E.height());D.element.hide()}else Za(E,1);E.css("overflow","hidden");if(n=Y[k])n.element.show();else n=Y[k]=new Ja[k](Z=s=m("
    ").appendTo(E),X);D&&C.deactivateButton(D.name);C.activateButton(k);S();E.css("overflow","");D&& +Za(E,1);Z||(n.afterShow||xb)();F--}}function S(k){if(j()){F++;pa();o===ma&&u();var D=false;if(!n.start||k||r=n.end){n.render(r,k||0);fa(true);D=true}else if(n.sizeDirty){n.clearEvents();fa();D=true}else if(n.eventsDirty){n.clearEvents();D=true}n.sizeDirty=false;n.eventsDirty=false;ga(D);W=a.outerWidth();C.updateTitle(n.title);k=new Date;k>=n.start&&k").append(m("").append(f("left")).append(f("center")).append(f("right")))}function d(){Q.remove()}function f(u){var fa=m("");(u=b.header[u])&&m.each(u.split(" "),function(oa){oa>0&&fa.append("");var ga; +m.each(this.split(","),function(ra,sa){if(sa=="title"){fa.append("

     

    ");ga&&ga.addClass(q+"-corner-right");ga=null}else{var ha;if(a[sa])ha=a[sa];else if(Ja[sa])ha=function(){na.removeClass(q+"-state-hover");a.changeView(sa)};if(ha){ra=b.theme?jb(b.buttonIcons,sa):null;var da=jb(b.buttonText,sa),na=m(""+(ra?"":da)+"");if(na){na.click(function(){na.hasClass(q+"-state-disabled")||ha()}).mousedown(function(){na.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-down")}).mouseup(function(){na.removeClass(q+"-state-down")}).hover(function(){na.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-hover")},function(){na.removeClass(q+"-state-hover").removeClass(q+"-state-down")}).appendTo(fa); +ga||na.addClass(q+"-corner-left");ga=na}}}});ga&&ga.addClass(q+"-corner-right")});return fa}function g(u){Q.find("h2").html(u)}function l(u){Q.find("span.fc-button-"+u).addClass(q+"-state-active")}function j(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-active")}function t(u){Q.find("span.fc-button-"+u).addClass(q+"-state-disabled")}function y(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-disabled")}var S=this;S.render=e;S.destroy=d;S.updateTitle=g;S.activateButton=l;S.deactivateButton= +j;S.disableButton=t;S.enableButton=y;var Q=m([]),q}function $b(a,b){function e(c,z){return!ca||cka}function d(c,z){ca=c;ka=z;L=[];c=++qa;G=z=U.length;for(var H=0;Hl;y--)if(S=dc[e.substring(l,y)]){if(f)Q+=S(f,d);l=y-1;break}if(y==l)if(f)Q+=t}}return Q}function Ua(a){return a.end?ec(a.end,a.allDay):ba(N(a.start),1)}function ec(a,b){a=N(a);return b||a.getHours()||a.getMinutes()?ba(a,1):Ka(a)}function fc(a,b){return(b.msLength-a.msLength)*100+(a.event.start-b.event.start)}function Cb(a,b){return a.end>b.start&&a.starte&&td){y=N(d);Q=false}else{y=y;Q=true}f.push({event:j,start:t,end:y,isStart:S,isEnd:Q,msLength:y-t})}}return f.sort(fc)}function ob(a){var b=[],e,d=a.length,f,g,l,j;for(e=0;e=0;e--){d=a[b[e].toLowerCase()];if(d!== +ma)return d}return a[""]}function Qa(a){return a.replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g,"
    ")}function Ib(a){return a.id+"/"+a.className+"/"+a.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig,"")}function qb(a){a.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})}function ab(a){a.children().removeClass("fc-first fc-last").filter(":first-child").addClass("fc-first").end().filter(":last-child").addClass("fc-last")} +function rb(a,b){a.each(function(e,d){d.className=d.className.replace(/^fc-\w*/,"fc-"+lc[b.getDay()])})}function Jb(a,b){var e=a.source||{},d=a.color,f=e.color,g=b("eventColor"),l=a.backgroundColor||d||e.backgroundColor||f||b("eventBackgroundColor")||g;d=a.borderColor||d||e.borderColor||f||b("eventBorderColor")||g;a=a.textColor||e.textColor||b("eventTextColor");b=[];l&&b.push("background-color:"+l);d&&b.push("border-color:"+d);a&&b.push("color:"+a);return b.join(";")}function $a(a,b,e){if(m.isFunction(a))a= +[a];if(a){var d,f;for(d=0;d";for(aa=0;aa";R+="";for(aa=0;aa";for(V=0;V
    "+(I?"
    ":"")+"
     
    ";R+=""}R+="";w= +m(R).appendTo(a);K=w.find("thead");i=K.find("th");C=w.find("tbody");P=C.find("tr");E=C.find("td");B=E.filter(":first-child");n=P.eq(0).find("div.fc-day-content div");ab(K.add(K.find("tr")));ab(P);P.eq(0).addClass("fc-first");y(E);Y=m("
    ").appendTo(a)}function l(w){var I=w||v==1,R=p.start.getMonth(),V=Ka(new Date),ea,aa,va;I&&i.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);ea.html(ya(aa,$));rb(ea,aa)});E.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);aa.getMonth()== +R?ea.removeClass("fc-other-month"):ea.addClass("fc-other-month");+aa==+V?ea.addClass(la+"-state-highlight fc-today"):ea.removeClass(la+"-state-highlight fc-today");ea.find("div.fc-day-number").text(aa.getDate());I&&rb(ea,aa)});P.each(function(wa,Ga){va=m(Ga);if(wa div"),(ea==v-1?R:I)-Sa(V))}})}function t(w){W=w;M.clear();s=Math.floor(W/F);Va(i.slice(0,-1),s)}function y(w){w.click(S).mousedown(X)}function S(w){if(!L("selectable")){var I=parseInt(this.className.match(/fc\-day(\d+)/)[1]);I=ca(I);c("dayClick",this,I,true,w)}}function Q(w,I,R){R&&r.build();R=N(p.visStart);for(var V=ba(N(R),F),ea=0;ea ";for(A=0;A";x+="  ";for(A=0;A
     
    ";x+=" ";v=m(x).appendTo(a);F=v.find("thead");r=F.find("th").slice(1,-1);J=v.find("tbody");M=J.find("td").slice(0,-1);k=M.find("div.fc-day-content div");D=M.eq(0);Z=D.find("> div");ab(F.add(F.find("tr")));ab(J.add(J.find("tr")));aa=F.find("th:first");va=v.find(".fc-agenda-gutter");ja=m("
    ").appendTo(a); +if(i("allDaySlot")){ia=m("
    ").appendTo(ja);x="
    "+i("allDayText")+"
     
    ";la=m(x).appendTo(ja);$=la.find("tr");q($.find("td"));aa=aa.add(la.find("th:first"));va=va.add(la.find("th.fc-agenda-gutter"));ja.append("
    ")}else ia=m([]);w=m("
    ").appendTo(ja);I=m("
    ").appendTo(w);R=m("
    ").appendTo(I);x="";ta=zb();za=xa(N(ta),bb);xa(ta,La);for(A=tb=0;ta";xa(ta,i("slotMinutes"));tb++}x+="
    "+(!Ea||!Da?s(ta,i("axisFormat")):" ")+"
     
    ";V=m(x).appendTo(I);ea=V.find("div:first");u(V.find("td"));aa=aa.add(V.find("th:first"))}function l(){var h,O,x,A,ta=Ka(new Date);for(h=0;h=0&&xa(O,La+h*i("slotMinutes"));return O}function ua(h){return ba(N(K.visStart),h*Ha+Ia)}function pa(h){return i("allDaySlot")&&!h.row}function U(h){return(h-Math.max(Tb,Sb)+Ba)%Ba*Ha+Ia}function ca(h,O){h=N(h,true);if(O=xa(N(h),bb))return V.height(); +h=i("slotMinutes");O=O.getHours()*60+O.getMinutes()-La;var x=Math.floor(O/h),A=ub[x];if(A===ma)A=ub[x]=V.find("tr:eq("+x+") td div")[0].offsetTop;return Math.max(0,Math.round(A-1+Xa*(O%h/h)))}function ka(){return{left:Ma,right:Ga-vb}}function qa(){return $}function G(h){var O=N(h.start);if(h.allDay)return O;return xa(O,i("defaultEventMinutes"))}function p(h,O){if(O)return N(h);return xa(N(h),i("slotMinutes"))}function L(h,O,x){if(x)i("allDaySlot")&&oa(h,ba(N(O),1),true);else c(h,O)}function c(h,O){var x= +i("selectHelper");Na.build();if(x){var A=Ca(h,K.visStart)*Ha+Ia;if(A>=0&&Ata){A.top=ta;A.height=za-ta;A.left+=2;A.width-=5;if(m.isFunction(x)){if(h=x(h,O)){A.position="absolute";A.zIndex=8;wa=m(h).css(A).appendTo(I)}}else{A.isStart=true;A.isEnd=true;wa=m(o({title:"",start:h,end:O,className:["fc-select-helper"],editable:false},A));wa.css("opacity",i("dragOpacity"))}if(wa){u(wa);I.append(wa);Va(wa,A.width,true);Eb(wa,A.height,true)}}}}else ra(h, +O)}function z(){B();if(wa){wa.remove();wa=null}}function H(h){if(h.which==1&&i("selectable")){Y(h);var O;Ra.start(function(x,A){z();if(x&&x.col==A.col&&!pa(x)){A=na(A);x=na(x);O=[A,xa(N(A),i("slotMinutes")),x,xa(N(x),i("slotMinutes"))].sort(Gb);c(O[0],O[3])}else O=null},h);m(document).one("mouseup",function(x){Ra.stop();if(O){+O[0]==+O[1]&&T(O[0],false,x);n(O[0],O[3],false,x)}})}}function T(h,O,x){C("dayClick",M[U(h.getDay())],h,O,x)}function X(h,O){Ra.start(function(x){B();if(x)if(pa(x))ga(x.row, +x.col,x.row,x.col);else{x=na(x);var A=xa(N(x),i("defaultEventMinutes"));ra(x,A)}},O)}function ya(h,O,x){var A=Ra.stop();B();A&&C("drop",h,na(A),pa(A),O,x)}var K=this;K.renderAgenda=d;K.setWidth=t;K.setHeight=j;K.beforeHide=S;K.afterShow=Q;K.defaultEventEnd=G;K.timePosition=ca;K.dayOfWeekCol=U;K.dateCell=da;K.cellDate=na;K.cellIsAllDay=pa;K.allDayRow=qa;K.allDayBounds=ka;K.getHoverListener=function(){return Ra};K.colContentLeft=sa;K.colContentRight=ha;K.getDaySegmentContainer=function(){return ia}; +K.getSlotSegmentContainer=function(){return R};K.getMinMinute=function(){return La};K.getMaxMinute=function(){return bb};K.getBodyContent=function(){return I};K.getRowCnt=function(){return 1};K.getColCnt=function(){return Ba};K.getColWidth=function(){return db};K.getSlotHeight=function(){return Xa};K.defaultSelectionEnd=p;K.renderDayOverlay=oa;K.renderSelection=L;K.clearSelection=z;K.reportDayClick=T;K.dragStart=X;K.dragStop=ya;Kb.call(K,a,b,e);Lb.call(K);Mb.call(K);sc.call(K);var i=K.opt,C=K.trigger, +P=K.clearEvents,E=K.renderOverlay,B=K.clearOverlays,n=K.reportSelection,Y=K.unselect,W=K.daySelectionMousedown,o=K.slotSegHtml,s=b.formatDate,v,F,r,J,M,k,D,Z,ja,ia,la,$,w,I,R,V,ea,aa,va,wa,Ga,Wb,Ma,db,vb,Xa,Xb,Ba,tb,Na,Ra,cb,ub={},Wa,Tb,Sb,Ub,Ha,Ia,La,bb,Vb;qb(a.addClass("fc-agenda"));Na=new Nb(function(h,O){function x(eb){return Math.max(Ea,Math.min(tc,eb))}var A,ta,za;r.each(function(eb,uc){A=m(uc);ta=A.offset().left;if(eb)za[1]=ta;za=[ta];O[eb]=za});za[1]=ta+A.outerWidth();if(i("allDaySlot")){A= +$;ta=A.offset().top;h[0]=[ta,ta+A.outerHeight()]}for(var Da=I.offset().top,Ea=w.offset().top,tc=Ea+w.outerHeight(),fb=0;fb
    "+Qa(W(o.start,o.end,u("timeFormat")))+"
    "+Qa(o.title)+"
    ";if(s.isEnd&&ga(o))v+="
    =
    "; +v+="";return v}function j(o,s,v){oa(o)&&y(o,s,v.isStart);v.isEnd&&ga(o)&&c(o,s,v);da(o,s)}function t(o,s,v){var F=s.find("div.fc-event-time");oa(o)&&S(o,s,F);v.isEnd&&ga(o)&&Q(o,s,F);da(o,s)}function y(o,s,v){function F(){if(!M){s.width(r).height("").draggable("option","grid",null);M=true}}var r,J,M=true,k,D=u("isRTL")?-1:1,Z=U(),ja=H(),ia=T(),la=ka();s.draggable({zIndex:9,opacity:u("dragOpacity","month"),revertDuration:u("dragRevertDuration"),start:function($,w){fa("eventDragStart", +s,o,$,w);i(o,s);r=s.width();Z.start(function(I,R,V,ea){B();if(I){J=false;k=ea*D;if(I.row)if(v){if(M){s.width(ja-10);Eb(s,ia*Math.round((o.end?(o.end-o.start)/wc:u("defaultEventMinutes"))/u("slotMinutes")));s.draggable("option","grid",[ja,1]);M=false}}else J=true;else{E(ba(N(o.start),k),ba(Ua(o),k));F()}J=J||M&&!k}else{F();J=true}s.draggable("option","revert",J)},$,"drag")},stop:function($,w){Z.stop();B();fa("eventDragStop",s,o,$,w);if(J){F();s.css("filter","");K(o,s)}else{var I=0;M||(I=Math.round((s.offset().top- +X().offset().top)/ia)*u("slotMinutes")+la-(o.start.getHours()*60+o.start.getMinutes()));C(this,o,k,I,M,$,w)}}})}function S(o,s,v){function F(I){var R=xa(N(o.start),I),V;if(o.end)V=xa(N(o.end),I);v.text(W(R,V,u("timeFormat")))}function r(){if(M){v.css("display","");s.draggable("option","grid",[$,w]);M=false}}var J,M=false,k,D,Z,ja=u("isRTL")?-1:1,ia=U(),la=z(),$=H(),w=T();s.draggable({zIndex:9,scroll:false,grid:[$,w],axis:la==1?"y":false,opacity:u("dragOpacity"),revertDuration:u("dragRevertDuration"), +start:function(I,R){fa("eventDragStart",s,o,I,R);i(o,s);J=s.position();D=Z=0;ia.start(function(V,ea,aa,va){s.draggable("option","revert",!V);B();if(V){k=va*ja;if(u("allDaySlot")&&!V.row){if(!M){M=true;v.hide();s.draggable("option","grid",null)}E(ba(N(o.start),k),ba(Ua(o),k))}else r()}},I,"drag")},drag:function(I,R){D=Math.round((R.position.top-J.top)/w)*u("slotMinutes");if(D!=Z){M||F(D);Z=D}},stop:function(I,R){var V=ia.stop();B();fa("eventDragStop",s,o,I,R);if(V&&(k||D||M))C(this,o,k,M?0:D,M,I,R); +else{r();s.css("filter","");s.css(J);F(0);K(o,s)}}})}function Q(o,s,v){var F,r,J=T();s.resizable({handles:{s:"div.ui-resizable-s"},grid:J,start:function(M,k){F=r=0;i(o,s);s.css("z-index",9);fa("eventResizeStart",this,o,M,k)},resize:function(M,k){F=Math.round((Math.max(J,s.height())-k.originalSize.height)/J);if(F!=r){v.text(W(o.start,!F&&!o.end?null:xa(ra(o),u("slotMinutes")*F),u("timeFormat")));r=F}},stop:function(M,k){fa("eventResizeStop",this,o,M,k);if(F)P(this,o,0,u("slotMinutes")*F,M,k);else{s.css("z-index", +8);K(o,s)}}})}var q=this;q.renderEvents=a;q.compileDaySegs=e;q.clearEvents=b;q.slotSegHtml=l;q.bindDaySeg=j;Qb.call(q);var u=q.opt,fa=q.trigger,oa=q.isEventDraggable,ga=q.isEventResizable,ra=q.eventEnd,sa=q.reportEvents,ha=q.reportEventClear,da=q.eventElementHandlers,na=q.setHeight,ua=q.getDaySegmentContainer,pa=q.getSlotSegmentContainer,U=q.getHoverListener,ca=q.getMaxMinute,ka=q.getMinMinute,qa=q.timePosition,G=q.colContentLeft,p=q.colContentRight,L=q.renderDaySegs,c=q.resizableDayEvent,z=q.getColCnt, +H=q.getColWidth,T=q.getSlotHeight,X=q.getBodyContent,ya=q.reportEventElement,K=q.showEvents,i=q.hideEvents,C=q.eventDrop,P=q.eventResize,E=q.renderDayOverlay,B=q.clearOverlays,n=q.calendar,Y=n.formatDate,W=n.formatDates}function vc(a){var b,e,d,f,g,l;for(b=a.length-1;b>0;b--){f=a[b];for(e=0;e"),B=z(),n=i.length,Y;E[0].innerHTML=e(i);E=E.children();B.append(E);d(i,E);l(i);j(i);t(i);Q(i,S(y()));E=[];for(B=0;B
    ";if(!n.allDay&&B.isStart)k+=""+Qa(T(n.start,n.end,fa("timeFormat")))+"";k+=""+Qa(n.title)+"
    ";if(B.isEnd&&ra(n))k+="
       
    ";k+="";B.left=r;B.outerWidth=J-r;B.startCol=v;B.endCol=F+1}return k}function d(i,C){var P,E=i.length,B,n,Y;for(P=0;P div");return P}function S(i){var C,P=i.length,E=[];for(C=0;C"));j[0].parentNode!=l[0]&&j.appendTo(l);d.push(j.css(g).show());return j}function b(){for(var g;g=d.shift();)f.push(g.hide().unbind())}var e=this;e.renderOverlay=a;e.clearOverlays=b;var d=[],f=[]}function Nb(a){var b=this,e,d;b.build=function(){e=[];d=[];a(e,d)};b.cell=function(f,g){var l=e.length,j=d.length, +t,y=-1,S=-1;for(t=0;t=e[t][0]&&g=d[t][0]&&f=0&&S>=0?{row:y,col:S}:null};b.rect=function(f,g,l,j,t){t=t.offset();return{top:e[f][0]-t.top,left:d[g][0]-t.left,width:d[j][1]-d[g][0],height:e[l][1]-e[f][0]}}}function Ob(a){function b(j){xc(j);j=a.cell(j.pageX,j.pageY);if(!j!=!l||j&&(j.row!=l.row||j.col!=l.col)){if(j){g||(g=j);f(j,g,j.row-g.row,j.col-g.col)}else f(j,g);l=j}}var e=this,d,f,g,l;e.start=function(j,t,y){f=j; +g=l=null;a.build();b(t);d=y||"mousemove";m(document).bind(d,b)};e.stop=function(){m(document).unbind(d,b);return l}}function xc(a){if(a.pageX===ma){a.pageX=a.originalEvent.pageX;a.pageY=a.originalEvent.pageY}}function Pb(a){function b(l){return d[l]=d[l]||a(l)}var e=this,d={},f={},g={};e.left=function(l){return f[l]=f[l]===ma?b(l).position().left:f[l]};e.right=function(l){return g[l]=g[l]===ma?e.left(l)+b(l).width():g[l]};e.clear=function(){d={};f={};g={}}}var Ya={defaultView:"month",aspectRatio:1.35, +header:{left:"title",center:"",right:"today prev,next"},weekends:true,allDayDefault:true,ignoreTimezone:true,lazyFetching:true,startParam:"start",endParam:"end",titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '—'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},columnFormat:{month:"ddd",week:"ddd M/d",day:"dddd M/d"},timeFormat:{"":"h(:mm)t"},isRTL:false,firstDay:0,monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan", +"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],buttonText:{prev:" ◄ ",next:" ► ",prevYear:" << ",nextYear:" >> ",today:"today",month:"month",week:"week",day:"day"},theme:false,buttonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e"},unselectAuto:true,dropAccept:"*"},yc= +{header:{left:"next,prev today",center:"",right:"title"},buttonText:{prev:" ► ",next:" ◄ ",prevYear:" >> ",nextYear:" << "},buttonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w"}},Aa=m.fullCalendar={version:"1.5.3"},Ja=Aa.views={};m.fn.fullCalendar=function(a){if(typeof a=="string"){var b=Array.prototype.slice.call(arguments,1),e;this.each(function(){var f=m.data(this,"fullCalendar");if(f&&m.isFunction(f[a])){f=f[a].apply(f, +b);if(e===ma)e=f;a=="destroy"&&m.removeData(this,"fullCalendar")}});if(e!==ma)return e;return this}var d=a.eventSources||[];delete a.eventSources;if(a.events){d.push(a.events);delete a.events}a=m.extend(true,{},Ya,a.isRTL||a.isRTL===ma&&Ya.isRTL?yc:{},a);this.each(function(f,g){f=m(g);g=new Yb(f,a,d);f.data("fullCalendar",g);g.render()});return this};Aa.sourceNormalizers=[];Aa.sourceFetchers=[];var ac={dataType:"json",cache:false},bc=1;Aa.addDays=ba;Aa.cloneDate=N;Aa.parseDate=kb;Aa.parseISO8601= +Bb;Aa.parseTime=mb;Aa.formatDate=Oa;Aa.formatDates=ib;var lc=["sun","mon","tue","wed","thu","fri","sat"],Ab=864E5,cc=36E5,wc=6E4,dc={s:function(a){return a.getSeconds()},ss:function(a){return Pa(a.getSeconds())},m:function(a){return a.getMinutes()},mm:function(a){return Pa(a.getMinutes())},h:function(a){return a.getHours()%12||12},hh:function(a){return Pa(a.getHours()%12||12)},H:function(a){return a.getHours()},HH:function(a){return Pa(a.getHours())},d:function(a){return a.getDate()},dd:function(a){return Pa(a.getDate())}, +ddd:function(a,b){return b.dayNamesShort[a.getDay()]},dddd:function(a,b){return b.dayNames[a.getDay()]},M:function(a){return a.getMonth()+1},MM:function(a){return Pa(a.getMonth()+1)},MMM:function(a,b){return b.monthNamesShort[a.getMonth()]},MMMM:function(a,b){return b.monthNames[a.getMonth()]},yy:function(a){return(a.getFullYear()+"").substring(2)},yyyy:function(a){return a.getFullYear()},t:function(a){return a.getHours()<12?"a":"p"},tt:function(a){return a.getHours()<12?"am":"pm"},T:function(a){return a.getHours()< +12?"A":"P"},TT:function(a){return a.getHours()<12?"AM":"PM"},u:function(a){return Oa(a,"yyyy-MM-dd'T'HH:mm:ss'Z'")},S:function(a){a=a.getDate();if(a>10&&a<20)return"th";return["st","nd","rd"][a%10-1]||"th"}};Aa.applyAll=$a;Ja.month=mc;Ja.basicWeek=nc;Ja.basicDay=oc;wb({weekMode:"fixed"});Ja.agendaWeek=qc;Ja.agendaDay=rc;wb({allDaySlot:true,allDayText:"all-day",firstHour:6,slotMinutes:30,defaultEventMinutes:120,axisFormat:"h(:mm)tt",timeFormat:{agenda:"h:mm{ - h:mm}"},dragOpacity:{agenda:0.5},minTime:0, +maxTime:24})})(jQuery); diff --git a/3rdparty/fullcalendar/fullcalendar.print.css b/3rdparty/fullcalendar/fullcalendar.print.css new file mode 100644 index 00000000000..e11c1816373 --- /dev/null +++ b/3rdparty/fullcalendar/fullcalendar.print.css @@ -0,0 +1,61 @@ +/* + * FullCalendar v1.5.3 Print Stylesheet + * + * Include this stylesheet on your page to get a more printer-friendly calendar. + * When including this stylesheet, use the media='print' attribute of the tag. + * Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css. + * + * Copyright (c) 2011 Adam Shaw + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Mon Feb 6 22:40:40 2012 -0800 + * + */ + + + /* Events +-----------------------------------------------------*/ + +.fc-event-skin { + background: none !important; + color: #000 !important; + } + +/* horizontal events */ + +.fc-event-hori { + border-width: 0 0 1px 0 !important; + border-bottom-style: dotted !important; + border-bottom-color: #000 !important; + padding: 1px 0 0 0 !important; + } + +.fc-event-hori .fc-event-inner { + border-width: 0 !important; + padding: 0 1px !important; + } + +/* vertical events */ + +.fc-event-vert { + border-width: 0 0 0 1px !important; + border-left-style: dotted !important; + border-left-color: #000 !important; + padding: 0 1px 0 0 !important; + } + +.fc-event-vert .fc-event-inner { + border-width: 0 !important; + padding: 1px 0 !important; + } + +.fc-event-bg { + display: none !important; + } + +.fc-event .ui-resizable-handle { + display: none !important; + } + + diff --git a/3rdparty/fullcalendar/gcal.js b/3rdparty/fullcalendar/gcal.js new file mode 100644 index 00000000000..e9bbe26d824 --- /dev/null +++ b/3rdparty/fullcalendar/gcal.js @@ -0,0 +1,112 @@ +/* + * FullCalendar v1.5.3 Google Calendar Plugin + * + * Copyright (c) 2011 Adam Shaw + * Dual licensed under the MIT and GPL licenses, located in + * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. + * + * Date: Mon Feb 6 22:40:40 2012 -0800 + * + */ + +(function($) { + + +var fc = $.fullCalendar; +var formatDate = fc.formatDate; +var parseISO8601 = fc.parseISO8601; +var addDays = fc.addDays; +var applyAll = fc.applyAll; + + +fc.sourceNormalizers.push(function(sourceOptions) { + if (sourceOptions.dataType == 'gcal' || + sourceOptions.dataType === undefined && + (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { + sourceOptions.dataType = 'gcal'; + if (sourceOptions.editable === undefined) { + sourceOptions.editable = false; + } + } +}); + + +fc.sourceFetchers.push(function(sourceOptions, start, end) { + if (sourceOptions.dataType == 'gcal') { + return transformOptions(sourceOptions, start, end); + } +}); + + +function transformOptions(sourceOptions, start, end) { + + var success = sourceOptions.success; + var data = $.extend({}, sourceOptions.data || {}, { + 'start-min': formatDate(start, 'u'), + 'start-max': formatDate(end, 'u'), + 'singleevents': true, + 'max-results': 9999 + }); + + var ctz = sourceOptions.currentTimezone; + if (ctz) { + data.ctz = ctz = ctz.replace(' ', '_'); + } + + return $.extend({}, sourceOptions, { + url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', + dataType: 'jsonp', + data: data, + startParam: false, + endParam: false, + success: function(data) { + var events = []; + if (data.feed.entry) { + $.each(data.feed.entry, function(i, entry) { + var startStr = entry['gd$when'][0]['startTime']; + var start = parseISO8601(startStr, true); + var end = parseISO8601(entry['gd$when'][0]['endTime'], true); + var allDay = startStr.indexOf('T') == -1; + var url; + $.each(entry.link, function(i, link) { + if (link.type == 'text/html') { + url = link.href; + if (ctz) { + url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; + } + } + }); + if (allDay) { + addDays(end, -1); // make inclusive + } + events.push({ + id: entry['gCal$uid']['value'], + title: entry['title']['$t'], + url: url, + start: start, + end: end, + allDay: allDay, + location: entry['gd$where'][0]['valueString'], + description: entry['content']['$t'] + }); + }); + } + var args = [events].concat(Array.prototype.slice.call(arguments, 1)); + var res = applyAll(success, this, args); + if ($.isArray(res)) { + return res; + } + return events; + } + }); + +} + + +// legacy +fc.gcalFeed = function(url, sourceOptions) { + return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); +}; + + +})(jQuery); -- GitLab From 44fa4433bc4bda437bf6c88a5020af075fb797d8 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Sun, 22 Apr 2012 21:17:56 +0200 Subject: [PATCH 233/430] move files of fullcalendar 1.5.3 --- 3rdparty/fullcalendar/{ => css}/fullcalendar.css | 0 3rdparty/fullcalendar/{ => css}/fullcalendar.print.css | 0 3rdparty/fullcalendar/{ => js}/fullcalendar.js | 0 3rdparty/fullcalendar/{ => js}/fullcalendar.min.js | 0 3rdparty/fullcalendar/{ => js}/gcal.js | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename 3rdparty/fullcalendar/{ => css}/fullcalendar.css (100%) rename 3rdparty/fullcalendar/{ => css}/fullcalendar.print.css (100%) rename 3rdparty/fullcalendar/{ => js}/fullcalendar.js (100%) rename 3rdparty/fullcalendar/{ => js}/fullcalendar.min.js (100%) rename 3rdparty/fullcalendar/{ => js}/gcal.js (100%) diff --git a/3rdparty/fullcalendar/fullcalendar.css b/3rdparty/fullcalendar/css/fullcalendar.css similarity index 100% rename from 3rdparty/fullcalendar/fullcalendar.css rename to 3rdparty/fullcalendar/css/fullcalendar.css diff --git a/3rdparty/fullcalendar/fullcalendar.print.css b/3rdparty/fullcalendar/css/fullcalendar.print.css similarity index 100% rename from 3rdparty/fullcalendar/fullcalendar.print.css rename to 3rdparty/fullcalendar/css/fullcalendar.print.css diff --git a/3rdparty/fullcalendar/fullcalendar.js b/3rdparty/fullcalendar/js/fullcalendar.js similarity index 100% rename from 3rdparty/fullcalendar/fullcalendar.js rename to 3rdparty/fullcalendar/js/fullcalendar.js diff --git a/3rdparty/fullcalendar/fullcalendar.min.js b/3rdparty/fullcalendar/js/fullcalendar.min.js similarity index 100% rename from 3rdparty/fullcalendar/fullcalendar.min.js rename to 3rdparty/fullcalendar/js/fullcalendar.min.js diff --git a/3rdparty/fullcalendar/gcal.js b/3rdparty/fullcalendar/js/gcal.js similarity index 100% rename from 3rdparty/fullcalendar/gcal.js rename to 3rdparty/fullcalendar/js/gcal.js -- GitLab From c5b31b001a12e4035555c6b507b6347bce90e272 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 19 Apr 2012 16:36:07 +0200 Subject: [PATCH 234/430] add the option to disable file encryption while still being able to decrypt existing files --- apps/files_encryption/js/settings.js | 5 +++++ apps/files_encryption/lib/proxy.php | 6 +++--- apps/files_encryption/settings.php | 2 ++ apps/files_encryption/templates/settings.php | 1 + 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/files_encryption/js/settings.js b/apps/files_encryption/js/settings.js index adbf0c87245..37d62265c94 100644 --- a/apps/files_encryption/js/settings.js +++ b/apps/files_encryption/js/settings.js @@ -16,4 +16,9 @@ $(document).ready(function(){ var blackList=$('#encryption_blacklist').val().join(','); OC.AppConfig.setValue('files_encryption','type_blacklist',blackList); } + + $('#enbale_encryption').change(function(){ + var checked=$('#enbale_encryption').is(':checked'); + OC.AppConfig.setValue('files_encryption','enable_encryption',(checked)?'true':'false'); + }) }) \ No newline at end of file diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index a0de411a7b6..e3a106d0d04 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -36,10 +36,10 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ * @return bool */ private static function shouldEncrypt($path){ - if(is_null($this->enableEncryption)){ - $this->enableEncryption=(OC_Appconfig::getValue('files_encryption','enabled','true')=='true'); + if(is_null(self::$enableEncryption)){ + self::$enableEncryption=(OC_Appconfig::getValue('files_encryption','enable_encryption','true')=='true'); } - if(!$this->enableEncryption){ + if(!self::$enableEncryption){ return false; } if(is_null(self::$blackList)){ diff --git a/apps/files_encryption/settings.php b/apps/files_encryption/settings.php index 396ad1ba78d..01caefd1249 100644 --- a/apps/files_encryption/settings.php +++ b/apps/files_encryption/settings.php @@ -8,7 +8,9 @@ $tmpl = new OC_Template( 'files_encryption', 'settings'); $blackList=explode(',',OC_Appconfig::getValue('files_encryption','type_blacklist','jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg')); +$enabled=(OC_Appconfig::getValue('files_encryption','enable_encryption','true')=='true'); $tmpl->assign('blacklist',$blackList); +$tmpl->assign('encryption_enabled',$enabled); OC_Util::addScript('files_encryption','settings'); OC_Util::addScript('core','multiselect'); diff --git a/apps/files_encryption/templates/settings.php b/apps/files_encryption/templates/settings.php index 724a03836a8..25b5a06f56c 100644 --- a/apps/files_encryption/templates/settings.php +++ b/apps/files_encryption/templates/settings.php @@ -7,5 +7,6 @@ + >
    -- GitLab From d17eba19c1dc2be936cd00747e6cead33c19e59a Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 19 Apr 2012 17:42:15 +0200 Subject: [PATCH 235/430] fix image viewer --- apps/files_imageviewer/js/lightbox.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/files_imageviewer/js/lightbox.js b/apps/files_imageviewer/js/lightbox.js index 6c97466e6d6..c0f569de351 100644 --- a/apps/files_imageviewer/js/lightbox.js +++ b/apps/files_imageviewer/js/lightbox.js @@ -18,7 +18,7 @@ $(document).ready(function() { }); function viewImage(dir, file) { - if(file.indexOf('.psd')){//can't view those + if(file.indexOf('.psd')>0){//can't view those return; } var location=OC.filePath('files','ajax','download.php')+'?files='+file+'&dir='+dir; -- GitLab From 8f2e9caf962e51105b94232b0120705bf2d31e1c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 22 Apr 2012 22:58:48 +0200 Subject: [PATCH 236/430] Contacts: Tipsyfied photo toolbar. --- apps/contacts/js/contacts.js | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index 45b2fe130e2..f03ae1e46d6 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1084,6 +1084,7 @@ Contacts={ } }, loadPhotoHandlers:function(){ + $('#phototools li a').tipsy(); $('#contacts_details_photo_wrapper').hover( function () { $('#phototools').slideDown(200); -- GitLab From 82ba2151d176e7e0e1ebcfde8de6db46f651dad4 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 23 Apr 2012 10:51:25 +0200 Subject: [PATCH 237/430] Wrong app check. --- apps/contacts/import.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/contacts/import.php b/apps/contacts/import.php index 04cfc397d56..233ed5be22f 100644 --- a/apps/contacts/import.php +++ b/apps/contacts/import.php @@ -9,7 +9,7 @@ ob_start(); require_once ('../../lib/base.php'); OC_JSON::checkLoggedIn(); -OC_Util::checkAppEnabled('calendar'); +OC_Util::checkAppEnabled('contacts'); $nl = "\n"; $progressfile = 'import_tmp/' . md5(session_id()) . '.txt'; if(is_writable('import_tmp/')){ -- GitLab From fffbf261590c15bac92e9437fe7d4b99a485a072 Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Mon, 23 Apr 2012 11:21:13 +0200 Subject: [PATCH 238/430] don't forget to declare class properties --- apps/user_ldap/group_ldap.php | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/user_ldap/group_ldap.php b/apps/user_ldap/group_ldap.php index e5948459dd0..b1619e06530 100644 --- a/apps/user_ldap/group_ldap.php +++ b/apps/user_ldap/group_ldap.php @@ -25,6 +25,7 @@ class OC_GROUP_LDAP extends OC_Group_Backend { // //group specific settings protected $ldapGroupFilter; protected $ldapGroupDisplayName; + protected $ldapGroupMemberAttr; public function __construct() { $this->ldapGroupFilter = OC_Appconfig::getValue('user_ldap', 'ldap_group_filter', '(objectClass=posixGroup)'); -- GitLab From 6ee7dc5f590e26f54d2a986a72bb328ed0b0db8f Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Mon, 23 Apr 2012 12:32:17 +0200 Subject: [PATCH 239/430] only retrieve requested attributes --- apps/user_ldap/lib_ldap.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/user_ldap/lib_ldap.php b/apps/user_ldap/lib_ldap.php index eea4a82011c..1016b955dcb 100644 --- a/apps/user_ldap/lib_ldap.php +++ b/apps/user_ldap/lib_ldap.php @@ -73,7 +73,7 @@ class OC_LDAP { * Executes an LDAP search */ static public function search($filter, $attr = null) { - $sr = ldap_search(self::getConnectionResource(), self::$ldapBase, $filter); + $sr = ldap_search(self::getConnectionResource(), self::$ldapBase, $filter, array($attr)); $findings = ldap_get_entries(self::getConnectionResource(), $sr ); if(!is_null($attr)) { -- GitLab From 912c87eedaa3ea909d5721d8066fa4455529aa1b Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Mon, 23 Apr 2012 13:04:58 +0200 Subject: [PATCH 240/430] LDAP: optimize LDAP requests for users and groups. Settings are still to do, though. --- apps/user_ldap/group_ldap.php | 27 ++++++++++++------------- apps/user_ldap/lib_ldap.php | 37 ++++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 18 deletions(-) diff --git a/apps/user_ldap/group_ldap.php b/apps/user_ldap/group_ldap.php index b1619e06530..fe0789cdeb7 100644 --- a/apps/user_ldap/group_ldap.php +++ b/apps/user_ldap/group_ldap.php @@ -47,14 +47,12 @@ class OC_GROUP_LDAP extends OC_Group_Backend { LDAP_GROUP_MEMBER_ASSOC_ATTR.'='.$uid, $this->ldapGroupDisplayName.'='.$gid )); - $groups = OC_LDAP::search($filter, $this->ldapGroupDisplayName); + $groups = $this->retrieveList($filter, $this->ldapGroupDisplayName); - if(count($groups) == 1) { + if(count($groups) > 0) { return true; - } else if(count($groups) < 1) { - return false; } else { - throw new Exception('Too many groups of the same name!? – this exception should never been thrown :)'); + return false; } } @@ -85,7 +83,7 @@ class OC_GROUP_LDAP extends OC_Group_Backend { $this->ldapGroupDisplayName.'='.$gid )); - return $this->retrieveList($filter, $this->ldapGroupMemberAttr); + return $this->retrieveList($filter, $this->ldapGroupMemberAttr, false); } /** @@ -95,13 +93,7 @@ class OC_GROUP_LDAP extends OC_Group_Backend { * Returns a list with all groups */ public function getGroups() { - $groups = OC_LDAP::search($this->ldapGroupFilter, $this->ldapGroupDisplayName); - - if(count($groups) == 0 ) - return array(); - else { - return array_unique($groups, SORT_LOCALE_STRING); - } + return $this->retrieveList($this->ldapGroupFilter, $this->ldapGroupDisplayName); } /** @@ -113,8 +105,13 @@ class OC_GROUP_LDAP extends OC_Group_Backend { return in_array($gid, $this->getGroups()); } - private function retrieveList($filter, $attr) { - $list = OC_LDAP::search($filter, $attr); + private function retrieveList($filter, $attr, $searchForGroups = true) { + if($searchForGroups) { + $list = OC_LDAP::searchGroups($filter, $attr); + } else { + $list = OC_LDAP::searchUsers($filter, $attr); + } + if(is_array($list)) { return array_unique($list, SORT_LOCALE_STRING); diff --git a/apps/user_ldap/lib_ldap.php b/apps/user_ldap/lib_ldap.php index 1016b955dcb..752ac4f2289 100644 --- a/apps/user_ldap/lib_ldap.php +++ b/apps/user_ldap/lib_ldap.php @@ -38,6 +38,8 @@ class OC_LDAP { static protected $ldapHost; static protected $ldapPort; static protected $ldapBase; + static protected $ldapBaseUsers; + static protected $ldapBaseGroups; static protected $ldapAgentName; static protected $ldapAgentPassword; static protected $ldapTLS; @@ -64,16 +66,41 @@ class OC_LDAP { } } + /** + * @brief executes an LDAP search, optimized for Users + * @param $filter the LDAP filter for the search + * @param $attr optional, when a certain attribute shall be filtered out + * @returns array with the search result + * + * Executes an LDAP search + */ + static public function searchUsers($filter, $attr = null) { + return self::search($filter, self::$ldapBaseUsers, $attr); + } + + /** + * @brief executes an LDAP search, optimized for Groups + * @param $filter the LDAP filter for the search + * @param $attr optional, when a certain attribute shall be filtered out + * @returns array with the search result + * + * Executes an LDAP search + */ + static public function searchGroups($filter, $attr = null) { + return self::search($filter, self::$ldapBaseGroups, $attr); + } + /** * @brief executes an LDAP search * @param $filter the LDAP filter for the search + * @param $base the LDAP subtree that shall be searched * @param $attr optional, when a certain attribute shall be filtered out * @returns array with the search result * * Executes an LDAP search */ - static public function search($filter, $attr = null) { - $sr = ldap_search(self::getConnectionResource(), self::$ldapBase, $filter, array($attr)); + static private function search($filter, $base, $attr = null) { + $sr = ldap_search(self::getConnectionResource(), $base, $filter, array($attr)); $findings = ldap_get_entries(self::getConnectionResource(), $sr ); if(!is_null($attr)) { @@ -150,7 +177,9 @@ class OC_LDAP { self::$ldapPort = OC_Appconfig::getValue('user_ldap', 'ldap_port', OC_USER_BACKEND_LDAP_DEFAULT_PORT); self::$ldapAgentName = OC_Appconfig::getValue('user_ldap', 'ldap_dn',''); self::$ldapAgentPassword = OC_Appconfig::getValue('user_ldap', 'ldap_password',''); - self::$ldapBase = OC_Appconfig::getValue('user_ldap', 'ldap_base',''); + self::$ldapBase = OC_Appconfig::getValue('user_ldap', 'ldap_base', ''); + self::$ldapBaseUsers = OC_Appconfig::getValue('user_ldap', 'ldap_base_users',self::$ldapBase); + self::$ldapBaseGroups = OC_Appconfig::getValue('user_ldap', 'ldap_base_groups', self::$ldapBase); self::$ldapTLS = OC_Appconfig::getValue('user_ldap', 'ldap_tls',0); self::$ldapNoCase = OC_Appconfig::getValue('user_ldap', 'ldap_nocase', 0); self::$ldapUserDisplayName = OC_Appconfig::getValue('user_ldap', 'ldap_display_name', OC_USER_BACKEND_LDAP_DEFAULT_DISPLAY_NAME); @@ -163,6 +192,8 @@ class OC_LDAP { || ( empty(self::$ldapAgentName) && empty(self::$ldapAgentPassword)) ) && !empty(self::$ldapBase) + && !empty(self::$ldapBaseUsers) + && !empty(self::$ldapBaseGroups) && !empty(self::$ldapUserDisplayName) ) { -- GitLab From 3ba9a9e6a8a49277583a56543fe8a55f985da564 Mon Sep 17 00:00:00 2001 From: Jan-Christoph Borchardt Date: Mon, 23 Apr 2012 14:19:03 +0200 Subject: [PATCH 241/430] adding proper copyright and license notice to the style files --- apps/files_sharing/css/sharing.css | 6 +++++- apps/media/css/music.css | 4 ++++ core/css/multiselect.css | 4 ++++ core/css/styles.css | 2 +- files/css/files.css | 2 +- search/css/results.css | 4 ++++ settings/css/settings.css | 4 ++++ 7 files changed, 23 insertions(+), 3 deletions(-) diff --git a/apps/files_sharing/css/sharing.css b/apps/files_sharing/css/sharing.css index db59a3d340b..5acd9af589a 100644 --- a/apps/files_sharing/css/sharing.css +++ b/apps/files_sharing/css/sharing.css @@ -1,3 +1,7 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + #dropdown { display:block; position:absolute; z-index:100; width:16em; right:0; margin-right:7em; background:#eee; padding:1em; -moz-box-shadow:0 1px 1px #777; -webkit-box-shadow:0 1px 1px #777; box-shadow:0 1px 1px #777; -moz-border-radius-bottomleft:1em; -webkit-border-bottom-left-radius:1em; border-bottom-left-radius:1em; @@ -6,4 +10,4 @@ #public { border-top:1px solid #ddd; padding-top:0.5em; } a.unshare { float:right; display:inline; margin:0 .5em; padding:.3em .3em 0 .3em !important; opacity:.5; } a.unshare:hover { opacity:1; } -#share_with { width: 16em; } \ No newline at end of file +#share_with { width: 16em; } diff --git a/apps/media/css/music.css b/apps/media/css/music.css index 164a6c62ae6..c782e8afeeb 100644 --- a/apps/media/css/music.css +++ b/apps/media/css/music.css @@ -1,3 +1,7 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + #controls ul.jp-controls { padding:0; } #controls ul.jp-controls li { display:inline; } #controls ul.jp-controls li a { position:absolute; padding:.8em 1em .8em 0; } diff --git a/core/css/multiselect.css b/core/css/multiselect.css index 1202ea18427..3dac0ea1a16 100644 --- a/core/css/multiselect.css +++ b/core/css/multiselect.css @@ -1,3 +1,7 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + ul.multiselectoptions { z-index:49; position:absolute; background-color:#fff; padding-top:.5em; border:1px solid #ddd; border-top:none; -moz-border-radius-bottomleft:.5em; -webkit-border-bottom-left-radius:.5em; border-bottom-left-radius:.5em; -moz-border-radius-bottomright:.5em; -webkit-border-bottom-right-radius:.5em; border-bottom-right-radius:.5em; -moz-box-shadow:0 1px 1px #ddd; -webkit-box-shadow:0 1px 1px #ddd; box-shadow:0 1px 1px #ddd; } ul.multiselectoptions>li{ white-space:nowrap; overflow: hidden; } div.multiselect { padding-right:.6em; display:inline; position:relative; display:inline-block; vertical-align: bottom; } diff --git a/core/css/styles.css b/core/css/styles.css index ccebc984fbb..945e5846683 100644 --- a/core/css/styles.css +++ b/core/css/styles.css @@ -1,4 +1,4 @@ -/* Copyright (c) 2011, Jan-Christoph Borchardt +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net This file is licensed under the Affero General Public License version 3 or later. See the COPYING-README file. */ diff --git a/files/css/files.css b/files/css/files.css index fd551b27625..2cf4f38fd20 100644 --- a/files/css/files.css +++ b/files/css/files.css @@ -1,4 +1,4 @@ -/* Copyright (c) 2011, Jan-Christoph Borchardt +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net This file is licensed under the Affero General Public License version 3 or later. See the COPYING-README file. */ diff --git a/search/css/results.css b/search/css/results.css index 440e68ee48f..40d5563e89e 100644 --- a/search/css/results.css +++ b/search/css/results.css @@ -1,3 +1,7 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + #searchresults { list-style:none; position:fixed; top:3.5em; right:0; z-index:75; background-color:#fff; overflow:hidden; text-overflow:ellipsis; max-height:80%; width:26.5em; padding-bottom:1em; -moz-box-shadow:0 0 10px #000; -webkit-box-shadow:0 0 10px #000; box-shadow:0 0 10px #000; -moz-border-radius-bottomleft:1em; -webkit-border-bottom-left-radius:1em; border-bottom-left-radius:1em; } #searchresults li.resultHeader { font-size:1.2em; font-weight:bold; border-bottom:solid 1px #CCC; padding:.2em; background-color:#eee; } #searchresults li.result { margin-left:2em; } diff --git a/settings/css/settings.css b/settings/css/settings.css index 62e84654d55..36d9b8d26f9 100644 --- a/settings/css/settings.css +++ b/settings/css/settings.css @@ -1,3 +1,7 @@ +/* Copyright (c) 2011, Jan-Christoph Borchardt, http://jancborchardt.net + This file is licensed under the Affero General Public License version 3 or later. + See the COPYING-README file. */ + select#languageinput, select#timezone { width:15em; } input#openid, input#webdav { width:20em; } -- GitLab From 1b29fc3fb2b090ca132cbe496276c3c0cc2e466e Mon Sep 17 00:00:00 2001 From: Jan-Christoph Borchardt Date: Mon, 23 Apr 2012 14:29:11 +0200 Subject: [PATCH 242/430] fixing multiselect overflow, issue 341 --- core/css/multiselect.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/css/multiselect.css b/core/css/multiselect.css index 3dac0ea1a16..040b0f46ed3 100644 --- a/core/css/multiselect.css +++ b/core/css/multiselect.css @@ -4,8 +4,8 @@ ul.multiselectoptions { z-index:49; position:absolute; background-color:#fff; padding-top:.5em; border:1px solid #ddd; border-top:none; -moz-border-radius-bottomleft:.5em; -webkit-border-bottom-left-radius:.5em; border-bottom-left-radius:.5em; -moz-border-radius-bottomright:.5em; -webkit-border-bottom-right-radius:.5em; border-bottom-right-radius:.5em; -moz-box-shadow:0 1px 1px #ddd; -webkit-box-shadow:0 1px 1px #ddd; box-shadow:0 1px 1px #ddd; } ul.multiselectoptions>li{ white-space:nowrap; overflow: hidden; } -div.multiselect { padding-right:.6em; display:inline; position:relative; display:inline-block; vertical-align: bottom; } +div.multiselect { padding-right:.6em; display:inline; position:relative; display:inline-block; vertical-align: bottom; min-width:100px; max-width:400px; } div.multiselect.active { background-color:#fff; border-bottom:none; border-bottom-left-radius:0; border-bottom-right-radius:0; z-index:50; position:relative } -div.multiselect>span:first-child { margin-right:2em; float:left; } -div.multiselect>span:last-child { float:right; position:relative } +div.multiselect>span:first-child { margin-right:2em; float:left; width:90%; overflow:hidden; text-overflow:ellipsis; } +div.multiselect>span:last-child { position:absolute; right:.8em; } ul.multiselectoptions input.new{ margin:0; padding-bottom:0.2em; padding-top:0.2em; border-top-left-radius:0; border-top-right-radius:0; } -- GitLab From f5c9fe9ece6fdfb35bab5eefdf83830b5045b5a8 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Mon, 23 Apr 2012 15:50:30 +0200 Subject: [PATCH 243/430] =?UTF-8?q?first=20step=20to=20an=20public=20api?= =?UTF-8?q?=20of=20ownCloud=20for=20the=20apps.=20In=20the=20future=20they?= =?UTF-8?q?=20shouldn=C2=B4t=20call=20internall=20classes,=20functions=20o?= =?UTF-8?q?r=20session=20variables=20because=20this=20will=20change=20and?= =?UTF-8?q?=20break=20in=20upcoming=20versions.=20Apps=20should=20only=20c?= =?UTF-8?q?all=20this=20public=20interface=20that=20we=20will=20kepp=20sta?= =?UTF-8?q?ble=20over=20different=20releases.=20The=20namespace=20is=20OCP?= =?UTF-8?q?=20for=20ownCloud=20public.=20This=20is=20just=20the=20first=20?= =?UTF-8?q?step.=20more=20coming=20soon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/base.php | 3 +++ lib/public/util.php | 60 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 lib/public/util.php diff --git a/lib/base.php b/lib/base.php index f3dacdc0f76..5c42000b9e1 100644 --- a/lib/base.php +++ b/lib/base.php @@ -81,6 +81,9 @@ class OC{ elseif(strpos($className,'OC_')===0){ require_once strtolower(str_replace('_','/',substr($className,3)) . '.php'); } + elseif(strpos($className,'OCP\\')===0){ + require_once 'public/'.strtolower(str_replace('\\','/',substr($className,3)) . '.php'); + } elseif(strpos($className,'Sabre_')===0) { require_once str_replace('_','/',$className) . '.php'; } diff --git a/lib/public/util.php b/lib/public/util.php new file mode 100644 index 00000000000..3425ed9df3b --- /dev/null +++ b/lib/public/util.php @@ -0,0 +1,60 @@ +. +* +*/ + +/** + * Public interface of ownCloud for apps to use. + * Utility Class. + * + */ + +// use OCP namespace for all classes that are considered public. +// This means that they should be used by apps instead of the internal ownCloud classes +namespace OCP; + +class Util { + + /** + * send an email + * + * @param string $toaddress + * @param string $toname + * @param string $subject + * @param string $mailtext + * @param string $fromaddress + * @param string $fromname + * @param bool $html + */ + public static function sendmail($toaddress,$toname,$subject,$mailtext,$fromaddress,$fromname,$html=0,$altbody='',$ccaddress='',$ccname='',$bcc='') { + + // call the internal mail class + OC_MAIL::send($toaddress,$toname,$subject,$mailtext,$fromaddress,$fromname,$html=0,$altbody='',$ccaddress='',$ccname='',$bcc=''); + + } + + + +} + + + + +?> -- GitLab From 08fe6bdb27878e0fd860969b4a3325e12cde22fc Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 16:17:35 +0200 Subject: [PATCH 244/430] fix path in /apps/files/js/timezone.php --- apps/files/js/timezone.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/files/js/timezone.js b/apps/files/js/timezone.js index d569683f210..4749417199d 100644 --- a/apps/files/js/timezone.js +++ b/apps/files/js/timezone.js @@ -3,7 +3,7 @@ $(document).ready(function() { var visitortimezone = (-new Date().getTimezoneOffset()/60); $.ajax({ type: "GET", - url: "ajax/timezone.php", + url: OC.filePath('files', 'ajax', 'timezone.php'), data: 'time='+ visitortimezone, success: function(){ location.reload(); -- GitLab From c0df15367ff411bb8bf8c58f74027ed7c1275e9e Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 16:18:15 +0200 Subject: [PATCH 245/430] fix style.css of the files app --- apps/files/css/files.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/files/css/files.css b/apps/files/css/files.css index fd551b27625..d50d9aa9c5a 100644 --- a/apps/files/css/files.css +++ b/apps/files/css/files.css @@ -20,7 +20,7 @@ #new>ul>li>p { cursor:pointer; } #new>ul>li>input { padding:0.3em; margin:-0.3em; } -#file_newfolder_name { background-image:url('../../core/img/places/folder.svg'); font-weight:normal; width:7em; } +#file_newfolder_name { background-image:url('../../../core/img/places/folder.svg'); font-weight:normal; width:7em; } .file_upload_start, .file_upload_filename { font-size:1em; } #file_newfolder_submit, #file_upload_submit { width:3em; } .file_upload_target { display:none; } @@ -81,7 +81,7 @@ a.action>img { max-height:16px; max-width:16px; vertical-align:text-bottom; } .selectedActions a img { position:relative; top:.3em; } /* add breadcrumb divider to the File item in navigation panel */ -#navigation>ul>li:first-child { background:url('../../core/img/breadcrumb-start.svg') no-repeat 12.5em 0px; width:12.5em; padding-right:1em; position:fixed; } +#navigation>ul>li:first-child { background:url('../../../core/img/breadcrumb-start.svg') no-repeat 12.5em 0px; width:12.5em; padding-right:1em; position:fixed; } #navigation>ul>li:first-child+li { padding-top:2.9em; } #scanning-message{ top:40%; left:40%; position:absolute; display:none } -- GitLab From 3b9d28324519993e032a8c743bd8caf52f99bf1e Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 16:25:07 +0200 Subject: [PATCH 246/430] fix path in apps/files/templats/index.php --- apps/files/templates/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/files/templates/index.php b/apps/files/templates/index.php index b21cf0aeb02..3571950467e 100644 --- a/apps/files/templates/index.php +++ b/apps/files/templates/index.php @@ -12,7 +12,7 @@
    -
    + -- GitLab From aaedb23f055d0b6465743e79fa97cc8b02121a35 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 16:28:37 +0200 Subject: [PATCH 247/430] fix bug in lib/helper.php and fix file upload --- lib/helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/helper.php b/lib/helper.php index 34f8faad4a5..d68830fe483 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -44,7 +44,7 @@ class OC_Helper { if(substr($app, -1, 1) == '/'){ $app = substr($app, 0, strlen($app) - 1); } - $urlLinkTo = OC::$WEBROOT . '?app=' . $app; + $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; $urlLinkTo .= ($file!='index.php')?'&file=' . $file:''; } else{ -- GitLab From 9226cb7a6a029ef1257eee46cd22044a294b0d5f Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 16:36:24 +0200 Subject: [PATCH 248/430] rename var file to getfile to prevent fails in files app --- core/js/js.js | 2 +- lib/base.php | 6 +++--- lib/helper.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core/js/js.js b/core/js/js.js index 9b0a159b5c2..4abaced1ae0 100644 --- a/core/js/js.js +++ b/core/js/js.js @@ -53,7 +53,7 @@ OC={ var isCore=OC.coreApps.indexOf(app)!=-1; var link=OC.webroot; if(file.substring(file.length-3) == 'php' && !isCore){ - link+='/?app=' + app + '&file=' + type + '/' + file; + link+='/?app=' + app + '&getfile=' + type + '/' + file; }else{ link+='/'; app+='/'; diff --git a/lib/base.php b/lib/base.php index df240dca6df..4800a426217 100644 --- a/lib/base.php +++ b/lib/base.php @@ -399,16 +399,16 @@ class OC{ register_shutdown_function(array('OC_Helper','cleanTmp')); self::$REQUESTEDAPP = (isset($_GET['app'])?strip_tags($_GET['app']):'files'); - self::$REQUESTEDFILE = $_GET['file']; + self::$REQUESTEDFILE = $_GET['getfile']; if(substr_count(self::$REQUESTEDFILE, '?') != 0){ $pos_questionmark = strpos(self::$REQUESTEDFILE, '?'); $pos_equal = strpos(self::$REQUESTEDFILE, '='); $pos_and = strpos(self::$REQUESTEDFILE, '?'); $_GET[substr(self::$REQUESTEDFILE, $pos_questionmark + 1, $pos_equal - $pos_questionmark - 1)] = substr(self::$REQUESTEDFILE, $pos_equal + 1, $pos_and); self::$REQUESTEDFILE = substr(self::$REQUESTEDFILE, 0, $pos_questionmark); - $_GET['file'] = OC::$REQUESTEDFILE; + $_GET['getfile'] = OC::$REQUESTEDFILE; } - self::$REQUESTEDFILE = (isset($_GET['file'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . self::$REQUESTEDFILE, OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?self::$REQUESTEDFILE:null):null); + self::$REQUESTEDFILE = (isset($_GET['getfile'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . self::$REQUESTEDFILE, OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?self::$REQUESTEDFILE:null):null); } } diff --git a/lib/helper.php b/lib/helper.php index d68830fe483..2067190bca7 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -45,7 +45,7 @@ class OC_Helper { $app = substr($app, 0, strlen($app) - 1); } $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; - $urlLinkTo .= ($file!='index.php')?'&file=' . $file:''; + $urlLinkTo .= ($file!='index.php')?'&getfile=' . $file:''; } else{ $urlLinkTo = OC::$WEBROOT . '/' . $app . $file; -- GitLab From 6d92ebca454ab2e6533d0b7a08bfe30d20005820 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 17:09:28 +0200 Subject: [PATCH 249/430] use native functions of php to parse the string into the Var --- core/js/js.js | 2 +- lib/base.php | 13 ++++++------- lib/helper.php | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/core/js/js.js b/core/js/js.js index 4abaced1ae0..b4482185509 100644 --- a/core/js/js.js +++ b/core/js/js.js @@ -53,7 +53,7 @@ OC={ var isCore=OC.coreApps.indexOf(app)!=-1; var link=OC.webroot; if(file.substring(file.length-3) == 'php' && !isCore){ - link+='/?app=' + app + '&getfile=' + type + '/' + file; + link+='/?app=' + app + '&getfile=' + encodeURI(type + '/' + file); }else{ link+='/'; app+='/'; diff --git a/lib/base.php b/lib/base.php index 4800a426217..559d49ca997 100644 --- a/lib/base.php +++ b/lib/base.php @@ -284,7 +284,7 @@ class OC{ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); }else{ - header('404 Not found'); + echo "WTF"; } } @@ -401,12 +401,11 @@ class OC{ self::$REQUESTEDAPP = (isset($_GET['app'])?strip_tags($_GET['app']):'files'); self::$REQUESTEDFILE = $_GET['getfile']; if(substr_count(self::$REQUESTEDFILE, '?') != 0){ - $pos_questionmark = strpos(self::$REQUESTEDFILE, '?'); - $pos_equal = strpos(self::$REQUESTEDFILE, '='); - $pos_and = strpos(self::$REQUESTEDFILE, '?'); - $_GET[substr(self::$REQUESTEDFILE, $pos_questionmark + 1, $pos_equal - $pos_questionmark - 1)] = substr(self::$REQUESTEDFILE, $pos_equal + 1, $pos_and); - self::$REQUESTEDFILE = substr(self::$REQUESTEDFILE, 0, $pos_questionmark); - $_GET['getfile'] = OC::$REQUESTEDFILE; + $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?')); + $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1); + parse_str($param, $_GET); + self::$REQUESTEDFILE = $file; + $_GET['getfile'] = $file; } self::$REQUESTEDFILE = (isset($_GET['getfile'])?(OC_Helper::issubdirectory(OC::$APPSROOT . '/' . self::$REQUESTEDAPP . '/' . self::$REQUESTEDFILE, OC::$APPSROOT . '/' . self::$REQUESTEDAPP)?self::$REQUESTEDFILE:null):null); } diff --git a/lib/helper.php b/lib/helper.php index 2067190bca7..072a544a40a 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -45,7 +45,7 @@ class OC_Helper { $app = substr($app, 0, strlen($app) - 1); } $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; - $urlLinkTo .= ($file!='index.php')?'&getfile=' . $file:''; + $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):''; } else{ $urlLinkTo = OC::$WEBROOT . '/' . $app . $file; -- GitLab From d1110c62ef084d5d38b8770a26def88dd0976674 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:01:48 +0200 Subject: [PATCH 250/430] fix file path in apps/media/ajax/api.php --- apps/media/ajax/api.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/media/ajax/api.php b/apps/media/ajax/api.php index 72235bf5db8..9c7b3efce75 100644 --- a/apps/media/ajax/api.php +++ b/apps/media/ajax/api.php @@ -23,10 +23,9 @@ header('Content-type: text/html; charset=UTF-8') ; - OC_JSON::checkAppEnabled('media'); -require_once('../lib_collection.php'); -require_once('../lib_scanner.php'); +require_once(OC::$APPSROOT . '/apps/media/lib_collection.php'); +require_once(OC::$APPSROOT . '/apps/media/lib_scanner.php'); error_reporting(E_ALL); //no script error reporting because of getID3 @@ -127,5 +126,4 @@ if($arguments['action']){ exit; } } - -?> +?> \ No newline at end of file -- GitLab From 19109afa79551e6dccbfc86ca27939b9df0fb7de Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:11:21 +0200 Subject: [PATCH 251/430] fix bug in lib base --- lib/base.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/base.php b/lib/base.php index 97b363b1fa9..0802e040c0f 100644 --- a/lib/base.php +++ b/lib/base.php @@ -406,7 +406,9 @@ class OC{ if(substr_count(self::$REQUESTEDFILE, '?') != 0){ $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?')); $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1); - parse_str($param, $_GET); + echo $param; + parse_str($param, $get); + $_GET = array_merge($_GET, $get); self::$REQUESTEDFILE = $file; $_GET['getfile'] = $file; } -- GitLab From 10eea3f4643ff0275d964ed7233d7a0c15afdf0a Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:13:55 +0200 Subject: [PATCH 252/430] fix pathes of shared calendars --- apps/calendar/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/calendar/index.php b/apps/calendar/index.php index 66f51c97226..417d2b6c225 100644 --- a/apps/calendar/index.php +++ b/apps/calendar/index.php @@ -22,8 +22,8 @@ foreach($calendars as $calendar){ $eventSources[] = OC_Calendar_Calendar::getEventSourceInfo($calendar); } -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_rw', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); -$eventSources[] = array('url' => 'ajax/events.php?calendar_id=shared_r', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); +$eventSources[] = array('url' => '?app=calendar&getfile=ajax/events.php?calendar_id=shared_rw', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable'=>'true'); +$eventSources[] = array('url' => '?app=calendar&getfile=ajax/events.php?calendar_id=shared_r', 'backgroundColor' => '#1D2D44', 'borderColor' => '#888', 'textColor' => 'white', 'editable' => 'false'); OC_Hook::emit('OC_Calendar', 'getSources', array('sources' => &$eventSources)); $categories = OC_Calendar_App::getCategoryOptions(); -- GitLab From 95c220a246573e08428d8fd98252cef271bc7da3 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:31:03 +0200 Subject: [PATCH 253/430] remove debug code in lib base --- lib/base.php | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/base.php b/lib/base.php index 0802e040c0f..f8f9362a64a 100644 --- a/lib/base.php +++ b/lib/base.php @@ -406,7 +406,6 @@ class OC{ if(substr_count(self::$REQUESTEDFILE, '?') != 0){ $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?')); $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1); - echo $param; parse_str($param, $get); $_GET = array_merge($_GET, $get); self::$REQUESTEDFILE = $file; -- GitLab From 9092692b8eed596b53ea06f6bea626bb470c4c25 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:32:55 +0200 Subject: [PATCH 254/430] make calendar work with movable apps --- apps/calendar/templates/part.editevent.php | 6 +++--- apps/calendar/templates/part.newevent.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/calendar/templates/part.editevent.php b/apps/calendar/templates/part.editevent.php index 58314db1a6b..102366f8f08 100644 --- a/apps/calendar/templates/part.editevent.php +++ b/apps/calendar/templates/part.editevent.php @@ -5,9 +5,9 @@ inc("part.eventform"); ?>
    - " onclick="Calendar.UI.validateEventForm('ajax/event/edit.php');"> - " onclick="Calendar.UI.submitDeleteEventForm('ajax/event/delete.php');"> - " onclick="window.location='export.php?eventid=';"> + " onclick="Calendar.UI.validateEventForm('?app=calendar&getfile=ajax/event/edit.php');"> + " onclick="Calendar.UI.submitDeleteEventForm('?app=calendar&getfile=ajax/event/delete.php');"> + " onclick="window.location='?app=calendar&getfile=export.php?eventid=';">
    diff --git a/apps/calendar/templates/part.newevent.php b/apps/calendar/templates/part.newevent.php index 11416260344..f4bb867b180 100644 --- a/apps/calendar/templates/part.newevent.php +++ b/apps/calendar/templates/part.newevent.php @@ -3,7 +3,7 @@ inc("part.eventform"); ?>
    - " onclick="Calendar.UI.validateEventForm('ajax/event/new.php');"> + " onclick="Calendar.UI.validateEventForm('?app=calendar&getfile=ajax/event/new.php');"> -- GitLab From fd47fbe17645b34448f38ac2819ac23ddbb405da Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Mon, 23 Apr 2012 20:39:04 +0200 Subject: [PATCH 255/430] fix contacts app a bit --- apps/contacts/css/contacts.css | 22 +++++++++++----------- apps/contacts/templates/index.php | 4 ++-- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index b0c68c96e67..4c5242f607f 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -11,7 +11,7 @@ #actionbar { height: 30px; width: 60px; position: fixed; right: 0px; top: 4em; margin: 0 0 0 0; padding: 0 0 0 0; z-index: 1000; } #contacts_deletecard {position:absolute;top:15px;right:25px;} #contacts_downloadcard {position:absolute;top:15px;right:50px;} -#contacts_propertymenu_button { position:absolute;top:15px;right:150px; background:url('../../../core/img/actions/add.svg') no-repeat center; } +#contacts_propertymenu_button { position:absolute;top:15px;right:150px; background:url('core/img/actions/add.svg') no-repeat center; } #contacts_propertymenu { background-color: #fff; position:absolute;top:40px;right:150px; overflow:hidden; text-overflow:ellipsis; /*border: thin solid #1d2d44;*/ -moz-box-shadow:0 0 10px #000; -webkit-box-shadow:0 0 10px #000; box-shadow:0 0 10px #000; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; } #contacts_propertymenu li { display: block; font-weight: bold; height: 20px; width: 100px; } #contacts_propertymenu li a { padding: 3px; display: block } @@ -34,20 +34,20 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } #address.form dt { min-width: 5em; } #address.form dl { min-width: 10em; } -.loading { background: url('../../../core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } -.ui-autocomplete-loading { background: url('../../../core/img/loading.gif') right center no-repeat; } +.loading { background: url('core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } +.ui-autocomplete-loading { background: url('core/img/loading.gif') right center no-repeat; } .float { float: left; } .listactions { height: 1em; width:60px; float: left; clear: right; } .add,.edit,.delete,.mail, .globe, .upload, .cloud { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } .add:hover,.edit:hover,.delete:hover,.mail:hover, .globe:hover, .upload:hover, .cloud:hover { opacity: 1.0 } -.add { background:url('../../../core/img/actions/add.svg') no-repeat center; clear: both; } -.delete { background:url('../../../core/img/actions/delete.svg') no-repeat center; } -.edit { background:url('../../../core/img/actions/rename.svg') no-repeat center; } -.mail { background:url('../../../core/img/actions/mail.svg') no-repeat center; } -.upload { background:url('../../../core/img/actions/upload.svg') no-repeat center; } -.cloud { background:url('../../../core/img/places/picture.svg') no-repeat center; } +.add { background:url('core/img/actions/add.svg') no-repeat center; clear: both; } +.delete { background:url('core/img/actions/delete.svg') no-repeat center; } +.edit { background:url('core/img/actions/rename.svg') no-repeat center; } +.mail { background:url('core/img/actions/mail.svg') no-repeat center; } +.upload { background:url('core/img/actions/upload.svg') no-repeat center; } +.cloud { background:url('core/img/places/picture.svg') no-repeat center; } /*.globe { background:url('../img/globe.svg') no-repeat center; }*/ -.globe { background:url('../../../core/img/actions/public.svg') no-repeat center; } +.globe { background:url('core/img/actions/public.svg') no-repeat center; } .transparent{ opacity: 0.6; } #edit_name_dialog { padding:0; } #edit_name_dialog > input { width: 15em; } @@ -63,7 +63,7 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } .contactpart legend { width:auto; padding:.3em; border:1px solid #ddd; font-weight:bold; cursor:pointer; background:#f8f8f8; color:#555; text-shadow:#fff 0 1px 0; -moz-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; } #cropbox { margin: auto; } -#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; background: url(../../../core/img/loading.gif) no-repeat center center; display: block; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; background: url(core/img/loading.gif) no-repeat center center; display: block; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } #contacts_details_photo:hover { background: #fff; cursor: default; } #phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.5em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } #phototools li { display: inline; } diff --git a/apps/contacts/templates/index.php b/apps/contacts/templates/index.php index 256d10afc07..d7aabbe76a5 100644 --- a/apps/contacts/templates/index.php +++ b/apps/contacts/templates/index.php @@ -16,8 +16,8 @@
    - <?php echo $l->t('Add Contact'); ?> - <?php echo $l->t('Addressbooks'); ?> + <?php echo $l->t('Add Contact'); ?> + <?php echo $l->t('Addressbooks'); ?>
    -- GitLab From 4ea927a7987d7fdcefcacb341f1a60b094ccf8d2 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Mon, 23 Apr 2012 23:54:49 +0200 Subject: [PATCH 256/430] wrote a new versioning app over the weekend. Basic functionality to far but it works (TM) and has all the needed features (TM) for ownCloud 4. Userinterface integration and small improvements still missing. --- apps/files_versions/appinfo/app.php | 19 ++ apps/files_versions/appinfo/info.xml | 12 ++ apps/files_versions/appinfo/version | 1 + apps/files_versions/css/versions.css | 2 + apps/files_versions/history.php | 60 ++++++ apps/files_versions/js/versions.js | 2 + apps/files_versions/settings.php | 10 + apps/files_versions/templates/history.php | 18 ++ apps/files_versions/templates/settings.php | 7 + apps/files_versions/versions.php | 216 +++++++++++++++++++++ 10 files changed, 347 insertions(+) create mode 100644 apps/files_versions/appinfo/app.php create mode 100644 apps/files_versions/appinfo/info.xml create mode 100644 apps/files_versions/appinfo/version create mode 100644 apps/files_versions/css/versions.css create mode 100644 apps/files_versions/history.php create mode 100644 apps/files_versions/js/versions.js create mode 100644 apps/files_versions/settings.php create mode 100644 apps/files_versions/templates/history.php create mode 100644 apps/files_versions/templates/settings.php create mode 100644 apps/files_versions/versions.php diff --git a/apps/files_versions/appinfo/app.php b/apps/files_versions/appinfo/app.php new file mode 100644 index 00000000000..6e7a803252e --- /dev/null +++ b/apps/files_versions/appinfo/app.php @@ -0,0 +1,19 @@ + 10, + 'id' => 'files_versions', + 'name' => 'Versioning' )); + +OC_APP::registerAdmin('files_versions', 'settings'); + +// Listen to write signals +OC_Hook::connect(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, "OCA_Versions\Storage", "write_hook"); + + + + +?> diff --git a/apps/files_versions/appinfo/info.xml b/apps/files_versions/appinfo/info.xml new file mode 100644 index 00000000000..9936a2ad8b2 --- /dev/null +++ b/apps/files_versions/appinfo/info.xml @@ -0,0 +1,12 @@ + + + files_versions + Versions + AGPL + Frank Karlitschek + 3 + Versioning of files + + + + diff --git a/apps/files_versions/appinfo/version b/apps/files_versions/appinfo/version new file mode 100644 index 00000000000..afaf360d37f --- /dev/null +++ b/apps/files_versions/appinfo/version @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file diff --git a/apps/files_versions/css/versions.css b/apps/files_versions/css/versions.css new file mode 100644 index 00000000000..139597f9cb0 --- /dev/null +++ b/apps/files_versions/css/versions.css @@ -0,0 +1,2 @@ + + diff --git a/apps/files_versions/history.php b/apps/files_versions/history.php new file mode 100644 index 00000000000..6c7626ca4ed --- /dev/null +++ b/apps/files_versions/history.php @@ -0,0 +1,60 @@ +. + * + */ +require_once('../../lib/base.php'); + +OC_Util::checkLoggedIn(); + +if (isset($_GET['path'])) { + + $path = $_GET['path']; + $path = strip_tags($path); + + // roll back to old version if button clicked + if(isset($_GET['revert'])) { + \OCA_Versions\Storage::rollback($path,$_GET['revert']); + } + + // show the history only if there is something to show + if(OCA_Versions\Storage::isversioned($path)) { + + $count=5; //show the newest revisions + $versions=OCA_Versions\Storage::getversions($path,$count); + + $tmpl = new OC_Template('files_versions', 'history', 'user'); + $tmpl->assign('path', $path); + $tmpl->assign('versions', array_reverse($versions)); + $tmpl->printPage(); + }else{ + $tmpl = new OC_Template('files_versions', 'history', 'user'); + $tmpl->assign('path', $path); + $tmpl->assign('message', 'No old versions available'); + $tmpl->printPage(); + } +}else{ + $tmpl = new OC_Template('files_versions', 'history', 'user'); + $tmpl->assign('message', 'No path specified'); + $tmpl->printPage(); +} + + +?> diff --git a/apps/files_versions/js/versions.js b/apps/files_versions/js/versions.js new file mode 100644 index 00000000000..139597f9cb0 --- /dev/null +++ b/apps/files_versions/js/versions.js @@ -0,0 +1,2 @@ + + diff --git a/apps/files_versions/settings.php b/apps/files_versions/settings.php new file mode 100644 index 00000000000..eb154d3edd3 --- /dev/null +++ b/apps/files_versions/settings.php @@ -0,0 +1,10 @@ +fetchPage(); +?> diff --git a/apps/files_versions/templates/history.php b/apps/files_versions/templates/history.php new file mode 100644 index 00000000000..1b3de9ce77c --- /dev/null +++ b/apps/files_versions/templates/history.php @@ -0,0 +1,18 @@ +File: '.$_['path']).'
    '; + echo(''.$_['message']).'
    '; + + }else{ + + echo('Versions of '.$_['path']).'
    '; + echo('

    You can click on the revert button to revert to the specific verson.


    '); + foreach ($_['versions'] as $v){ + echo(' '.OC_Util::formatDate($v).'
    revert

    '); + } + + } + +?> diff --git a/apps/files_versions/templates/settings.php b/apps/files_versions/templates/settings.php new file mode 100644 index 00000000000..8c8def94429 --- /dev/null +++ b/apps/files_versions/templates/settings.php @@ -0,0 +1,7 @@ +
    +
    + Versions
    + + Configuration goes here... +
    +
    diff --git a/apps/files_versions/versions.php b/apps/files_versions/versions.php new file mode 100644 index 00000000000..156a4f59c73 --- /dev/null +++ b/apps/files_versions/versions.php @@ -0,0 +1,216 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Versions + * + * A class to handle the versioning of files. + */ + +namespace OCA_Versions; + +class Storage { + + + // config.php configuration: + // - files_versions + // - files_versionsfolder + // - files_versionsblacklist + // - files_versionsmaxfilesize + // - files_versionsinterval + // - files_versionmaxversions + // + // todo: + // - port to oc_filesystem to enable network transparency + // - check if it works well together with encryption + // - do configuration web interface + // - implement expire all function. And find a place to call it ;-) + // - add transparent compression. first test if it´s worth it. + + const DEFAULTENABLED=true; + const DEFAULTFOLDER='versions'; + const DEFAULTBLACKLIST='avi mp3 mpg mp4'; + const DEFAULTMAXFILESIZE=1048576; // 10MB + const DEFAULTMININTERVAL=300; // 5 min + const DEFAULTMAXVERSIONS=50; + + /** + * init the versioning and create the versions folder. + */ + public static function init() { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + // create versions folder + $foldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + if(!is_dir($foldername)){ + mkdir($foldername); + } + } + } + + + /** + * listen to write event. + */ + public static function write_hook($params) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + $path = $params[\OC_Filesystem::signal_param_path]; + if($path<>'') Storage::store($path); + } + } + + + + /** + * store a new version of a file. + */ + public static function store($filename) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + $versionsfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + $filesfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/files'; + Storage::init(); + + // check if filename is a directory + if(is_dir($filesfoldername.$filename)){ + return false; + } + + // check filetype blacklist + $blacklist=explode(' ',\OC_Config::getValue('files_versionsblacklist', Storage::DEFAULTBLACKLIST)); + foreach($blacklist as $bl) { + $parts=explode('.', $filename); + $ext=end($parts); + if(strtolower($ext)==$bl) { + return false; + } + } + + // check filesize + if(filesize($filesfoldername.$filename)>\OC_Config::getValue('files_versionsmaxfilesize', Storage::DEFAULTMAXFILESIZE)){ + return false; + } + + + // check mininterval + $matches=glob($versionsfoldername.$filename.'.v*'); + sort($matches); + $parts=explode('.v',end($matches)); + if((end($parts)+Storage::DEFAULTMININTERVAL)>time()){ + return false; + } + + + // create all parent folders + $info=pathinfo($filename); + @mkdir($versionsfoldername.$info['dirname'],0700,true); + + + // store a new version of a file + copy($filesfoldername.$filename,$versionsfoldername.$filename.'.v'.time()); + + // expire old revisions + Storage::expire($filename); + } + } + + + /** + * rollback to an old version of a file. + */ + public static function rollback($filename,$revision) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + $versionsfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + $filesfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/files'; + // rollback + @copy($versionsfoldername.$filename.'.v'.$revision,$filesfoldername.$filename); + } + } + + /** + * check if old versions of a file exist. + */ + public static function isversioned($filename) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + $versionsfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + + // check for old versions + $matches=glob($versionsfoldername.$filename.'.v*'); + if(count($matches)>1){ + return true; + }else{ + return false; + } + }else{ + return(false); + } + } + + + + /** + * get a list of old versions of a file. + */ + public static function getversions($filename,$count=0) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + $versionsfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + $versions=array(); + + // fetch for old versions + $matches=glob($versionsfoldername.$filename.'.v*'); + sort($matches); + foreach($matches as $ma) { + $parts=explode('.v',$ma); + $versions[]=(end($parts)); + } + + // only show the newest commits + if($count<>0 and (count($versions)>$count)) { + $versions=array_slice($versions,count($versions)-$count); + } + + return($versions); + + + }else{ + return(array()); + } + } + + + + /** + * expire old versions of a file. + */ + public static function expire($filename) { + if(\OC_Config::getValue('files_versions', Storage::DEFAULTENABLED)=='true') { + + $versionsfoldername=\OC_Config::getValue('datadirectory').'/'. \OC_User::getUser() .'/'.\OC_Config::getValue('files_versionsfolder', Storage::DEFAULTFOLDER); + + // check for old versions + $matches=glob($versionsfoldername.$filename.'.v*'); + if(count($matches)>\OC_Config::getValue('files_versionmaxversions', Storage::DEFAULTMAXVERSIONS)){ + $numbertodelete=count($matches-\OC_Config::getValue('files_versionmaxversions', Storage::DEFAULTMAXVERSIONS)); + + // delete old versions of a file + $deleteitems=array_slice($matches,0,$numbertodelete); + foreach($deleteitems as $de){ + unlink($versionsfoldername.$filename.'.v'.$de); + } + } + } + } + + /** + * expire all old versions. + */ + public static function expireall($filename) { + // todo this should go through all the versions directories and delete all the not needed files and not needed directories. + // useful to be included in a cleanup cronjob. + } + + +} -- GitLab From 0cd9570277152d85a257b01e70d86e39ba8aa51c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 23 Apr 2012 21:08:38 +0200 Subject: [PATCH 257/430] Applied patches by Nicolas progweb at free.fr - https://mail.kde.org/pipermail/owncloud/2012-April/002900.html --- apps/contacts/lib/app.php | 1 + apps/contacts/lib/vcard.php | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/contacts/lib/app.php b/apps/contacts/lib/app.php index 475d2c8dc2e..2c2cc331ed7 100644 --- a/apps/contacts/lib/app.php +++ b/apps/contacts/lib/app.php @@ -149,6 +149,7 @@ class OC_Contacts_App { 'WORK' => $l->t('Work'), 'TEXT' => $l->t('Text'), 'VOICE' => $l->t('Voice'), + 'MSG' => $l->t('Message'), 'FAX' => $l->t('Fax'), 'VIDEO' => $l->t('Video'), 'PAGER' => $l->t('Pager'), diff --git a/apps/contacts/lib/vcard.php b/apps/contacts/lib/vcard.php index 90b037f76ee..53c952656b6 100644 --- a/apps/contacts/lib/vcard.php +++ b/apps/contacts/lib/vcard.php @@ -214,7 +214,8 @@ class OC_Contacts_VCard{ $prodid = trim($vcard->getAsString('PRODID')); if(!$prodid) { $appinfo = OC_App::getAppInfo('contacts'); - $prodid = '-//ownCloud//NONSGML '.$appinfo['name'].' '.$appinfo['version'].'//EN'; + $appversion = OC_App::getAppVersion('contacts'); + $prodid = '-//ownCloud//NONSGML '.$appinfo['name'].' '.$appversion.'//EN'; $vcard->setString('PRODID', $prodid); } $now = new DateTime; -- GitLab From dfc94cbe84f03d73b59a1e97a745f7f3837c609b Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 23 Apr 2012 21:14:10 +0200 Subject: [PATCH 258/430] Contacts: In app import. Cleanup still needed. --- apps/contacts/ajax/importaddressbook.php | 24 ++++ apps/contacts/ajax/uploadimport.php | 57 +++++++++ apps/contacts/css/contacts.css | 3 +- apps/contacts/import.php | 12 +- apps/contacts/js/contacts.js | 115 ++++++++++++++++-- .../templates/part.chooseaddressbook.php | 3 +- .../part.chooseaddressbook.rowfields.php | 2 +- 7 files changed, 201 insertions(+), 15 deletions(-) create mode 100644 apps/contacts/ajax/importaddressbook.php create mode 100644 apps/contacts/ajax/uploadimport.php diff --git a/apps/contacts/ajax/importaddressbook.php b/apps/contacts/ajax/importaddressbook.php new file mode 100644 index 00000000000..5776c801a76 --- /dev/null +++ b/apps/contacts/ajax/importaddressbook.php @@ -0,0 +1,24 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +require_once('../../../lib/base.php'); +OC_JSON::checkLoggedIn(); +OC_Util::checkAppEnabled('contacts'); +$upload_max_filesize = OC_Helper::computerFileSize(ini_get('upload_max_filesize')); +$post_max_size = OC_Helper::computerFileSize(ini_get('post_max_size')); +$maxUploadFilesize = min($upload_max_filesize, $post_max_size); + +$freeSpace=OC_Filesystem::free_space('/'); +$freeSpace=max($freeSpace,0); +$maxUploadFilesize = min($maxUploadFilesize ,$freeSpace); + +$tmpl = new OC_Template('contacts', 'part.importaddressbook'); +$tmpl->assign('uploadMaxFilesize', $maxUploadFilesize); +$tmpl->assign('uploadMaxHumanFilesize', OC_Helper::humanFileSize($maxUploadFilesize)); +$tmpl->printpage(); +?> diff --git a/apps/contacts/ajax/uploadimport.php b/apps/contacts/ajax/uploadimport.php new file mode 100644 index 00000000000..08bc436bc58 --- /dev/null +++ b/apps/contacts/ajax/uploadimport.php @@ -0,0 +1,57 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see . + * + */ +// Init owncloud +require_once('../../../lib/base.php'); + +// Check if we are a user +OC_JSON::checkLoggedIn(); +OC_JSON::checkAppEnabled('contacts'); +function bailOut($msg) { + OC_JSON::error(array('data' => array('message' => $msg))); + OC_Log::write('contacts','ajax/uploadimport.php: '.$msg, OC_Log::ERROR); + exit(); +} +function debug($msg) { + OC_Log::write('contacts','ajax/uploadimport.php: '.$msg, OC_Log::DEBUG); +} + +// If it is a Drag'n'Drop transfer it's handled here. +$fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false); +if($fn) { + /*$dir = OC_App::getStorage('contacts'); + $handle = $dir->touch(''.$fn); + if(!$handle) { + bailOut('Bugger!'); + } else { + bailOut('Yippie!'); + } + debug('Internal path: '.$dir->getInternalPath());*/ + $tmpfile = md5(rand()); + if(OC_Filesystem::file_put_contents('/'.$tmpfile, file_get_contents('php://input'))) { + debug($fn.' uploaded'); + OC_JSON::success(array('data' => array('path'=>'', 'file'=>$tmpfile))); + } else { + bailOut(OC_Contacts_App::$l10n->t('Error uploading contacts to storage.')); + } +} + +?> diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index b0c68c96e67..04700aa456a 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -33,7 +33,8 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } .form dd { display: table-cell; clear: right; float: left; margin: 0; padding: 0px; white-space: nowrap; vertical-align: text-bottom; } #address.form dt { min-width: 5em; } #address.form dl { min-width: 10em; } - +.droptarget { margin: 0.5em; padding: 0.5em; border: thin solid #ccc; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; } +.droppable { margin: 0.5em; padding: 0.5em; border: thin dashed #333; -moz-border-radius:.3em; -webkit-border-radius:.3em; border-radius:.3em; } .loading { background: url('../../../core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } .ui-autocomplete-loading { background: url('../../../core/img/loading.gif') right center no-repeat; } .float { float: left; } diff --git a/apps/contacts/import.php b/apps/contacts/import.php index 233ed5be22f..c98e46995ff 100644 --- a/apps/contacts/import.php +++ b/apps/contacts/import.php @@ -99,12 +99,16 @@ if(is_writable('import_tmp/')){ if(count($parts) == 1){ $importready = array($file); } +$imported = 0; +$failed = 0; foreach($importready as $import){ $card = OC_VObject::parse($import); if (!$card) { + $failed += 1; OC_Log::write('contacts','Import: skipping card. Error parsing VCard: '.$import, OC_Log::ERROR); continue; // Ditch cards that can't be parsed by Sabre. } + $imported += 1; OC_Contacts_VCard::add($id, $card); } //done the import @@ -117,4 +121,10 @@ sleep(3); if(is_writable('import_tmp/')){ unlink($progressfile); } -OC_JSON::success(); +if(isset($_POST['istmpfile'])) { + OC_Log::write('contacts','Import: Unlinking '.$_POST['path'] . '/' . $_POST['file'], OC_Log::ERROR); + if(!OC_Filesystem::unlink($_POST['path'] . '/' . $_POST['file'])) { + OC_Log::write('contacts','Import: Error unlinking '.$_POST['path'] . '/' . $_POST['file'], OC_Log::ERROR); + } +} +OC_JSON::success(array('data' => array('imported'=>$imported, 'failed'=>$failed))); diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index f03ae1e46d6..f471a7f25aa 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1263,7 +1263,8 @@ Contacts={ for(ptype in this.data.TEL[phone]['parameters'][param]) { var pt = this.data.TEL[phone]['parameters'][param][ptype]; $('#phonelist li:last-child').find('select option').each(function(){ - if ($(this).val().toUpperCase() == pt.toUpperCase()) { + //if ($(this).val().toUpperCase() == pt.toUpperCase()) { + if ($.inArray($(this).val().toUpperCase(), pt.toUpperCase().split(',')) > -1) { $(this).attr('selected', 'selected'); } }); @@ -1285,6 +1286,7 @@ Contacts={ }, }, Addressbooks:{ + droptarget:undefined, overview:function(){ if($('#chooseaddressbook_dialog').dialog('isOpen') == true){ $('#chooseaddressbook_dialog').dialog('moveToTop'); @@ -1317,14 +1319,13 @@ Contacts={ var tr = $(document.createElement('tr')) .load(OC.filePath('contacts', 'ajax', 'addbook.php')); $(object).closest('tr').after(tr).hide(); - /* TODO: Shouldn't there be some kinda error checking here? */ }, editAddressbook:function(object, bookid){ var tr = $(document.createElement('tr')) .load(OC.filePath('contacts', 'ajax', 'editaddressbook.php') + "?bookid="+bookid); $(object).closest('tr').after(tr).hide(); }, - deleteAddressbook:function(bookid){ + deleteAddressbook:function(obj, bookid){ var check = confirm("Do you really want to delete this address book?"); if(check == false){ return false; @@ -1332,9 +1333,10 @@ Contacts={ $.post(OC.filePath('contacts', 'ajax', 'deletebook.php'), { id: bookid}, function(jsondata) { if (jsondata.status == 'success'){ - $('#chooseaddressbook_dialog').dialog('destroy').remove(); + $(obj).closest('tr').remove(); + //$('#chooseaddressbook_dialog').dialog('destroy').remove(); Contacts.UI.Contacts.update(); - Contacts.UI.Addressbooks.overview(); + //Contacts.UI.Addressbooks.overview(); } else { OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); //alert('Error: ' + data.message); @@ -1342,8 +1344,99 @@ Contacts={ }); } }, - doImport:function(){ - Contacts.UI.notImplemented(); + loadImportHandlers:function() { + this.droptarget = $('#import_drop_target'); + console.log($('#import_drop_target').html()); + $(this.droptarget).bind('dragover',function(event){ + //console.log('dragover'); + $(event.target).addClass('droppable'); + event.stopPropagation(); + event.preventDefault(); + }); + $(this.droptarget).bind('dragleave',function(event){ + //console.log('dragleave'); + $(event.target).removeClass('droppable'); + //event.stopPropagation(); + //event.preventDefault(); + }); + $(this.droptarget).bind('drop',function(event){ + event.stopPropagation(); + event.preventDefault(); + console.log('drop'); + $(event.target).removeClass('droppable'); + $(event.target).html(t('contacts', 'Uploading...')); + Contacts.UI.loading(event.target, true); + $.fileUpload(event.originalEvent.dataTransfer.files); + }); + + $.fileUpload = function(files){ + console.log(files + ', ' + files.length); + var file = files[0]; + console.log('size: '+file.size+', type: '+file.type); + if(file.size > $('#max_upload').val()){ + OC.dialogs.alert(t('contacts','The file you are trying to upload exceed the maximum size for file uploads on this server.'), t('contacts','Upload too large')); + $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Drop a VCF file to import contacts.')); + Contacts.UI.loading(Contacts.UI.Addressbooks.droptarget, false); + return; + } + if(file.type.indexOf('text') != 0) { + OC.dialogs.alert(t('contacts','You have dropped a file type that cannot be imported: ') + file.type, t('contacts','Wrong file type')); + $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Drop a VCF file to import contacts.')); + Contacts.UI.loading(Contacts.UI.Addressbooks.droptarget, false); + return; + } + var xhr = new XMLHttpRequest(); + + if (!xhr.upload) { + OC.dialogs.alert(t('contacts', 'Your browser doesn\'t support AJAX upload. Please upload the contacts file to ownCloud and import that way.'), t('contacts', 'Error')) + } + fileUpload = xhr.upload, + xhr.onreadystatechange = function() { + if (xhr.readyState == 4){ + response = $.parseJSON(xhr.responseText); + if(response.status == 'success') { + if(xhr.status == 200) { + $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Importing...')); + Contacts.UI.Addressbooks.doImport(response.data.path, response.data.file); + } else { + $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Drop a VCF file to import contacts.')); + Contacts.UI.loading(Contacts.UI.Addressbooks.droptarget, false); + OC.dialogs.alert(xhr.status + ': ' + xhr.responseText, t('contacts', 'Error')); + } + } else { + OC.dialogs.alert(response.data.message, t('contacts', 'Error')); + } + } + }; + xhr.open("POST", 'ajax/uploadimport.php?file='+encodeURIComponent(file.name), true); + xhr.setRequestHeader('Cache-Control', 'no-cache'); + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + xhr.setRequestHeader('X_FILE_NAME', encodeURIComponent(file.name)); + xhr.setRequestHeader('X-File-Size', file.size); + xhr.setRequestHeader('Content-Type', file.type); + xhr.send(file); + } + }, + importAddressbook:function(object){ + var tr = $(document.createElement('tr')) + .load(OC.filePath('contacts', 'ajax', 'importaddressbook.php')); + $(object).closest('tr').after(tr).hide(); + //this.loadImportHandlers(); + }, + doImport:function(path, file){ + var id = $('#importaddressbook_dialog').find('#book').val(); + console.log('Selected book: ' + id); + $.post(OC.filePath('contacts', '', 'import.php'), { id: id, path: path, file: file, istmpfile: true }, + function(jsondata){ + if(jsondata.status == 'success'){ + Contacts.UI.Addressbooks.droptarget.html(t('contacts', 'Import done. Success/Failure: ')+jsondata.data.imported+'/'+jsondata.data.failed); + $('#chooseaddressbook_dialog').find('#close_button').val(t('contacts', 'OK')); + Contacts.UI.Contacts.update(); + } else { + OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); + } + }); + Contacts.UI.loading(Contacts.UI.Addressbooks.droptarget, false); }, submit:function(button, bookid){ var displayname = $("#displayname_"+bookid).val().trim(); @@ -1368,7 +1461,7 @@ Contacts={ } else { OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); } - }); + }); }, cancel:function(button, bookid){ $(button).closest('tr').prev().show().next().remove(); @@ -1507,13 +1600,13 @@ $(document).ready(function(){ }); $('#contacts_details_photo_wrapper').bind('dragover',function(event){ console.log('dragover'); - $(event.target).css('background-color','red'); + $(event.target).addClass('droppable'); event.stopPropagation(); event.preventDefault(); }); $('#contacts_details_photo_wrapper').bind('dragleave',function(event){ console.log('dragleave'); - $(event.target).css('background-color','white'); + $(event.target).removeClass('droppable'); //event.stopPropagation(); //event.preventDefault(); }); @@ -1521,7 +1614,7 @@ $(document).ready(function(){ event.stopPropagation(); event.preventDefault(); console.log('drop'); - $(event.target).css('background-color','white') + $(event.target).removeClass('droppable'); $.fileUpload(event.originalEvent.dataTransfer.files); }); diff --git a/apps/contacts/templates/part.chooseaddressbook.php b/apps/contacts/templates/part.chooseaddressbook.php index 90894220ef8..adfc8c15161 100644 --- a/apps/contacts/templates/part.chooseaddressbook.php +++ b/apps/contacts/templates/part.chooseaddressbook.php @@ -1,4 +1,4 @@ -
    "> +
    "> diff --git a/apps/contacts/templates/part.chooseaddressbook.rowfields.php b/apps/contacts/templates/part.chooseaddressbook.rowfields.php index 8518c1acd13..20b67a4161e 100644 --- a/apps/contacts/templates/part.chooseaddressbook.rowfields.php +++ b/apps/contacts/templates/part.chooseaddressbook.rowfields.php @@ -2,4 +2,4 @@ // FIXME: Make this readable. echo ""; echo ""; - echo ""; + echo ""; -- GitLab From 6848b069c9f33a164c8a5ab180a9a7f40802527b Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 24 Apr 2012 00:26:33 +0200 Subject: [PATCH 259/430] OC_App::getStorage() failed if app dir didn't exist. --- lib/app.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/app.php b/lib/app.php index 9f7d23872f3..29653775253 100755 --- a/lib/app.php +++ b/lib/app.php @@ -519,6 +519,10 @@ class OC_App{ public static function getStorage($appid){ if(OC_App::isEnabled($appid)){//sanity check if(OC_User::isLoggedIn()){ + $view = new OC_FilesystemView('/'.OC_User::getUser()); + if(!$view->file_exists($appid)) { + $view->mkdir($appid); + } return new OC_FilesystemView('/'.OC_User::getUser().'/'.$appid); }else{ OC_Log::write('core','Can\'t get app storage, app, user not logged in',OC_Log::ERROR); -- GitLab From b8da5c526219fae28434ede6cd53e0010d83c8ee Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 24 Apr 2012 00:43:08 +0200 Subject: [PATCH 260/430] Contacts: Tried to format NOTE field a bit. Needs to be improved more though. --- apps/contacts/css/contacts.css | 1 + apps/contacts/templates/part.contact.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index 04700aa456a..7338eed4a7f 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -60,6 +60,7 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } #identityprops { /*position: absolute; top: 2.5em; left: 0px;*/ } /*#contact_photo { max-width: 250px; }*/ #contact_identity { min-width: 30em; } +#note { min-width: 200px; } .contactsection { position: relative; float: left; /*max-width: 40em;*/ padding: 0.5em; height: auto: border: thin solid lightgray;/* -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; background-color: #f8f8f8;*/ } .contactpart legend { width:auto; padding:.3em; border:1px solid #ddd; font-weight:bold; cursor:pointer; background:#f8f8f8; color:#555; text-shadow:#fff 0 1px 0; -moz-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; } diff --git a/apps/contacts/templates/part.contact.php b/apps/contacts/templates/part.contact.php index b90fa92c2c5..dec081a9b89 100644 --- a/apps/contacts/templates/part.contact.php +++ b/apps/contacts/templates/part.contact.php @@ -112,7 +112,7 @@ $id = isset($_['id']) ? $_['id'] : '';
    - +
    -- GitLab From 22f4acadc05c16c19c312517ba494752fe385ccc Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 24 Apr 2012 01:43:21 +0200 Subject: [PATCH 261/430] Contacts: In app import (for Chrome and Firefox only) --- apps/contacts/ajax/uploadimport.php | 11 ++--------- apps/contacts/import.php | 17 +++++++++++------ apps/contacts/js/contacts.js | 8 +------- 3 files changed, 14 insertions(+), 22 deletions(-) diff --git a/apps/contacts/ajax/uploadimport.php b/apps/contacts/ajax/uploadimport.php index 08bc436bc58..ab680c8823f 100644 --- a/apps/contacts/ajax/uploadimport.php +++ b/apps/contacts/ajax/uploadimport.php @@ -37,16 +37,9 @@ function debug($msg) { // If it is a Drag'n'Drop transfer it's handled here. $fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false); if($fn) { - /*$dir = OC_App::getStorage('contacts'); - $handle = $dir->touch(''.$fn); - if(!$handle) { - bailOut('Bugger!'); - } else { - bailOut('Yippie!'); - } - debug('Internal path: '.$dir->getInternalPath());*/ + $view = OC_App::getStorage('contacts'); $tmpfile = md5(rand()); - if(OC_Filesystem::file_put_contents('/'.$tmpfile, file_get_contents('php://input'))) { + if($view->file_put_contents('/'.$tmpfile, file_get_contents('php://input'))) { debug($fn.' uploaded'); OC_JSON::success(array('data' => array('path'=>'', 'file'=>$tmpfile))); } else { diff --git a/apps/contacts/import.php b/apps/contacts/import.php index c98e46995ff..93af7e62814 100644 --- a/apps/contacts/import.php +++ b/apps/contacts/import.php @@ -17,8 +17,14 @@ if(is_writable('import_tmp/')){ fwrite($progressfopen, '10'); fclose($progressfopen); } -$file = OC_Filesystem::file_get_contents($_POST['path'] . '/' . $_POST['file']); -if($_POST['method'] == 'new'){ +$view = $file = null; +if(isset($_POST['fstype']) && $_POST['fstype'] == 'OC_FilesystemView') { + $view = OC_App::getStorage('contacts'); + $file = $view->file_get_contents('/' . $_POST['file']); +} else { + $file = OC_Filesystem::file_get_contents($_POST['path'] . '/' . $_POST['file']); +} +if(isset($_POST['method']) && $_POST['method'] == 'new'){ $id = OC_Contacts_Addressbook::add(OC_User::getUser(), $_POST['addressbookname']); OC_Contacts_Addressbook::setActive($id, 1); }else{ @@ -121,10 +127,9 @@ sleep(3); if(is_writable('import_tmp/')){ unlink($progressfile); } -if(isset($_POST['istmpfile'])) { - OC_Log::write('contacts','Import: Unlinking '.$_POST['path'] . '/' . $_POST['file'], OC_Log::ERROR); - if(!OC_Filesystem::unlink($_POST['path'] . '/' . $_POST['file'])) { - OC_Log::write('contacts','Import: Error unlinking '.$_POST['path'] . '/' . $_POST['file'], OC_Log::ERROR); +if(isset($_POST['fstype']) && $_POST['fstype'] == 'OC_FilesystemView') { + if(!$view->unlink('/' . $_POST['file'])) { + OC_Log::write('contacts','Import: Error unlinking OC_FilesystemView ' . '/' . $_POST['file'], OC_Log::ERROR); } } OC_JSON::success(array('data' => array('imported'=>$imported, 'failed'=>$failed))); diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index f471a7f25aa..a3e1a1361df 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1348,16 +1348,12 @@ Contacts={ this.droptarget = $('#import_drop_target'); console.log($('#import_drop_target').html()); $(this.droptarget).bind('dragover',function(event){ - //console.log('dragover'); $(event.target).addClass('droppable'); event.stopPropagation(); event.preventDefault(); }); $(this.droptarget).bind('dragleave',function(event){ - //console.log('dragleave'); $(event.target).removeClass('droppable'); - //event.stopPropagation(); - //event.preventDefault(); }); $(this.droptarget).bind('drop',function(event){ event.stopPropagation(); @@ -1421,12 +1417,11 @@ Contacts={ var tr = $(document.createElement('tr')) .load(OC.filePath('contacts', 'ajax', 'importaddressbook.php')); $(object).closest('tr').after(tr).hide(); - //this.loadImportHandlers(); }, doImport:function(path, file){ var id = $('#importaddressbook_dialog').find('#book').val(); console.log('Selected book: ' + id); - $.post(OC.filePath('contacts', '', 'import.php'), { id: id, path: path, file: file, istmpfile: true }, + $.post(OC.filePath('contacts', '', 'import.php'), { id: id, path: path, file: file, fstype: 'OC_FilesystemView' }, function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.Addressbooks.droptarget.html(t('contacts', 'Import done. Success/Failure: ')+jsondata.data.imported+'/'+jsondata.data.failed); @@ -1478,7 +1473,6 @@ Contacts={ } else{ OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error')); - //alert(jsondata.data.message); } }); setTimeout(Contacts.UI.Contacts.lazyupdate, 500); -- GitLab From 988f98fc6f2942a09ffbd901bb24651acac75c8c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 24 Apr 2012 11:35:56 +0200 Subject: [PATCH 262/430] Contacts: Check that UIDs really are unique on import. Better solution would be to suggest to merge contacts, but that will have to wait to OC5 ;-) --- apps/contacts/lib/vcard.php | 38 ++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/apps/contacts/lib/vcard.php b/apps/contacts/lib/vcard.php index 53c952656b6..96fc8cf7121 100644 --- a/apps/contacts/lib/vcard.php +++ b/apps/contacts/lib/vcard.php @@ -141,10 +141,38 @@ class OC_Contacts_VCard{ } /** - * @brief Tries to update imported VCards to adhere to rfc2426 (VERSION: 3.0) + * @brief Checks if a contact with the same UID already exist in the address book. + * @param $aid Address book ID. + * @param $uid UID (passed by reference). + * @returns true if the UID has been changed. + */ + protected static function trueUID($aid, &$uid) { + $stmt = OC_DB::prepare( 'SELECT * FROM *PREFIX*contacts_cards WHERE addressbookid = ? AND uri = ?' ); + $uri = $uid.'.vcf'; + $result = $stmt->execute(array($aid,$uri)); + if($result->numRows() > 0){ + while(true) { + $tmpuid = substr(md5(rand().time()),0,10); + $uri = $tmpuid.'.vcf'; + $result = $stmt->execute(array($aid,$uri)); + if($result->numRows() > 0){ + continue; + } else { + $uid = $tmpuid; + return true; + } + } + } else { + return false; + } + } + + /** + * @brief Tries to update imported VCards to adhere to rfc2426 (VERSION: 3.0) and add mandatory fields if missing. + * @param aid Address book id. * @param vcard An OC_VObject of type VCARD (passed by reference). */ - protected static function updateValuesFromAdd(&$vcard) { // any suggestions for a better method name? ;-) + protected static function updateValuesFromAdd($aid, &$vcard) { // any suggestions for a better method name? ;-) $stringprops = array('N', 'FN', 'ORG', 'NICK', 'ADR', 'NOTE'); $typeprops = array('ADR', 'TEL', 'EMAIL'); $upgrade = false; @@ -207,8 +235,12 @@ class OC_Contacts_VCard{ } if(!$uid) { $vcard->setUID(); + $uid = $vcard->getAsString('UID'); OC_Log::write('contacts','OC_Contacts_VCard::updateValuesFromAdd. Added missing \'UID\' field: '.$uid,OC_Log::DEBUG); } + if(self::trueUID($aid, $uid)) { + $vcard->setString('UID', $uid); + } $vcard->setString('VERSION','3.0'); // Add product ID is missing. $prodid = trim($vcard->getAsString('PRODID')); @@ -237,7 +269,7 @@ class OC_Contacts_VCard{ OC_Contacts_App::loadCategoriesFromVCard($card); - self::updateValuesFromAdd($card); + self::updateValuesFromAdd($aid, $card); $fn = $card->getAsString('FN'); if (empty($fn)) { -- GitLab From b824425186abc3ea7218252c26d44f8aee73b95d Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Tue, 24 Apr 2012 11:38:11 +0200 Subject: [PATCH 263/430] Added loading indicator. --- apps/contacts/js/contacts.js | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index a3e1a1361df..e00e9257e65 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1393,6 +1393,7 @@ Contacts={ if(response.status == 'success') { if(xhr.status == 200) { $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Importing...')); + Contacts.UI.loading(Contacts.UI.Addressbooks.droptarget, true); Contacts.UI.Addressbooks.doImport(response.data.path, response.data.file); } else { $(Contacts.UI.Addressbooks.droptarget).html(t('contacts', 'Drop a VCF file to import contacts.')); -- GitLab From 69a2173fdbc31eda0110997e28fea2037e5e1558 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Tue, 24 Apr 2012 14:00:44 +0200 Subject: [PATCH 264/430] non working app. moved to the apps-playground repository --- apps/files_versioning/ajax/gethead.php | 12 - apps/files_versioning/ajax/sethead.php | 14 - apps/files_versioning/appinfo/app.php | 20 - apps/files_versioning/appinfo/info.xml | 12 - apps/files_versioning/appinfo/version | 1 - apps/files_versioning/css/settings.css | 3 - apps/files_versioning/js/settings.js | 25 - apps/files_versioning/lib_granite.php | 12 - apps/files_versioning/settings.php | 34 - apps/files_versioning/templates/settings.php | 12 - apps/files_versioning/versionstorage.php | 386 ----------- apps/files_versioning/versionwrapper.php | 686 ------------------- 12 files changed, 1217 deletions(-) delete mode 100644 apps/files_versioning/ajax/gethead.php delete mode 100644 apps/files_versioning/ajax/sethead.php delete mode 100644 apps/files_versioning/appinfo/app.php delete mode 100644 apps/files_versioning/appinfo/info.xml delete mode 100644 apps/files_versioning/appinfo/version delete mode 100644 apps/files_versioning/css/settings.css delete mode 100644 apps/files_versioning/js/settings.js delete mode 100644 apps/files_versioning/lib_granite.php delete mode 100644 apps/files_versioning/settings.php delete mode 100644 apps/files_versioning/templates/settings.php delete mode 100644 apps/files_versioning/versionstorage.php delete mode 100644 apps/files_versioning/versionwrapper.php diff --git a/apps/files_versioning/ajax/gethead.php b/apps/files_versioning/ajax/gethead.php deleted file mode 100644 index cc93b7a1d17..00000000000 --- a/apps/files_versioning/ajax/gethead.php +++ /dev/null @@ -1,12 +0,0 @@ - $head)); diff --git a/apps/files_versioning/ajax/sethead.php b/apps/files_versioning/ajax/sethead.php deleted file mode 100644 index d1b2df9b00f..00000000000 --- a/apps/files_versioning/ajax/sethead.php +++ /dev/null @@ -1,14 +0,0 @@ - 10, - 'id' => 'files_versioning', - 'name' => 'Versioning and Backup' )); - -// Include stylesheets for the settings page -OC_Util::addStyle( 'files_versioning', 'settings' ); -OC_Util::addScript('files_versioning','settings'); - -// Register a settings section in the Admin > Personal page -OC_APP::registerPersonal('files_versioning','settings'); diff --git a/apps/files_versioning/appinfo/info.xml b/apps/files_versioning/appinfo/info.xml deleted file mode 100644 index b9f56f674a0..00000000000 --- a/apps/files_versioning/appinfo/info.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - files_versioning - Versioning and Backup - GPLv2 - Craig Roberts - 3 - Versions files using Git repositories, providing a simple backup facility. Currently in *beta* and explicitly without warranty of any kind. - - - - diff --git a/apps/files_versioning/appinfo/version b/apps/files_versioning/appinfo/version deleted file mode 100644 index afaf360d37f..00000000000 --- a/apps/files_versioning/appinfo/version +++ /dev/null @@ -1 +0,0 @@ -1.0.0 \ No newline at end of file diff --git a/apps/files_versioning/css/settings.css b/apps/files_versioning/css/settings.css deleted file mode 100644 index afe2cd5508f..00000000000 --- a/apps/files_versioning/css/settings.css +++ /dev/null @@ -1,3 +0,0 @@ -#file_versioning_commit_chzn { - width: 15em; -} diff --git a/apps/files_versioning/js/settings.js b/apps/files_versioning/js/settings.js deleted file mode 100644 index 8dd13bac033..00000000000 --- a/apps/files_versioning/js/settings.js +++ /dev/null @@ -1,25 +0,0 @@ -$(document).ready(function(){ - $('#file_versioning_head').chosen(); - - $.getJSON(OC.filePath('files_versioning', 'ajax', 'gethead.php'), function(jsondata, status) { - - if (jsondata.head == 'HEAD') { - // Most recent commit, do nothing - } else { - $("#file_versioning_head").val(jsondata.head); - // Trigger the chosen update call - // See http://harvesthq.github.com/chosen/ - $("#file_versioning_head").trigger("liszt:updated"); - } - }); - - $('#file_versioning_head').change(function() { - - var data = $(this).serialize(); - $.post( OC.filePath('files_versioning', 'ajax', 'sethead.php'), data, function(data){ - if(data == 'error'){ - console.log('Saving new HEAD failed'); - } - }); - }); -}); diff --git a/apps/files_versioning/lib_granite.php b/apps/files_versioning/lib_granite.php deleted file mode 100644 index 571e5cea637..00000000000 --- a/apps/files_versioning/lib_granite.php +++ /dev/null @@ -1,12 +0,0 @@ -head(); -for ($i = 0; $i < 50; $i++) { - $commits[] = $commit; - $parents = $commit->parents(); - if (count($parents) > 0) { - $parent = $parents[0]; - } else { - break; - } - - $commit = $repository->factory('commit', $parent); -} - -$tmpl = new OC_Template( 'files_versioning', 'settings'); -$tmpl->assign('commits', $commits); -return $tmpl->fetchPage(); diff --git a/apps/files_versioning/templates/settings.php b/apps/files_versioning/templates/settings.php deleted file mode 100644 index 17f4cc7f77f..00000000000 --- a/apps/files_versioning/templates/settings.php +++ /dev/null @@ -1,12 +0,0 @@ -
    - Versioning and Backup
    -

    Please note: Backing up large files (around 16MB+) will cause your backup history to grow very large, very quickly.

    - - -
    diff --git a/apps/files_versioning/versionstorage.php b/apps/files_versioning/versionstorage.php deleted file mode 100644 index d083e623df9..00000000000 --- a/apps/files_versioning/versionstorage.php +++ /dev/null @@ -1,386 +0,0 @@ -. - */ - -// Include Granite -require_once('lib_granite.php'); - -// Create a top-level 'Backup' directory if it does not already exist -$user = OC_User::getUser(); -if (OC_Filesystem::$loaded and !OC_Filesystem::is_dir('/Backup')) { - OC_Filesystem::mkdir('/Backup'); - OC_Preferences::setValue(OC_User::getUser(), 'files_versioning', 'head', 'HEAD'); -} - -// Generate the repository path (currently using 'full' repositories, as opposed to bare ones) -$repo_path = DIRECTORY_SEPARATOR - . OC_User::getUser() - . DIRECTORY_SEPARATOR - . 'files' - . DIRECTORY_SEPARATOR - . 'Backup'; - -// Mount the 'Backup' folder using the versioned storage provider below -OC_Filesystem::mount('OC_Filestorage_Versioned', array('repo'=>$repo_path), $repo_path . DIRECTORY_SEPARATOR); - -class OC_Filestorage_Versioned extends OC_Filestorage { - - /** - * Holds an instance of Granite\Git\Repository - */ - protected $repo; - - /** - * Constructs a new OC_Filestorage_Versioned instance, expects an associative - * array with a `repo` key set to the path of the repository's `.git` folder - * - * @param array $parameters An array containing the key `repo` pointing to the - * repository path. - */ - public function __construct($parameters) { - // Get the full path to the repository folder - $path = OC_Config::getValue('datadirectory', OC::$SERVERROOT.'/data') - . $parameters['repo'] - . DIRECTORY_SEPARATOR - . '.git' - . DIRECTORY_SEPARATOR; - - try { - // Attempt to load the repository - $this->repo = new Granite\Git\Repository($path); - } catch (InvalidArgumentException $e) { - // $path is not a valid Git repository, we must create one - Granite\Git\Repository::init($path); - - // Load the newly-initialised repository - $this->repo = new Granite\Git\Repository($path); - - /** - * Create an initial commit with a README file - * FIXME: This functionality should be transferred to the Granite library - */ - $blob = new Granite\Git\Blob($this->repo->path()); - $blob->content('Your Backup directory is now ready for use.'); - - // Create a new tree to hold the README file - $tree = $this->repo->factory('tree'); - // Create a tree node to represent the README blob - $tree_node = new Granite\Git\Tree\Node('README', '100644', $blob->sha()); - $tree->nodes(array($tree_node->name() => $tree_node)); - - // Create an initial commit - $commit = new Granite\Git\Commit($this->repo->path()); - $user_string = OC_User::getUser() . ' ' . time() . ' +0000'; - $commit->author($user_string); - $commit->committer($user_string); - $commit->message('Initial commit'); - $commit->tree($tree); - - // Write it all to disk - $blob->write(); - $tree->write(); - $commit->write(); - - // Update the HEAD for the 'master' branch - $this->repo->head('master', $commit->sha()); - } - - // Update the class pointer to the HEAD - $head = OC_Preferences::getValue(OC_User::getUser(), 'files_versioning', 'head', 'HEAD'); - - // Load the most recent commit if the preference is not set - if ($head == 'HEAD') { - $this->head = $this->repo->head()->sha(); - } else { - $this->head = $head; - } - } - - public function mkdir($path) { - if (mkdir("versioned:/{$this->repo->path()}$path#{$this->head}")) { - $this->head = $this->repo->head()->sha(); - OC_Preferences::setValue(OC_User::getUser(), 'files_versioning', 'head', $head); - return true; - } - - return false; - } - - public function rmdir($path) { - - } - - /** - * Returns a directory handle to the requested path, or FALSE on failure - * - * @param string $path The directory path to open - * - * @return boolean|resource A directory handle, or FALSE on failure - */ - public function opendir($path) { - return opendir("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - /** - * Returns TRUE if $path is a directory, or FALSE if not - * - * @param string $path The path to check - * - * @return boolean - */ - public function is_dir($path) { - return $this->filetype($path) == 'dir'; - } - - /** - * Returns TRUE if $path is a file, or FALSE if not - * - * @param string $path The path to check - * - * @return boolean - */ - public function is_file($path) { - return $this->filetype($path) == 'file'; - } - - public function stat($path) - { - return stat("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - /** - * Returns the strings 'dir' or 'file', depending on the type of $path - * - * @param string $path The path to check - * - * @return string Returns 'dir' if a directory, 'file' otherwise - */ - public function filetype($path) { - if ($path == "" || $path == "/") { - return 'dir'; - } else { - if (substr($path, -1) == '/') { - $path = substr($path, 0, -1); - } - - $node = $this->tree_search($this->repo, $this->repo->factory('commit', $this->head)->tree(), $path); - - // Does it exist, or is it new? - if ($node == null) { - // New file - return 'file'; - } else { - // Is it a tree? - try { - $this->repo->factory('tree', $node); - return 'dir'; - } catch (InvalidArgumentException $e) { - // Nope, must be a blob - return 'file'; - } - } - } - } - - public function filesize($path) { - return filesize("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - /** - * Returns a boolean value representing whether $path is readable - * - * @param string $path The path to check - *( - * @return boolean Whether or not the path is readable - */ - public function is_readable($path) { - return true; - } - - /** - * Returns a boolean value representing whether $path is writable - * - * @param string $path The path to check - *( - * @return boolean Whether or not the path is writable - */ - public function is_writable($path) { - - $head = OC_Preferences::getValue(OC_User::getUser(), 'files_versioning', 'head', 'HEAD'); - if ($head !== 'HEAD' && $head !== $this->repo->head()->sha()) { - // Cannot modify previous commits - return false; - } - return true; - } - - /** - * Returns a boolean value representing whether $path exists - * - * @param string $path The path to check - *( - * @return boolean Whether or not the path exists - */ - public function file_exists($path) { - return file_exists("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - /** - * Returns an integer value representing the inode change time - * (NOT IMPLEMENTED) - * - * @param string $path The path to check - *( - * @return int Timestamp of the last inode change - */ - public function filectime($path) { - return -1; - } - - /** - * Returns an integer value representing the file modification time - * - * @param string $path The path to check - *( - * @return int Timestamp of the last file modification - */ - public function filemtime($path) { - return filemtime("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - public function file_get_contents($path) { - return file_get_contents("versioned:/{$this->repo->path()}$path#{$this->head}"); - } - - public function file_put_contents($path, $data) { - $success = file_put_contents("versioned:/{$this->repo->path()}$path#{$this->head}", $data); - if ($success !== false) { - // Update the HEAD in the preferences - OC_Preferences::setValue(OC_User::getUser(), 'files_versioning', 'head', $this->repo->head()->sha()); - return $success; - } - - return false; - } - - public function unlink($path) { - - } - - public function rename($path1, $path2) { - - } - - public function copy($path1, $path2) { - - } - - public function fopen($path, $mode) { - return fopen("versioned:/{$this->repo->path()}$path#{$this->head}", $mode); - } - - public function getMimeType($path) { - if ($this->filetype($path) == 'dir') { - return 'httpd/unix-directory'; - } elseif ($this->filesize($path) == 0) { - // File's empty, returning text/plain allows opening in the web editor - return 'text/plain'; - } else { - $finfo = new finfo(FILEINFO_MIME_TYPE); - /** - * We need to represent the repository path, the file path, and the - * revision, which can be simply achieved with a convention of using - * `.git` in the repository directory (bare or not) and the '#part' - * segment of a URL to specify the revision. For example - * - * versioned://var/www/myrepo.git/docs/README.md#HEAD ('bare' repo) - * versioned://var/www/myrepo/.git/docs/README.md#HEAD ('full' repo) - * versioned://var/www/myrepo/.git/docs/README.md#6a8f...8a54 ('full' repo and SHA-1 commit ID) - */ - $mime = $finfo->buffer(file_get_contents("versioned:/{$this->repo->path()}$path#{$this->head}")); - return $mime; - } - } - - /** - * Generates a hash based on the file contents - * - * @param string $type The hashing algorithm to use (e.g. 'md5', 'sha256', etc.) - * @param string $path The file to be hashed - * @param boolean $raw Outputs binary data if true, lowercase hex digits otherwise - * - * @return string Hashed string representing the file contents - */ - public function hash($type, $path, $raw) { - return hash($type, file_get_contents($path), $raw); - } - - public function free_space($path) { - } - - public function search($query) { - - } - - public function touch($path, $mtime=null) { - - } - - - public function getLocalFile($path) { - } - - /** - * Recursively searches a tree for a path, returning FALSE if is not found - * or an SHA-1 id if it is found. - * - * @param string $repo The repository containing the tree object - * @param string $tree The tree object to search - * @param string $path The path to search for (relative to the tree) - * @param int $depth The depth of the current search (for recursion) - * - * @return string|boolean The SHA-1 id of the sub-tree - */ - private function tree_search($repo, $tree, $path, $depth = 0) - { - $paths = array_values(explode(DIRECTORY_SEPARATOR, $path)); - - $current_path = $paths[$depth]; - - $nodes = $tree->nodes(); - foreach ($nodes as $node) { - if ($node->name() == $current_path) { - - if (count($paths)-1 == $depth) { - // Stop, found it - return $node->sha(); - } - - // Recurse if necessary - if ($node->isDirectory()) { - $tree = $this->repo->factory('tree', $node->sha()); - return $this->tree_search($repo, $tree, $path, $depth + 1); - } - } - } - - return false; - } - -} diff --git a/apps/files_versioning/versionwrapper.php b/apps/files_versioning/versionwrapper.php deleted file mode 100644 index b83a4fd3b22..00000000000 --- a/apps/files_versioning/versionwrapper.php +++ /dev/null @@ -1,686 +0,0 @@ -tree); - return true; - } - - /** - * Open directory handle - */ - public function dir_opendir($path, $options) { - // Parse the URL into a repository directory, file path and commit ID - list($this->repo, $repo_file, $this->commit) = $this->parse_url($path); - - if ($repo_file == '' || $repo_file == '/') { - // Set the tree property for the future `readdir()` etc. calls - $this->tree = array_values($this->commit->tree()->nodes()); - return true; - } elseif ($this->tree_search($this->repo, $this->commit->tree(), $repo_file) !== false) { - // Something exists at this path, is it a directory though? - try { - $tree = $this->repo->factory( - 'tree', - $this->tree_search($this->repo, $this->commit->tree(), $repo_file) - ); - $this->tree = array_values($tree->nodes()); - return true; - } catch (InvalidArgumentException $e) { - // Trying to call `opendir()` on a file, return false below - } - } - - // Unable to find the directory, return false - return false; - } - - /** - * Read entry from directory handle - */ - public function dir_readdir() { - return isset($this->tree[$this->dir_position]) - ? $this->tree[$this->dir_position++]->name() - : false; - } - - /** - * Rewind directory handle - */ - public function dir_rewinddir() { - $this->dir_position = 0; - } - - /** - * Create a directory - * Git doesn't track empty directories, so a ".empty" file is added instead - */ - public function mkdir($path, $mode, $options) { - // Parse the URL into a repository directory, file path and commit ID - list($this->repo, $repo_file, $this->commit) = $this->parse_url($path); - - // Create an empty file for Git - $empty = new Granite\Git\Blob($this->repo->path()); - $empty->content(''); - $empty->write(); - - if (dirname($repo_file) == '.') { - // Adding a new directory to the root tree - $tree = $this->repo->head()->tree(); - } else { - $tree = $this->repo->factory('tree', $this->tree_search( - $this->repo, $this->repo->head()->tree(), dirname($repo_file) - ) - ); - } - - // Create our new tree, with our empty file - $dir = $this->repo->factory('tree'); - $nodes = array(); - $nodes[self::EMPTYFILE] = new Granite\Git\Tree\Node(self::EMPTYFILE, '100644', $empty->sha()); - $dir->nodes($nodes); - $dir->write(); - - // Add our new tree to its parent - $nodes = $tree->nodes(); - $nodes[basename($repo_file)] = new Granite\Git\Tree\Node(basename($repo_file), '040000', $dir->sha()); - $tree->nodes($nodes); - $tree->write(); - - // We need to recursively update each parent tree, since they are all - // hashed and the changes will cascade back up the chain - - // So, we're currently at the bottom-most directory - $current_dir = dirname($repo_file); - $previous_tree = $tree; - - if ($current_dir !== '.') { - do { - // Determine the parent directory - $previous_dir = $current_dir; - $current_dir = dirname($current_dir); - - $current_tree = $current_dir !== '.' - ? $this->repo->factory( - 'tree', $this->tree_search( - $this->repo, - $this->repo->head()->tree(), - $current_dir - ) - ) - : $this->repo->head()->tree(); - - $current_nodes = $current_tree->nodes(); - $current_nodes[basename($previous_dir)] = new Granite\Git\Tree\Node( - basename($previous_dir), '040000', $previous_tree->sha() - ); - $current_tree->nodes($current_nodes); - $current_tree->write(); - - $previous_tree = $current_tree; - } while ($current_dir !== '.'); - - $tree = $previous_tree; - } - - // Create a new commit to represent this write - $commit = $this->repo->factory('commit'); - $username = OC_User::getUser(); - $user_string = $username . ' ' . time() . ' +0000'; - $commit->author($user_string); - $commit->committer($user_string); - $commit->message("$username created the `$repo_file` directory, " . date('d F Y H:i', time()) . '.'); - $commit->parents(array($this->repo->head()->sha())); - $commit->tree($tree); - - // Write it to disk - $commit->write(); - - // Update the HEAD for the 'master' branch - $this->repo->head('master', $commit->sha()); - - return true; - } - - /** - * Renames a file or directory - */ - public function rename($path_from, $path_to) { - - } - - /** - * Removes a directory - */ - public function rmdir($path, $options) { - - } - - /** - * Retrieve the underlaying resource (NOT IMPLEMENTED) - */ - public function stream_cast($cast_as) { - return false; - } - - /** - * Close a resource - */ - public function stream_close() { - unset($this->blob); - return true; - } - - /** - * Tests for end-of-file on a file pointer - */ - public function stream_eof() { - return !($this->file_position < strlen($this->blob)); - } - - /** - * Flushes the output (NOT IMPLEMENTED) - */ - public function stream_flush() { - return false; - } - - /** - * Advisory file locking (NOT IMPLEMENTED) - */ - public function stream_lock($operation) { - return false; - } - - /** - * Change stream options (NOT IMPLEMENTED) - * Called in response to `chgrp()`, `chown()`, `chmod()` and `touch()` - */ - public function stream_metadata($path, $option, $var) { - return false; - } - - /** - * Opens file or URL - */ - public function stream_open($path, $mode, $options, &$opened_path) { - // Store the path, so we can use it later in `stream_write()` if necessary - $this->path = $path; - // Parse the URL into a repository directory, file path and commit ID - list($this->repo, $repo_file, $this->commit) = $this->parse_url($path); - - $file = $this->tree_search($this->repo, $this->commit->tree(), $repo_file); - if ($file !== false) { - try { - $this->blob = $this->repo->factory('blob', $file)->content(); - return true; - } catch (InvalidArgumentException $e) { - // Trying to open a directory, return false below - } - } elseif ($mode !== 'r') { - // All other modes allow opening for reading and writing, clearly - // some 'write' files may not exist yet... - return true; - } - - // File could not be found or is not actually a file - return false; - } - - /** - * Read from stream - */ - public function stream_read($count) { - // Fetch the remaining set of bytes - $bytes = substr($this->blob, $this->file_position, $count); - - // If EOF or empty string, return false - if ($bytes == '' || $bytes == false) { - return false; - } - - // If $count does not extend past EOF, add $count to stream offset - if ($this->file_position + $count < strlen($this->blob)) { - $this->file_position += $count; - } else { - // Otherwise return all remaining bytes - $this->file_position = strlen($this->blob); - } - - return $bytes; - } - - /** - * Seeks to specific location in a stream - */ - public function stream_seek($offset, $whence = SEEK_SET) { - $new_offset = false; - - switch ($whence) - { - case SEEK_SET: - $new_offset = $offset; - break; - case SEEK_CUR: - $new_offset = $this->file_position += $offset; - break; - case SEEK_END: - $new_offset = strlen($this->blob) + $offset; - break; - } - - $this->file_position = $offset; - - return ($new_offset !== false); - } - - /** - * Change stream options (NOT IMPLEMENTED) - */ - public function stream_set_option($option, $arg1, $arg2) { - return false; - } - - /** - * Retrieve information about a file resource (NOT IMPLEMENTED) - */ - public function stream_stat() { - - } - - /** - * Retrieve the current position of a stream - */ - public function stream_tell() { - return $this->file_position; - } - - /** - * Truncate stream - */ - public function stream_truncate($new_size) { - - } - - /** - * Write to stream - * FIXME: Could use heavy refactoring - */ - public function stream_write($data) { - /** - * FIXME: This also needs to be added to Granite, in the form of `add()`, - * `rm()` and `commit()` calls - */ - - // Parse the URL into a repository directory, file path and commit ID - list($this->repo, $repo_file, $this->commit) = $this->parse_url($this->path); - - $node = $this->tree_search($this->repo, $this->commit->tree(), $repo_file); - - if ($node !== false) { - // File already exists, attempting modification of existing tree - try { - $this->repo->factory('blob', $node); - - // Create our new blob with the provided $data - $blob = $this->repo->factory('blob'); - $blob->content($data); - $blob->write(); - - // We know the tree exists, so strip the filename from the path and - // find it... - - if (dirname($repo_file) == '.' || dirname($repo_file) == '') { - // Root directory - $tree = $this->repo->head()->tree(); - } else { - // Sub-directory - $tree = $this->repo->factory('tree', $this->tree_search( - $this->repo, - $this->repo->head()->tree(), - dirname($repo_file) - ) - ); - } - - // Replace the old blob with our newly modified one - $tree_nodes = $tree->nodes(); - $tree_nodes[basename($repo_file)] = new Granite\Git\Tree\Node( - basename($repo_file), '100644', $blob->sha() - ); - $tree->nodes($tree_nodes); - $tree->write(); - - // We need to recursively update each parent tree, since they are all - // hashed and the changes will cascade back up the chain - - // So, we're currently at the bottom-most directory - $current_dir = dirname($repo_file); - $previous_tree = $tree; - - if ($current_dir !== '.') { - do { - // Determine the parent directory - $previous_dir = $current_dir; - $current_dir = dirname($current_dir); - - $current_tree = $current_dir !== '.' - ? $this->repo->factory( - 'tree', $this->tree_search( - $this->repo, - $this->repo->head()->tree(), - $current_dir - ) - ) - : $this->repo->head()->tree(); - - $current_nodes = $current_tree->nodes(); - $current_nodes[basename($previous_dir)] = new Granite\Git\Tree\Node( - basename($previous_dir), '040000', $previous_tree->sha() - ); - $current_tree->nodes($current_nodes); - $current_tree->write(); - - $previous_tree = $current_tree; - } while ($current_dir !== '.'); - } - - // Create a new commit to represent this write - $commit = $this->repo->factory('commit'); - $username = OC_User::getUser(); - $user_string = $username . ' ' . time() . ' +0000'; - $commit->author($user_string); - $commit->committer($user_string); - $commit->message("$username modified the `$repo_file` file, " . date('d F Y H:i', time()) . '.'); - $commit->parents(array($this->repo->head()->sha())); - $commit->tree($previous_tree); - - // Write it to disk - $commit->write(); - - // Update the HEAD for the 'master' branch - $this->repo->head('master', $commit->sha()); - - // If we made it this far, write was successful - update the stream - // position and return the number of bytes written - $this->file_position += strlen($data); - return strlen($data); - - } catch (InvalidArgumentException $e) { - // Attempting to write to a directory or other error, fail - return 0; - } - } else { - // File does not exist, needs to be created - - // Create our new blob with the provided $data - $blob = $this->repo->factory('blob'); - $blob->content($data); - $blob->write(); - - if (dirname($repo_file) == '.') { - // Trying to add a new file to the root tree, nice and easy - $tree = $this->repo->head()->tree(); - $tree_nodes = $tree->nodes(); - $tree_nodes[basename($repo_file)] = new Granite\Git\Tree\Node( - basename($repo_file), '100644', $blob->sha() - ); - $tree->nodes($tree_nodes); - $tree->write(); - } else { - // Trying to add a new file to a subdirectory, try and find it - $tree = $this->repo->factory('tree', $this->tree_search( - $this->repo, $this->repo->head()->tree(), dirname($repo_file) - ) - ); - - // Add the blob to the tree - $nodes = $tree->nodes(); - $nodes[basename($repo_file)] = new Granite\Git\Tree\Node( - basename($repo_file), '100644', $blob->sha() - ); - $tree->nodes($nodes); - $tree->write(); - - // We need to recursively update each parent tree, since they are all - // hashed and the changes will cascade back up the chain - - // So, we're currently at the bottom-most directory - $current_dir = dirname($repo_file); - $previous_tree = $tree; - - if ($current_dir !== '.') { - do { - // Determine the parent directory - $previous_dir = $current_dir; - $current_dir = dirname($current_dir); - - $current_tree = $current_dir !== '.' - ? $this->repo->factory( - 'tree', $this->tree_search( - $this->repo, - $this->repo->head()->tree(), - $current_dir - ) - ) - : $this->repo->head()->tree(); - - $current_nodes = $current_tree->nodes(); - $current_nodes[basename($previous_dir)] = new Granite\Git\Tree\Node( - basename($previous_dir), '040000', $previous_tree->sha() - ); - $current_tree->nodes($current_nodes); - $current_tree->write(); - - $previous_tree = $current_tree; - } while ($current_dir !== '.'); - - $tree = $previous_tree; - } - } - - // Create a new commit to represent this write - $commit = $this->repo->factory('commit'); - $username = OC_User::getUser(); - $user_string = $username . ' ' . time() . ' +0000'; - $commit->author($user_string); - $commit->committer($user_string); - $commit->message("$username created the `$repo_file` file, " . date('d F Y H:i', time()) . '.'); - $commit->parents(array($this->repo->head()->sha())); - $commit->tree($tree); // Top-level tree (NOT the newly modified tree) - - // Write it to disk - $commit->write(); - - // Update the HEAD for the 'master' branch - $this->repo->head('master', $commit->sha()); - - // If we made it this far, write was successful - update the stream - // position and return the number of bytes written - $this->file_position += strlen($data); - return strlen($data); - } - - // Write failed - return 0; - } - - /** - * Delete a file - */ - public function unlink($path) { - - } - - /** - * Retrieve information about a file - */ - public function url_stat($path, $flags) { - // Parse the URL into a repository directory, file path and commit ID - list($this->repo, $repo_file, $this->commit) = $this->parse_url($path); - - $node = $this->tree_search($this->repo, $this->commit->tree(), $repo_file); - - if ($node == false && $this->commit->sha() == $this->repo->head()->sha()) { - // A new file - no information available - $size = 0; - $mtime = -1; - } else { - - // Is it a directory? - try { - $this->repo->factory('tree', $node); - $size = 4096; // FIXME - } catch (InvalidArgumentException $e) { - // Must be a file - $size = strlen(file_get_contents($path)); - } - - // Parse the timestamp from the commit message - preg_match('/[0-9]{10}+/', $this->commit->committer(), $matches); - $mtime = $matches[0]; - } - - $stat["dev"] = ""; - $stat["ino"] = ""; - $stat["mode"] = ""; - $stat["nlink"] = ""; - $stat["uid"] = ""; - $stat["gid"] = ""; - $stat["rdev"] = ""; - $stat["size"] = $size; - $stat["atime"] = $mtime; - $stat["mtime"] = $mtime; - $stat["ctime"] = $mtime; - $stat["blksize"] = ""; - $stat["blocks"] = ""; - - return $stat; - } - - /** - * Debug function for development purposes - */ - private function debug($message, $level = OC_Log::DEBUG) - { - if ($this->debug) { - OC_Log::write('files_versioning', $message, $level); - } - } - - /** - * Parses a URL of the form: - * `versioned://path/to/git/repository/.git/path/to/file#SHA-1-commit-id` - * FIXME: Will throw an InvalidArgumentException if $path is invaid - * - * @param string $path The path to parse - * - * @return array An array containing an instance of Granite\Git\Repository, - * the file path, and an instance of Granite\Git\Commit - * @throws InvalidArgumentException If the repository cannot be loaded - */ - private function parse_url($path) - { - preg_match('/\/([A-Za-z0-9\/]+\.git\/)([A-Za-z0-9\/\.\/]*)(#([A-Fa-f0-9]+))*/', $path, $matches); - - // Load up the repo - $repo = new \Granite\Git\Repository($matches[1]); - // Parse the filename (stripping any trailing slashes) - $repo_file = $matches[2]; - if (substr($repo_file, -1) == '/') { - $repo_file = substr($repo_file, 0, -1); - } - - // Default to HEAD if no commit is provided - $repo_commit = isset($matches[4]) - ? $matches[4] - : $repo->head()->sha(); - - // Load the relevant commit - $commit = $repo->factory('commit', $repo_commit); - - return array($repo, $repo_file, $commit); - } - - /** - * Recursively searches a tree for a path, returning FALSE if is not found - * or an SHA-1 id if it is found. - * - * @param string $repo The repository containing the tree object - * @param string $tree The tree object to search - * @param string $path The path to search for (relative to the tree) - * @param int $depth The depth of the current search (for recursion) - * - * @return string|boolean The SHA-1 id of the sub-tree - */ - private function tree_search($repo, $tree, $path, $depth = 0) - { - $paths = array_values(explode(DIRECTORY_SEPARATOR, $path)); - - $current_path = $paths[$depth]; - - $nodes = $tree->nodes(); - foreach ($nodes as $node) { - if ($node->name() == $current_path) { - - if (count($paths)-1 == $depth) { - // Stop, found it - return $node->sha(); - } - - // Recurse if necessary - if ($node->isDirectory()) { - $tree = $this->repo->factory('tree', $node->sha()); - return $this->tree_search($repo, $tree, $path, $depth + 1); - } - } - } - - return false; - } - -} -- GitLab From 9b134b063683aca678e19912ebc3928321751714 Mon Sep 17 00:00:00 2001 From: Frank Karlitschek Date: Tue, 24 Apr 2012 15:41:54 +0200 Subject: [PATCH 265/430] =?UTF-8?q?move=20granite=20also=20to=20apps-playg?= =?UTF-8?q?round=20because=20it=C2=B4s=20not=20stable=20yet=20and=20is=20n?= =?UTF-8?q?o=20longer=20used?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdparty/granite/git/blob.php | 162 ------------- 3rdparty/granite/git/commit.php | 232 ------------------- 3rdparty/granite/git/object/index.php | 210 ----------------- 3rdparty/granite/git/object/loose.php | 81 ------- 3rdparty/granite/git/object/packed.php | 304 ------------------------- 3rdparty/granite/git/object/raw.php | 153 ------------- 3rdparty/granite/git/repository.php | 293 ------------------------ 3rdparty/granite/git/tag.php | 38 ---- 3rdparty/granite/git/tree.php | 198 ---------------- 3rdparty/granite/git/tree/node.php | 126 ---------- 10 files changed, 1797 deletions(-) delete mode 100644 3rdparty/granite/git/blob.php delete mode 100644 3rdparty/granite/git/commit.php delete mode 100644 3rdparty/granite/git/object/index.php delete mode 100644 3rdparty/granite/git/object/loose.php delete mode 100644 3rdparty/granite/git/object/packed.php delete mode 100644 3rdparty/granite/git/object/raw.php delete mode 100644 3rdparty/granite/git/repository.php delete mode 100644 3rdparty/granite/git/tag.php delete mode 100644 3rdparty/granite/git/tree.php delete mode 100644 3rdparty/granite/git/tree/node.php diff --git a/3rdparty/granite/git/blob.php b/3rdparty/granite/git/blob.php deleted file mode 100644 index 781a697d560..00000000000 --- a/3rdparty/granite/git/blob.php +++ /dev/null @@ -1,162 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git; -use \Granite\Git\Object\Raw as Raw; -use \InvalidArgumentException as InvalidArgumentException; -use \finfo as finfo; -/** - * **Granite\Git\Blob** represents the raw content of an object in a Git repository, - * typically a **file**. This class provides methods related to the handling of - * blob content, mimetypes, sizes and write support. - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Blob -{ - - /** - * Stores the SHA-1 id of the object requested; accessed through the `sha()` - * method where it is recalculated based on the blob content. - */ - private $sha = null; - /** - * The raw binary string of the file contents. - */ - private $content = ""; - /** - * The path to the repository location. - */ - private $path; - - /** - * Fetches a raw Git object and parses the result. Throws an - * InvalidArgumentException if the object is not of the correct type, - * or cannot be found. - * - * @param string $path The path to the repository root. - * @param string $sha The SHA-1 id of the requested object, or `null` if - * creating a new blob object. - * - * @throws InvalidArgumentException If the SHA-1 id provided is not a blob. - */ - public function __construct($path, $sha = NULL) - { - $this->path = $path; - if ($sha !== NULL) { - $this->sha = $sha; - $object = Raw::factory($path, $sha); - - if ($object->type() !== Raw::OBJ_BLOB) { - throw new InvalidArgumentException( - "The object $sha is not a blob, type is {$object->type()}" - ); - } - - $this->content = $object->content(); - unset($object); - } - } - - /** - * Sets or returns the raw file content, depending whether the parameter is - * provided. - * - * @param string $content The object content to set, or `null` if requesting the - * current content. - * - * @return string The raw binary string of the file contents. - */ - public function content($content = NULL) - { - if ($content == NULL) { - return $this->content; - } - $this->content = $content; - } - - /** - * Returns the size of the file content in bytes, equivalent to - * `strlen($blob->content())`. - * - * @return int The size of the object in bytes. - */ - public function size() - { - return strlen($this->content); - } - - /** - * Updates and returns the SHA-1 id of the object, based on it's contents. - * - * @return int The SHA-1 id of the object. - */ - public function sha() - { - $sha = hash_init('sha1'); - $header = 'blob ' . strlen($this->content) . "\0"; - hash_update($sha, $header); - hash_update($sha, $this->content); - $this->sha = hash_final($sha); - return $this->sha; - } - - /** - * Returns the mimetype of the object, using `finfo()` to determine the mimetype - * of the string. - * - * @return string The object mimetype. - * @see http://php.net/manual/en/function.finfo-open.php - */ - public function mimetype() - { - $finfo = new finfo(FILEINFO_MIME); - return $finfo->buffer($this->content); - } - - /** - * Encode and compress the object content, saving it to a 'loose' file. - * - * @return boolean True on success, false on failure. - */ - public function write() - { - $sha = $this->sha(TRUE); - $path = $this->path - . 'objects' - . DIRECTORY_SEPARATOR - . substr($sha, 0, 2) - . DIRECTORY_SEPARATOR - . substr($sha, 2); - // FIXME: currently writes loose objects only - if (file_exists($path)) { - return FALSE; - } - - if (!is_dir(dirname($path))) { - mkdir(dirname($path), 0777, TRUE); - } - - $loose = fopen($path, 'wb'); - $data = 'blob ' . strlen($this->content) . "\0" . $this->content; - $write = fwrite($loose, gzcompress($data)); - fclose($loose); - - return ($write !== FALSE); - } - -} diff --git a/3rdparty/granite/git/commit.php b/3rdparty/granite/git/commit.php deleted file mode 100644 index 51077e89f3c..00000000000 --- a/3rdparty/granite/git/commit.php +++ /dev/null @@ -1,232 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git; -use \Granite\Git\Object\Raw as Raw; -use \InvalidArgumentException as InvalidArgumentException; - -/** - * Commit represents a full commit object - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Commit -{ - - /** - * The path to the repository root - */ - private $path; - /** - * The SHA-1 id of the requested commit - */ - private $sha; - /** - * The size of the commit in bytes - */ - private $size; - /** - * The commit message - */ - private $message; - /** - * The full committer string - */ - private $committer; - /** - * The full author string - */ - private $author; - /** - * The SHA-1 ids of the parent commits - */ - private $parents = array(); - - /** - * Fetches a raw Git object and parses the result. Throws an - * InvalidArgumentException if the object is not of the correct type, - * or cannot be found. - * - * @param string $path The path to the repository root - * @param string $sha The SHA-1 id of the requested object - * - * @throws InvalidArgumentException - */ - public function __construct($path, $sha = NULL) - { - $this->path = $path; - if ($sha !== NULL) { - $this->sha = $sha; - $object = Raw::factory($path, $sha); - $this->size = $object->size(); - - if ($object->type() !== Raw::OBJ_COMMIT) { - throw new InvalidArgumentException( - "The object $sha is not a commit, type is " . $object->type() - ); - } - - // Parse headers and commit message (delimited with "\n\n") - list($headers, $this->message) = explode("\n\n", $object->content(), 2); - $headers = explode("\n", $headers); - - foreach ($headers as $header) { - list($header, $value) = explode(' ', $header, 2); - if ($header == 'parent') { - $this->parents[] = $value; - } else { - $this->$header = $value; - } - } - - $this->tree = new Tree($this->path, $this->tree); - } - } - - /** - * Returns the message stored in the commit - * - * @return string The commit message - */ - public function message($message = NULL) - { - if ($message !== NULL) { - $this->message = $message; - return $this; - } - return $this->message; - } - - /** - * Returns the commiter string - * - * @return string The committer string - */ - public function committer($committer = NULL) - { - if ($committer !== NULL) { - $this->committer = $committer; - return $this; - } - return $this->committer; - } - - /** - * Returns the author string - * - * @return string The author string - */ - public function author($author = NULL) - { - if ($author !== NULL) { - $this->author = $author; - return $this; - } - return $this->author; - } - - /** - * Returns the parents of the commit, or an empty array if none - * - * @return array The parents of the commit - */ - public function parents($parents = NULL) - { - if ($parents !== NULL) { - $this->parents = $parents; - return $this; - } - return $this->parents; - } - - /** - * Returns a tree object associated with the commit - * - * @return Tree - */ - public function tree(Tree $tree = NULL) - { - if ($tree !== NULL) { - $this->tree = $tree; - return $this; - } - return $this->tree; - } - - /** - * Returns the size of the commit in bytes (Git header + data) - * - * @return int - */ - public function size() - { - return $this->size; - } - - /** - * Returns the size of the commit in bytes (Git header + data) - * - * @return int - */ - public function sha() - { - $this->sha = hash('sha1', $this->_raw()); - return $this->sha; - } - - public function write() - { - $sha = $this->sha(); - $path = $this->path - . 'objects' - . DIRECTORY_SEPARATOR - . substr($sha, 0, 2) - . DIRECTORY_SEPARATOR - . substr($sha, 2); - // FIXME: currently writes loose objects only - if (file_exists($path)) { - return FALSE; - } - - if (!is_dir(dirname($path))) { - mkdir(dirname($path), 0777, TRUE); - } - - $loose = fopen($path, 'wb'); - $data = $this->_raw(); - $write = fwrite($loose, gzcompress($data)); - fclose($loose); - - return ($write !== FALSE); - } - - public function _raw() - { - $data = 'tree ' . $this->tree->sha() . "\n"; - foreach ($this->parents as $parent) - { - $data .= "parent $parent\n"; - } - $data .= 'author ' . $this->author . "\n"; - $data .= 'committer ' . $this->committer . "\n\n"; - $data .= $this->message; - - $data = 'commit ' . strlen($data) . "\0" . $data; - return $data; - } - -} diff --git a/3rdparty/granite/git/object/index.php b/3rdparty/granite/git/object/index.php deleted file mode 100644 index 239706d4efd..00000000000 --- a/3rdparty/granite/git/object/index.php +++ /dev/null @@ -1,210 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git\Object; -use \UnexpectedValueException as UnexpectedValueException; - -/** - * Index represents a packfile index - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT License - * @link http://craig0990.github.com/Granite/ - */ -class Index -{ - const INDEX_MAGIC = "\377tOc"; - - /** - * The full path to the packfile index - */ - private $path; - /** - * The offset at which the fanout begins, version 2+ indexes have a 2-byte header - */ - private $offset = 8; - /** - * The size of the SHA-1 entries, version 1 stores 4-byte offsets alongside to - * total 24 bytes, version 2+ stores offsets separately - */ - private $size = 20; - /** - * The version of the index file format, versions 1 and 2 are in use and - * currently supported - */ - private $version; - - /** - * Fetches a raw Git object and parses the result - * - * @param string $path The path to the repository root - * @param string $packname The name of the packfile index to read - */ - public function __construct($path, $packname) - { - $this->path = $path - . 'objects' - . DIRECTORY_SEPARATOR - . 'pack' - . DIRECTORY_SEPARATOR - . 'pack-' . $packname . '.idx'; - - $this->version = $this->_readVersion(); - if ($this->version !== 1 && $this->version !== 2) { - throw new UnexpectedValueException( - "Unsupported index version (version $version)" - ); - } - - if ($this->version == 1) { - $this->offset = 0; // Version 1 index has no header/version - $this->size = 24; // Offsets + SHA-1 ids are stored together - } - } - - /** - * Returns the offset of the object stored in the index - * - * @param string $sha The SHA-1 id of the object being requested - * - * @return int The offset of the object in the packfile - */ - public function find($sha) - { - $index = fopen($this->path, 'rb'); - $offset = false; // Offset for object in packfile not found by default - - // Read the fanout to skip to the start char in the sorted SHA-1 list - list($start, $after) = $this->_readFanout($index, $sha); - - if ($start == $after) { - fclose($index); - return false; // Object is apparently located in a 0-length section - } - - // Seek $offset + 255 4-byte fanout entries and read 256th entry - fseek($index, $this->offset + 4 * 255); - $totalObjects = $this->_uint32($index); - - // Look up the SHA-1 id of the object - // TODO: Binary search - fseek($index, $this->offset + 1024 + $this->size * $start); - for ($i = $start; $i < $after; $i++) { - if ($this->version == 1) { - $offset = $this->_uint32($index); - } - - $name = fread($index, 20); - if ($name == pack('H40', $sha)) { - break; // Found it - } - } - - if ($i == $after) { - fclose($index); - return false; // Scanned entire section, couldn't find it - } - - if ($this->version == 2) { - // Jump to the offset location and read it - fseek($index, 1032 + 24 * $totalObjects + 4 * $i); - $offset = $this->_uint32($index); - if ($offset & 0x80000000) { - // Offset is a 64-bit integer; packfile is larger than 2GB - fclose($index); - throw new UnexpectedValueException( - "Packfile larger than 2GB, currently unsupported" - ); - } - } - - fclose($index); - return $offset; - } - - /** - * Converts a binary string into a 32-bit unsigned integer - * - * @param handle $file Binary string to convert - * - * @return int Integer value - */ - private function _uint32($file) - { - $val = unpack('Nx', fread($file, 4)); - return $val['x']; - } - - /** - * Reads the fanout for a particular SHA-1 id - * - * Largely modified from Glip, with some reference to Grit - largely because I - * can't see how to re-implement this in PHP - * - * @param handle $file File handle to the index file - * @param string $sha The SHA-1 id to search for - * @param int $offset The offset at which the fanout begins - * - * @return array Array containing integer 'start' and - * 'past-the-end' locations - */ - private function _readFanout($file, $sha) - { - $sha = pack('H40', $sha); - fseek($file, $this->offset); - if ($sha{0} == "\00") { - /** - * First character is 0, read first fanout entry to provide - * 'past-the-end' location (since first fanout entry provides start - * point for '1'-prefixed SHA-1 ids) - */ - $start = 0; - fseek($file, $this->offset); // Jump to start of fanout, $offset bytes in - $after = $this->_uint32($file); - } else { - /** - * Take ASCII value of first character, minus one to get the fanout - * position of the offset (minus one because the fanout does not - * contain an entry for "\00"), multiplied by four bytes per entry - */ - fseek($file, $this->offset + (ord($sha{0}) - 1) * 4); - $start = $this->_uint32($file); - $after = $this->_uint32($file); - } - - return array($start, $after); - } - - /** - * Returns the version number of the index file, or 1 if there is no version - * information - * - * @return int - */ - private function _readVersion() - { - $file = fopen($this->path, 'rb'); - $magic = fread($file, 4); - $version = $this->_uint32($file); - - if ($magic !== self::INDEX_MAGIC) { - $version = 1; - } - - fclose($file); - return $version; - } - -} diff --git a/3rdparty/granite/git/object/loose.php b/3rdparty/granite/git/object/loose.php deleted file mode 100644 index 32f894845b9..00000000000 --- a/3rdparty/granite/git/object/loose.php +++ /dev/null @@ -1,81 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git\Object; -use \UnexpectedValueException as UnexpectedValueException; - -/** - * Loose represents a loose object in the Git repository - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Loose extends Raw -{ - - /** - * Reads an object from a loose object file based on the SHA-1 id - * - * @param string $path The path to the repository root - * @param string $sha The SHA-1 id of the requested object - * - * @throws UnexpectedValueException If the type is not 'commit', 'tree', - * 'tag' or 'blob' - */ - public function __construct($path, $sha) - { - $this->sha = $sha; - - $loose_path = $path - . 'objects/' - . substr($sha, 0, 2) - . '/' - . substr($sha, 2); - - if (!file_exists($loose_path)) { - throw new InvalidArgumentException("Cannot open loose object file for $sha"); - } - - $raw = gzuncompress(file_get_contents($loose_path)); - $data = explode("\0", $raw, 2); - - $header = $data[0]; - $this->content = $data[1]; - - list($this->type, $this->size) = explode(' ', $header); - - switch ($this->type) { - case 'commit': - $this->type = Raw::OBJ_COMMIT; - break; - case 'tree': - $this->type = Raw::OBJ_TREE; - break; - case 'blob': - $this->type = Raw::OBJ_BLOB; - break; - case 'tag': - $this->type = Raw::OBJ_TAG; - break; - default: - throw new UnexpectedValueException( - "Unexpected type '{$this->type}'" - ); - break; - } - } - -} diff --git a/3rdparty/granite/git/object/packed.php b/3rdparty/granite/git/object/packed.php deleted file mode 100644 index 7e8d663b32e..00000000000 --- a/3rdparty/granite/git/object/packed.php +++ /dev/null @@ -1,304 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git\Object; -use \UnexpectedValueException as UnexpectedValueException; - -/** - * Packed represents a packed object in the Git repository - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Packed extends Raw -{ - - /** - * The name of the packfile being read - */ - private $_packfile; - - /** - * Added to the object size to make a 'best-guess' effort at how much compressed - * data to read - should be reimplemented, ideally with streams. - */ - const OBJ_PADDING = 512; - - /** - * Reads the object data from the compressed data at $offset in $packfile - * - * @param string $packfile The path to the packfile - * @param int $offset The offset of the object data - */ - public function __construct($packfile, $offset) - { - $this->_packfile = $packfile; - - list($this->type, $this->size, $this->content) - = $this->_readPackedObject($offset); - } - - /** - * Reads the object data at $this->_offset - * - * @param int $offset Offset of the object header - * - * @return array Containing the type, size and object data - */ - private function _readPackedObject($offset) - { - $file = fopen($this->_packfile, 'rb'); - fseek($file, $offset); - // Read the type and uncompressed size from the object header - list($type, $size) = $this->_readHeader($file, $offset); - $object_offset = ftell($file); - - if ($type == self::OBJ_OFS_DELTA || $type == self::OBJ_REF_DELTA) { - return $this->_unpackDeltified( - $file, $offset, $object_offset, $type, $size - ); - } - - $content = gzuncompress(fread($file, $size + self::OBJ_PADDING), $size); - - return array($type, $size, $content); - } - - /** - * Reads a packed object header, returning the type and the size. For more - * detailed information, refer to the @see tag. - * - * From the @see tag: "Each byte is really 7 bits of data, with the first bit - * being used to say if that hunk is the last one or not before the data starts. - * If the first bit is a 1, you will read another byte, otherwise the data starts - * next. The first 3 bits in the first byte specifies the type of data..." - * - * @param handle $file File handle to read - * @param int $offset Offset of the object header - * - * @return array Containing the type and the size - * @see http://book.git-scm.com/7_the_packfile.html - */ - private function _readHeader($file, $offset) - { - // Read the object header byte-by-byte - fseek($file, $offset); - $byte = ord(fgetc($file)); - /** - * Bit-shift right by four, then ignore the first bit with a bitwise AND - * This gives us the object type in binary: - * 001 commit self::OBJ_COMMIT - * 010 tree self::OBJ_TREE - * 011 blob self::OBJ_BLOB - * 100 tag self::OBJ_TAG - * 110 offset delta self::OBJ_OFS_DELTA - * 111 ref delta self::OBJ_REF_DELTA - * - * (000 is undefined, 101 is not currently in use) - * See http://book.git-scm.com/7_the_packfile.html for details - */ - $type = ($byte >> 4) & 0x07; - - // Read the last four bits of the first byte, used to find the size - $size = $byte & 0x0F; - - /** - * $shift initially set to four, since we use the last four bits of the first - * byte - * - * $byte & 0x80 checks the initial bit is set to 1 (i.e. keep reading data) - * - * Finally, $shift is incremented by seven for each consecutive byte (because - * we ignore the initial bit) - */ - for ($shift = 4; $byte & 0x80; $shift += 7) { - $byte = ord(fgetc($file)); - /** - * The size is ANDed against 0x7F to strip the initial bit, then - * bitshifted by left $shift (4 or 7, depending on whether it's the - * initial byte) and ORed against the existing binary $size. This - * continuously increments the $size variable. - */ - $size |= (($byte & 0x7F) << $shift); - } - - return array($type, $size); - } - - /** - * Unpacks a deltified object located at $offset in $file - * - * @param handle $file File handle to read - * @param int $offset Offset of the object data - * @param int $object_offset Offset of the object data, past the header - * @param int $type The object type, either OBJ_REF_DELTA - or OBJ_OFS_DELTA - * @param int $size The expected size of the uncompressed data - * - * @return array Containing the type, size and object data - */ - private function _unpackDeltified($file, $offset, $object_offset, $type, $size) - { - fseek($file, $object_offset); - - if ($type == self::OBJ_REF_DELTA) { - - $base_sha = bin2hex(fread($file, 20)); - - $path = substr($this->_packfile, 0, strpos($this->_packfile, '.git')+5); - $base = Raw::factory($path, $base_sha); - $type = $base->type(); - $base = $base->content(); - - $delta = gzuncompress( - fread($file, $size + self::OBJ_PADDING), $size - ); - - $content = $this->_applyDelta($base, $delta); - - } elseif ($type == self::OBJ_OFS_DELTA) { - - // 20 = maximum varint size according to Glip - $data = fread($file, $size + self::OBJ_PADDING + 20); - - list($base_offset, $length) = $this->_bigEndianNumber($data); - - $delta = gzuncompress(substr($data, $length), $size); - unset($data); - - $base_offset = $offset - $base_offset; - list($type, $size, $base) = $this->_readPackedObject($base_offset); - - $content = $this->_applyDelta($base, $delta); - - } else { - throw new UnexpectedValueException( - "Unknown type $type for deltified object" - ); - } - - return array($type, strlen($content), $content); - } - - /** - * Applies the $delta byte-sequence to $base and returns the - * resultant binary string. - * - * This code is modified from Grit (see below), the Ruby - * implementation used for GitHub under an MIT license. - * - * @param string $base The base string for the delta to be applied to - * @param string $delta The delta string to apply - * - * @return string The patched binary string - * @see - * https://github.com/mojombo/grit/blob/master/lib/grit/git-ruby/internal/pack.rb - */ - private function _applyDelta($base, $delta) - { - $pos = 0; - $src_size = $this->_varint($delta, $pos); - $dst_size = $this->_varint($delta, $pos); - - if ($src_size !== strlen($base)) { - throw new UnexpectedValueException( - 'Expected base delta size ' . strlen($base) . ' does not match the expected ' - . "value $src_size" - ); - } - - $dest = ""; - while ($pos < strlen($delta)) { - $byte = ord($delta{$pos++}); - - if ($byte & 0x80) { - /* copy a part of $base */ - $offset = 0; - if ($byte & 0x01) $offset = ord($delta{$pos++}); - if ($byte & 0x02) $offset |= ord($delta{$pos++}) << 8; - if ($byte & 0x04) $offset |= ord($delta{$pos++}) << 16; - if ($byte & 0x08) $offset |= ord($delta{$pos++}) << 24; - $length = 0; - if ($byte & 0x10) $length = ord($delta{$pos++}); - if ($byte & 0x20) $length |= ord($delta{$pos++}) << 8; - if ($byte & 0x40) $length |= ord($delta{$pos++}) << 16; - if ($length == 0) $length = 0x10000; - $dest .= substr($base, $offset, $length); - } else { - /* take the next $byte bytes as they are */ - $dest .= substr($delta, $pos, $byte); - $pos += $byte; - } - } - - if (strlen($dest) !== $dst_size) { - throw new UnexpectedValueException( - "Deltified string expected to be $dst_size bytes, but actually " - . strlen($dest) . ' bytes' - ); - } - - return $dest; - } - - /** - * Parse a Git varint (variable-length integer). Used in the `_applyDelta()` - * method to read the delta header. - * - * @param string $string The string to parse - * @param int &$pos The position in the string to read from - * - * @return int The integer value - */ - private function _varint($string, &$pos = 0) - { - $varint = 0; - $bitmask = 0x80; - for ($i = 0; $bitmask & 0x80; $i += 7) { - $bitmask = ord($string{$pos++}); - $varint |= (($bitmask & 0x7F) << $i); - } - return $varint; - } - - /** - * Decodes a big endian modified base 128 number (refer to @see tag); this only - * appears to be used in one place, the offset delta in packfiles. The offset - * is the number of bytes to seek back from the start of the delta object to find - * the base object. - * - * This code has been implemented using the C code given in the @see tag below. - * - * @param string &$data The data to read from and decode the number - * - * @return Array Containing the base offset (number of bytes to seek back) and - * the length to use when reading the delta - * @see http://git.rsbx.net/Documents/Git_Data_Formats.txt - */ - private function _bigEndianNumber(&$data) - { - $i = 0; - $byte = ord($data{$i++}); - $number = $byte & 0x7F; - while ($byte & 0x80) { - $byte = ord($data{$i++}); - $number = (($number + 1) << 7) | ($byte & 0x7F); - } - - return array($number, $i); - } - -} diff --git a/3rdparty/granite/git/object/raw.php b/3rdparty/granite/git/object/raw.php deleted file mode 100644 index 56f363c37b2..00000000000 --- a/3rdparty/granite/git/object/raw.php +++ /dev/null @@ -1,153 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git\Object; -use \InvalidArgumentException as InvalidArgumentException; - -/** - * Raw represents a raw Git object, using Index to locate - * packed objects. - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Raw -{ - /** - * Integer values for Git objects - * @see http://book.git-scm.com/7_the_packfile.html - */ - const OBJ_COMMIT = 1; - const OBJ_TREE = 2; - const OBJ_BLOB = 3; - const OBJ_TAG = 4; - const OBJ_OFS_DELTA = 6; - const OBJ_REF_DELTA = 7; - - /** - * The SHA-1 id of the requested object - */ - protected $sha; - /** - * The type of the requested object (see class constants) - */ - protected $type; - /** - * The binary string content of the requested object - */ - protected $content; - - /** - * Returns an instance of a raw Git object - * - * @param string $path The path to the repository root - * @param string $sha The SHA-1 id of the requested object - * - * @return Packed|Loose - */ - public static function factory($path, $sha) - { - $loose_path = $path - . 'objects/' - . substr($sha, 0, 2) - . '/' - . substr($sha, 2); - if (file_exists($loose_path)) { - return new Loose($path, $sha); - } else { - return self::_findPackedObject($path, $sha); - } - } - - /** - * Returns the raw content of the Git object requested - * - * @return string Raw object content - */ - public function content() - { - return $this->content; - } - - /** - * Returns the size of the Git object - * - * @return int The size of the object in bytes - */ - public function size() - { - return strlen($this->content); - } - - /** - * Returns the type of the object as either commit, tag, blob or tree - * - * @return string The object type - */ - public function type() - { - return $this->type; - } - - /** - * Searches a packfile for the SHA id and reads the object from the packfile - * - * @param string $path The path to the repository - * @param string $sha The SHA-1 id of the object being requested - * - * @throws \InvalidArgumentException - * @return array An array containing the type, size and object data - */ - private static function _findPackedObject($path, $sha) - { - $packfiles = glob( - $path - . 'objects' - . DIRECTORY_SEPARATOR - . 'pack' - . DIRECTORY_SEPARATOR - . 'pack-*.pack' - ); - - $offset = false; - foreach ($packfiles as $packfile) { - $packname = substr(basename($packfile, '.pack'), 5); - $idx = new Index($path, $packname); - $offset = $idx->find($sha); - - if ($offset !== false) { - break; // Found it - } - } - - if ($offset == false) { - throw new InvalidArgumentException("Could not find packed object $sha"); - } - - $packname = $path - . 'objects' - . DIRECTORY_SEPARATOR - . 'pack' - . DIRECTORY_SEPARATOR - . 'pack-' . $packname . '.pack'; - $object = new Packed($packname, $offset); - - return $object; - } - -} - -?> diff --git a/3rdparty/granite/git/repository.php b/3rdparty/granite/git/repository.php deleted file mode 100644 index 30b58a39f5a..00000000000 --- a/3rdparty/granite/git/repository.php +++ /dev/null @@ -1,293 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git; -use \InvalidArgumentException as InvalidArgumentException; -use \UnexpectedValueException as UnexpectedValueException; - -/** - * Repository represents a Git repository, providing a variety of methods for - * fetching objects from SHA-1 ids or the tip of a branch with `head()` - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Repository -{ - - /** - * The path to the repository root - */ - private $_path; - /** - * The indexed version of a commit, ready to write with `commit()` - */ - private $idx_commit; - /** - * The indexed version of a tree, modified to with `add()` and `remove()` - */ - private $idx_tree; - - /** - * Sets the repository path - * - * @param string $path The path to the repository root (i.e. /repo/.git/) - */ - public function __construct($path) - { - if (!is_dir($path)) { - throw new InvalidArgumentException("Unable to find directory $path"); - } elseif (!is_readable($path)) { - throw new InvalidArgumentException("Unable to read directory $path"); - } elseif (!is_dir($path . DIRECTORY_SEPARATOR . 'objects') - || !is_dir($path . DIRECTORY_SEPARATOR . 'refs') - ) { - throw new UnexpectedValueException( - "Invalid directory, could not find 'objects' or 'refs' in $path" - ); - } - - $this->_path = $path; - $this->idx_commit = $this->factory('commit'); - $this->idx_tree = $this->factory('tree'); - } - - /** - * Returns an object from the Repository of the given type, with the given - * SHA-1 id, or false if it cannot be found - * - * @param string $type The type (blob, commit, tag or tree) of object being - * requested - * @param string $sha The SHA-1 id of the object (or the name of a tag) - * - * @return Blob|Commit|Tag|Tree - */ - public function factory($type, $sha = null) - { - if (!in_array($type, array('blob', 'commit', 'tag', 'tree'))) { - throw new InvalidArgumentException("Invalid type: $type"); - } - - if ($type == 'tag') { - $sha = $this->_ref('tags' . DIRECTORY_SEPARATOR . $sha); - } - $type = 'Granite\\Git\\' . ucwords($type); - - return new $type($this->_path, $sha); - } - - /** - * Returns a Commit object representing the HEAD commit - * - * @param string $branch The branch name to lookup, defaults to 'master' - * - * @return Commit An object representing the HEAD commit - */ - public function head($branch = 'master', $value = NULL) - { - if ($value == NULL) - return $this->factory( - 'commit', $this->_ref('heads' . DIRECTORY_SEPARATOR . $branch) - ); - - file_put_contents( - $this->_path . DIRECTORY_SEPARATOR - . 'refs' . DIRECTORY_SEPARATOR - . 'heads' . DIRECTORY_SEPARATOR . 'master', - $value - ); - } - - /** - * Returns a string representing the repository's location, which may or may - * not be initialised - * - * @return string A string representing the repository's location - */ - public function path() - { - return $this->_path; - } - - /** - * Returns an array of the local branches under `refs/heads` - * - * @return array - */ - public function tags() - { - return $this->_refs('tags'); - } - - /** - * Returns an array of the local tags under `refs/tags` - * - * @return array - */ - public function branches() - { - return $this->_refs('heads'); - } - - private function _refs($type) - { - $dir = $this->_path . 'refs' . DIRECTORY_SEPARATOR . $type; - $refs = glob($dir . DIRECTORY_SEPARATOR . '*'); - foreach ($refs as &$ref) { - $ref = basename($ref); - } - return $refs; - } - - /** - * Initialises a Git repository - * - * @return boolean Returns true on success, false on error - */ - public static function init($path) - { - $path .= '/'; - if (!is_dir($path)) { - mkdir($path); - } elseif (is_dir($path . 'objects')) { - return false; - } - - mkdir($path . 'objects'); - mkdir($path . 'objects/info'); - mkdir($path . 'objects/pack'); - mkdir($path . 'refs'); - mkdir($path . 'refs/heads'); - mkdir($path . 'refs/tags'); - - file_put_contents($path . 'HEAD', 'ref: refs/heads/master'); - - return true; - } - - /** - * Writes the indexed commit to disk, with blobs added/removed via `add()` and - * `rm()` - * - * @param string $message The commit message - * @param string $author The author name - * - * @return boolean True on success, or false on failure - */ - public function commit($message, $author) - { - $user_string = $username . ' ' . time() . ' +0000'; - - try { - $parents = array($this->repo->head()->sha()); - } catch (InvalidArgumentException $e) { - $parents = array(); - } - - $this->idx_commit->message($message); - $this->idx_commit->author($user_string); - $this->idx_commit->committer($user_string); - $this->idx_commit->tree($this->idx_tree); - $commit->parents($parents); - - $this->idx_tree->write(); - $this->idx_commit->write(); - - $this->repo->head('master', $this->idx_commit->sha()); - - $this->idx_commit = $this->factory('commit'); - $this->idx_tree = $this->factory('tree'); - } - - /** - * Adds a file to the indexed commit, to be written to disk with `commit()` - * - * @param string $filename The filename to save it under - * @param Granite\Git\Blob $blob The raw blob object to add to the tree - */ - public function add($filename, Granite\Git\Blob $blob) - { - $blob->write(); - $nodes = $this->idx_tree->nodes(); - $nodes[$filename] = new Granite\Git\Tree\Node($filename, '100644', $blob->sha()); - $this->idx_tree->nodes($nodes); - } - - /** - * Removes a file from the indexed commit - */ - public function rm($filename) - { - $nodes = $this->idx_tree->nodes(); - unset($nodes[$filename]); - $this->idx_tree->nodes($nodes); - } - - /** - * Returns an SHA-1 id of the ref resource - * - * @param string $ref The ref name to lookup - * - * @return string An SHA-1 id of the ref resource - */ - private function _ref($ref) - { - // All refs are stored in `.git/refs` - $file = $this->_path . 'refs' . DIRECTORY_SEPARATOR . $ref; - - if (file_exists($file)) { - return trim(file_get_contents($file)); - } - - $sha = $this->_packedRef($ref); - - if ($sha == false) { - throw new InvalidArgumentException("The ref $ref could not be found"); - } - - return $sha; - } - - /** - * Returns an SHA-1 id of the ref resource, or false if it cannot be found - * - * @param string $ref The ref name to lookup - * - * @return string An SHA-1 id of the ref resource - */ - private function _packedRef($ref) - { - $sha = false; - if (file_exists($this->_path . 'packed-refs')) { - $file = fopen($this->_path . 'packed-refs', 'r'); - - while (($line = fgets($file)) !== false) { - $info = explode(' ', $line); - if (count($info) == 2 - && trim($info[1]) == 'refs' . DIRECTORY_SEPARATOR . $ref - ) { - $sha = trim($info[0]); - break; - } - } - - fclose($file); - } - - return $sha; - } - -} diff --git a/3rdparty/granite/git/tag.php b/3rdparty/granite/git/tag.php deleted file mode 100644 index e26ddaffa6d..00000000000 --- a/3rdparty/granite/git/tag.php +++ /dev/null @@ -1,38 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git; - -/** - * Tag represents a full tag object - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Tag -{ - - public function __construct($path, $sha) - { - $this->sha = $sha; - } - - public function sha() - { - return $this->sha; - } - -} diff --git a/3rdparty/granite/git/tree.php b/3rdparty/granite/git/tree.php deleted file mode 100644 index 2de72274532..00000000000 --- a/3rdparty/granite/git/tree.php +++ /dev/null @@ -1,198 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git; -use \Granite\Git\Tree\Node as Node; - -/** - * Tree represents a full tree object, with nodes pointing to other tree objects - * and file blobs - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Tree -{ - - /** - * The SHA-1 id of the requested tree - */ - private $sha; - /** - * The nodes/entries for the requested tree - */ - private $nodes = array(); - /** - * The path to the repository - */ - private $path; - - /** - * Reads a tree object by fetching the raw object - * - * @param string $path The path to the repository root - * @param string $sha The SHA-1 id of the requested object - */ - public function __construct($path, $sha = NULL, $dbg = FALSE) - { - $this->path = $path; - if ($sha !== NULL) { - $object = Object\Raw::factory($path, $sha); - $this->sha = $sha; - - if ($object->type() !== Object\Raw::OBJ_TREE) { - throw new \InvalidArgumentException( - "The object $sha is not a tree, type is " . $object->type() - ); - } - - $content = $object->content(); - file_put_contents('/tmp/tree_from_real_repo'.time(), $content); - $nodes = array(); - - for ($i = 0; $i < strlen($content); $i = $data_start + 21) { - $data_start = strpos($content, "\0", $i); - $info = substr($content, $i, $data_start-$i); - list($mode, $name) = explode(' ', $info, 2); - // Read the object SHA-1 id - $sha = bin2hex(substr($content, $data_start + 1, 20)); - - $this->nodes[$name] = new Node($name, $mode, $sha); - } - } - } - - /** - * Returns an array of Tree and Granite\Git\Blob objects, - * representing subdirectories and files - * - * @return array Array of Tree and Granite\Git\Blob objects - */ - public function nodes($nodes = null) - { - if ($nodes == null) { - return $this->nodes; - } - $this->nodes = $nodes; - } - - /** - * Adds a blob or a tree to the list of nodes - * - * @param string $name The basename (filename) of the blob or tree - * @param string $mode The mode of the blob or tree (see above) - * @param string $sha The SHA-1 id of the blob or tree to add - */ - public function add($name, $mode, $sha) - { - $this->nodes[$name] = new Node($name, $mode, $sha); - uasort($this->nodes, array($this, '_sort')); - } - - public function write() - { - $sha = $this->sha(); - $path = $this->path - . 'objects' - . DIRECTORY_SEPARATOR - . substr($sha, 0, 2) - . DIRECTORY_SEPARATOR - . substr($sha, 2); - // FIXME: currently writes loose objects only - if (file_exists($path)) { - return FALSE; - } - - if (!is_dir(dirname($path))) { - mkdir(dirname($path), 0777, TRUE); - } - - $loose = fopen($path, 'wb'); - $data = $this->_raw(); - $data = 'tree ' . strlen($data) . "\0" . $data; - $write = fwrite($loose, gzcompress($data)); - fclose($loose); - - return ($write !== FALSE); - } - - /** - * Returns the SHA-1 id of the Tree - * - * @return string SHA-1 id of the Tree - */ - public function sha() - { - $data = $this->_raw(); - $raw = 'tree ' . strlen($data) . "\0" . $data; - $this->sha = hash('sha1', $raw); - return $this->sha; - } - - /** - * Generates the raw object content to be saved to disk - */ - public function _raw() - { - uasort($this->nodes, array($this, '_sort')); - $data = ''; - foreach ($this->nodes as $node) - { - $data .= base_convert($node->mode(), 10, 8) . ' ' . $node->name() . "\0"; - $data .= pack('H40', $node->sha()); - } - file_put_contents('/tmp/tree_made'.time(), $data); - return $data; - } - - /** - * Sorts the node entries in a tree, general sort method adapted from original - * Git C code (see @see tag below). - * - * @return 1, 0 or -1 if the first entry is greater than, the same as, or less - * than the second, respectively. - * @see https://github.com/gitster/git/blob/master/read-cache.c Around line 352, - * the `base_name_compare` function - */ - public function _sort(&$a, &$b) - { - $length = strlen($a->name()) < strlen($b->name()) ? strlen($a->name()) : strlen($b->name()); - - $cmp = strncmp($a->name(), $b->name(), $length); - if ($cmp) { - return $cmp; - } - - $suffix1 = $a->name(); - $suffix1 = (strlen($suffix1) > $length) ? $suffix1{$length} : FALSE; - $suffix2 = $b->name(); - $suffix2 = (strlen($suffix2) > $length) ? $suffix2{$length} : FALSE; - if (!$suffix1 && $a->isDirectory()) { - $suffix1 = '/'; - } - if (!$suffix2 && $b->isDirectory()) { - $suffix2 = '/'; - } - if ($suffix1 < $suffix2) { - return -1; - } elseif ($suffix1 > $suffix2) { - return 1; - } - - return 0; - } - -} diff --git a/3rdparty/granite/git/tree/node.php b/3rdparty/granite/git/tree/node.php deleted file mode 100644 index f99eb1ae281..00000000000 --- a/3rdparty/granite/git/tree/node.php +++ /dev/null @@ -1,126 +0,0 @@ - - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ - -namespace Granite\Git\Tree; - -/** - * Node represents an entry in a Tree - * - * @category Git - * @package Granite - * @author Craig Roberts - * @license http://www.opensource.org/licenses/mit-license.php MIT Expat License - * @link http://craig0990.github.com/Granite/ - */ -class Node -{ - - /** - * Name of the file, directory or submodule - */ - private $_name; - /** - * Mode of the object, in octal - */ - private $_mode; - /** - * SHA-1 id of the tree - */ - private $_sha; - /** - * Boolean value for whether the entry represents a directory - */ - private $_is_dir; - /** - * Boolean value for whether the entry represents a submodule - */ - private $_is_submodule; - - /** - * Sets up a Node class with properties corresponding to the $mode parameter - * - * @param string $name The name of the object (file, directory or submodule name) - * @param int $mode The mode of the object, retrieved from the repository - * @param string $sha The SHA-1 id of the object - */ - public function __construct($name, $mode, $sha) - { - $this->_name = $name; - $this->_mode = intval($mode, 8); - $this->_sha = $sha; - - $this->_is_dir = (bool) ($this->_mode & 0x4000); - $this->_is_submodule = ($this->_mode == 0xE000); - } - - /** - * Returns a boolean value indicating whether the node is a directory - * - * @return boolean - */ - public function isDirectory() - { - return $this->_is_dir; - } - - /** - * Returns a boolean value indicating whether the node is a submodule - * - * @return boolean - */ - public function isSubmodule() - { - return $this->_is_submodule; - } - - /** - * Returns the object name - * - * @return string - */ - public function name() - { - return $this->_name; - } - - /** - * Returns the object's SHA-1 id - * - * @return string - */ - public function sha() - { - return $this->_sha; - } - - /** - * Returns the octal value of the file mode - * - * @return int - */ - public function mode() - { - return $this->_mode; - } - - public function type() - { - if ($this->isDirectory()) { - return 'tree'; - } elseif ($this->isSubmodule()) { - return 'commit'; - } else { - return 'blob'; - } - } -} -- GitLab From 29b9e27078ea2a1ca404a7b7b32de7e7afc52274 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 20:14:42 +0200 Subject: [PATCH 266/430] fix linkto function in OC_Helper --- lib/helper.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/helper.php b/lib/helper.php index 072a544a40a..e532d5391f9 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -41,11 +41,15 @@ class OC_Helper { $app .= '/'; // Check if the app is in the app folder if( file_exists( OC::$APPSROOT . '/apps/'. $app.$file )){ - if(substr($app, -1, 1) == '/'){ - $app = substr($app, 0, strlen($app) - 1); + if(substr($file, -3) == 'php'){ + if(substr($app, -1, 1) == '/'){ + $app = substr($app, 0, strlen($app) - 1); + } + $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; + $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):''; + }else{ + $urlLinkTo = OC::$APPSWEBROOT . '/' . $app . $file; } - $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; - $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):''; } else{ $urlLinkTo = OC::$WEBROOT . '/' . $app . $file; -- GitLab From 0b06eff3a016a274b5f5f01ec1ff225da7d7b639 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 20:17:00 +0200 Subject: [PATCH 267/430] another fix for linkto function --- lib/helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/helper.php b/lib/helper.php index e532d5391f9..2bc738e6650 100755 --- a/lib/helper.php +++ b/lib/helper.php @@ -48,7 +48,7 @@ class OC_Helper { $urlLinkTo = OC::$APPSWEBROOT . '/?app=' . $app; $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):''; }else{ - $urlLinkTo = OC::$APPSWEBROOT . '/' . $app . $file; + $urlLinkTo = OC::$APPSWEBROOT . '/apps/' . $app . $file; } } else{ -- GitLab From 684007bbaefe0bb415a1903e2807809623c4b250 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 21:33:34 +0200 Subject: [PATCH 268/430] fix pathes in contacts --- apps/contacts/css/contacts.css | 18 ++++--------- apps/contacts/js/contacts.js | 49 ++++++++++++++++++++++------------ core/js/js.js | 9 +++++++ core/templates/layout.user.php | 1 + 4 files changed, 47 insertions(+), 30 deletions(-) diff --git a/apps/contacts/css/contacts.css b/apps/contacts/css/contacts.css index 4c5242f607f..15f98cffbfb 100644 --- a/apps/contacts/css/contacts.css +++ b/apps/contacts/css/contacts.css @@ -11,7 +11,7 @@ #actionbar { height: 30px; width: 60px; position: fixed; right: 0px; top: 4em; margin: 0 0 0 0; padding: 0 0 0 0; z-index: 1000; } #contacts_deletecard {position:absolute;top:15px;right:25px;} #contacts_downloadcard {position:absolute;top:15px;right:50px;} -#contacts_propertymenu_button { position:absolute;top:15px;right:150px; background:url('core/img/actions/add.svg') no-repeat center; } +#contacts_propertymenu_button { position:absolute;top:15px;right:150px;} #contacts_propertymenu { background-color: #fff; position:absolute;top:40px;right:150px; overflow:hidden; text-overflow:ellipsis; /*border: thin solid #1d2d44;*/ -moz-box-shadow:0 0 10px #000; -webkit-box-shadow:0 0 10px #000; box-shadow:0 0 10px #000; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; } #contacts_propertymenu li { display: block; font-weight: bold; height: 20px; width: 100px; } #contacts_propertymenu li a { padding: 3px; display: block } @@ -34,20 +34,12 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } #address.form dt { min-width: 5em; } #address.form dl { min-width: 10em; } -.loading { background: url('core/img/loading.gif') no-repeat center !important; /*cursor: progress; */ cursor: wait; } -.ui-autocomplete-loading { background: url('core/img/loading.gif') right center no-repeat; } +.loading {/*cursor: progress; */ cursor: wait; } .float { float: left; } .listactions { height: 1em; width:60px; float: left; clear: right; } .add,.edit,.delete,.mail, .globe, .upload, .cloud { cursor: pointer; width: 20px; height: 20px; margin: 0; float: left; position:relative; opacity: 0.1; } .add:hover,.edit:hover,.delete:hover,.mail:hover, .globe:hover, .upload:hover, .cloud:hover { opacity: 1.0 } -.add { background:url('core/img/actions/add.svg') no-repeat center; clear: both; } -.delete { background:url('core/img/actions/delete.svg') no-repeat center; } -.edit { background:url('core/img/actions/rename.svg') no-repeat center; } -.mail { background:url('core/img/actions/mail.svg') no-repeat center; } -.upload { background:url('core/img/actions/upload.svg') no-repeat center; } -.cloud { background:url('core/img/places/picture.svg') no-repeat center; } -/*.globe { background:url('../img/globe.svg') no-repeat center; }*/ -.globe { background:url('core/img/actions/public.svg') no-repeat center; } + .transparent{ opacity: 0.6; } #edit_name_dialog { padding:0; } #edit_name_dialog > input { width: 15em; } @@ -59,11 +51,11 @@ dl.form { width: 100%; float: left; clear: right; margin: 0; padding: 0; } #identityprops { /*position: absolute; top: 2.5em; left: 0px;*/ } /*#contact_photo { max-width: 250px; }*/ #contact_identity { min-width: 30em; } -.contactsection { position: relative; float: left; /*max-width: 40em;*/ padding: 0.5em; height: auto: border: thin solid lightgray;/* -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; background-color: #f8f8f8;*/ } +.contactsection { position: relative; float: left; /*max-width: 40em;*/ padding: 0.5em; height: auto; border: thin solid lightgray;/* -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; background-color: #f8f8f8;*/ } .contactpart legend { width:auto; padding:.3em; border:1px solid #ddd; font-weight:bold; cursor:pointer; background:#f8f8f8; color:#555; text-shadow:#fff 0 1px 0; -moz-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -webkit-box-shadow:0 1px 1px #fff, 0 1px 1px #fff inset; -moz-border-radius:.5em; -webkit-border-radius:.5em; border-radius:.5em; } #cropbox { margin: auto; } -#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; background: url(core/img/loading.gif) no-repeat center center; display: block; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } +#contacts_details_photo { border-radius: 0.5em; border: thin solid #bbb; margin: 0.3em; display: block; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } #contacts_details_photo:hover { background: #fff; cursor: default; } #phototools { position:absolute; margin: 5px 0 0 10px; width:auto; height:22px; padding:0px; background-color:#fff; list-style-type:none; border-radius: 0.5em; -moz-box-shadow: 0 1px 3px #777; -webkit-box-shadow: 0 1px 3px #777; box-shadow: 0 1px 3px #777; } #phototools li { display: inline; } diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index f03ae1e46d6..f684576b787 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -289,12 +289,12 @@ Contacts={ if (jsondata.status == 'success'){ $('#rightcontent').data('id',jsondata.data.id); var id = jsondata.data.id; - $.getJSON('ajax/contactdetails.php',{'id':id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contactdetails.php'),{'id':id},function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.loadHandlers(); Contacts.UI.Card.loadContact(jsondata.data); $('#leftcontent .active').removeClass('active'); - var item = '
  • '+Contacts.UI.Card.fn+'
  • '; + var item = '
  • '+Contacts.UI.Card.fn+'
  • '; var added = false; $('#leftcontent ul li').each(function(){ if ($(this).text().toLowerCase() > Contacts.UI.Card.fn.toLowerCase()) { @@ -335,7 +335,7 @@ Contacts={ $('#contacts_deletecard').tipsy('hide'); OC.dialogs.confirm(t('contacts', 'Are you sure you want to delete this contact?'), t('contacts', 'Warning'), function(answer) { if(answer == true) { - $.getJSON('ajax/deletecard.php',{'id':Contacts.UI.Card.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'deletecard.php'),{'id':Contacts.UI.Card.id},function(jsondata){ if(jsondata.status == 'success'){ var newid = ''; var curlistitem = $('#leftcontent [data-id="'+jsondata.data.id+'"]'); @@ -357,7 +357,7 @@ Contacts={ Contacts.UI.Card.update(newid); } else { // load intro page - $.getJSON('ajax/loadintro.php',{},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'loadintro.php'),{},function(jsondata){ if(jsondata.status == 'success'){ id = ''; $('#rightcontent').data('id',''); @@ -616,7 +616,7 @@ Contacts={ q = q + '&checksum=' + checksum; console.log('Saving: ' + q); $(obj).attr('disabled', 'disabled'); - $.post('ajax/saveproperty.php',q,function(jsondata){ + $.post(OC.filePath('contacts', 'ajax', 'saveproperty.php'),q,function(jsondata){ if(jsondata.status == 'success'){ container.data('checksum', jsondata.data.checksum); Contacts.UI.Card.savePropertyInternal(name, fields, checksum, jsondata.data.checksum); @@ -634,7 +634,7 @@ Contacts={ } else { // add console.log('Adding: ' + q); $(obj).attr('disabled', 'disabled'); - $.post('ajax/addproperty.php',q,function(jsondata){ + $.post(OC.filePath('contacts', 'ajax', 'addproperty.php'),q,function(jsondata){ if(jsondata.status == 'success'){ container.data('checksum', jsondata.data.checksum); // TODO: savePropertyInternal doesn't know about new fields @@ -704,7 +704,7 @@ Contacts={ var checksum = Contacts.UI.checksumFor(obj); console.log('deleteProperty, id: ' + this.id + ', checksum: ' + checksum); if(checksum) { - $.getJSON('ajax/deleteproperty.php',{'id': this.id, 'checksum': checksum },function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'deleteproperty.php'),{'id': this.id, 'checksum': checksum },function(jsondata){ if(jsondata.status == 'success'){ if(type == 'list') { Contacts.UI.propertyContainerFor(obj).remove(); @@ -1124,7 +1124,7 @@ Contacts={ }, cloudPhotoSelected:function(path){ console.log('cloudPhotoSelected: ' + path); - $.getJSON('ajax/oc_photo.php',{'path':path,'id':Contacts.UI.Card.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'),{'path':path,'id':Contacts.UI.Card.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) @@ -1137,7 +1137,7 @@ Contacts={ }, loadPhoto:function(force){ //if(this.data.PHOTO||force==true) { - $.getJSON('ajax/loadphoto.php',{'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contact', 'ajax', 'loadphoto.php'),{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); $('#contacts_details_photo_wrapper').data('checksum', jsondata.data.checksum); @@ -1157,7 +1157,7 @@ Contacts={ }*/ }, editCurrentPhoto:function(){ - $.getJSON('ajax/currentphoto.php',{'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'currentphoto.php'),{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) @@ -1170,7 +1170,7 @@ Contacts={ }, editPhoto:function(id, tmp_path){ //alert('editPhoto: ' + tmp_path); - $.getJSON('ajax/cropphoto.php',{'tmp_path':tmp_path,'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'cropphoto.php'),{'tmp_path':tmp_path,'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); $('#edit_photo_dialog_img').html(jsondata.data.page); @@ -1378,7 +1378,7 @@ Contacts={ // Reload the contacts list. update:function(){ console.log('Contacts.update, start'); - $.getJSON('ajax/contacts.php',{},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contacts.php'),{},function(jsondata){ if(jsondata.status == 'success'){ $('#contacts').html(jsondata.data.page); Contacts.UI.Card.update(); @@ -1394,12 +1394,12 @@ Contacts={ lazyupdate:function(){ $('#contacts li').live('inview', function(){ if (!$(this).find('a').attr('style')) { - $(this).find('a').css('background','url(thumbnail.php?id='+$(this).data('id')+') no-repeat'); + $(this).find('a').css('background','url('+OC.filePath('contacts', '', 'thumbnail.php')+'?id='+$(this).data('id')+') no-repeat'); } }); }, refreshThumbnail:function(id){ - $('#contacts [data-id="'+id+'"]').find('a').css('background','url(thumbnail.php?id='+id+'&refresh=1'+Math.random()+') no-repeat'); + $('#contacts [data-id="'+id+'"]').find('a').css('background','url('+OC.filePath('contacts', '', 'thumbnail.php')+'?id='+id+'&refresh=1'+Math.random()+') no-repeat'); } } } @@ -1431,7 +1431,7 @@ $(document).ready(function(){ if(oldid != 0){ $('#leftcontent li[data-id="'+oldid+'"]').removeClass('active'); } - $.getJSON('ajax/contactdetails.php',{'id':id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contactsdetails.php'),{'id':id},function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.Card.loadContact(jsondata.data); } @@ -1454,7 +1454,7 @@ $(document).ready(function(){ // whole part of element is visible if (!$(this).find('a').attr('style')) { //alert($(this).data('id') + ' has background: ' + $(this).attr('style')); - $(this).find('a').css('background','url(thumbnail.php?id='+$(this).data('id')+') no-repeat'); + $(this).find('a').css('background','url('+OC.filePath('contacts', '', 'thumbnail.php')+'?id='+$(this).data('id')+') no-repeat'); }/* else { alert($(this).data('id') + ' has style ' + $(this).attr('style').match('url')); }*/ @@ -1574,7 +1574,7 @@ $(document).ready(function(){ }; // Start loading indicator. //$('#contacts_details_photo_progress').show()(); - xhr.open("POST", 'ajax/uploadphoto.php?id='+Contacts.UI.Card.id+'&imagefile='+encodeURIComponent(file.name), true); + xhr.open("POST", OC.filePath('contacts', 'ajax', 'uploadphoto.php')+'?id='+Contacts.UI.Card.id+'&imagefile='+encodeURIComponent(file.name), true); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('X_FILE_NAME', encodeURIComponent(file.name)); @@ -1604,3 +1604,18 @@ $(document).ready(function(){ $('#contacts_propertymenu').hide(); }); }); +$(document).ready(function() { + $('.add').css('background', 'url('+OC.filePath('core', 'img/actions', 'add.svg')+') no-repeat center'); + $('.delete').css('background', 'url('+OC.filePath('core', 'img/actions', 'delete.svg')+') no-repeat center'); + $('.edit').css('background', 'url('+OC.filePath('core', 'img/actions', 'rename.svg')+') no-repeat center'); + $('.mail').css('background', 'url('+OC.filePath('core', 'img/actions', 'mail.svg')+') no-repeat center'); + $('.upload').css('background', 'url('+OC.filePath('core', 'img/actions', 'upload.svg')+') no-repeat center'); + $('.cloud').css('background', 'url('+OC.filePath('core', 'img/actions', 'picture.svg')+') no-repeat center'); + /*$('.globe').css('background', 'url('+OC.filePath('core', 'img/actions', 'globe.svg')+') no-repeat center');*/ + $('.globe').css('background', 'url('+OC.filePath('core', 'img/actions', 'public.svg')+') no-repeat center'); + $('#contacts_propertymenu_button').css('background', 'url('+OC.filePath('core', 'img/actions', 'add.svg')+' no-repeat center'); + $('.loading').css('background', 'url('+OC.filePath('core', 'img', 'loading.gif')+' no-repeat center !important'); + $('.ui-autocomplete-loading').css('background', 'url('+OC.filePath('core', 'img', 'loading.gif')+' right center no-repeat'); + $('#contacts_details_photo').css('background', 'url('+OC.filePath('core', 'img', 'loading.gif')+' no-repeat center center'); + $('#contacts_propertymenu_button').css('background', 'url('+OC.filePath('core', 'img/actions', 'add.svg')+') no-repeat center'); +}); \ No newline at end of file diff --git a/core/js/js.js b/core/js/js.js index b4482185509..25de7c13b74 100644 --- a/core/js/js.js +++ b/core/js/js.js @@ -31,6 +31,7 @@ t.cache={}; OC={ webroot:oc_webroot, + appswebroot:oc_appswebroot, currentUser:(typeof oc_current_user!=='undefined')?oc_current_user:false, coreApps:['admin','log','search','settings','core','3rdparty'], /** @@ -54,6 +55,14 @@ OC={ var link=OC.webroot; if(file.substring(file.length-3) == 'php' && !isCore){ link+='/?app=' + app + '&getfile=' + encodeURI(type + '/' + file); + }else if(file.substring(file.length-3) != 'php' && !isCore){ + link=OC.appswebroot; + link+='apps/'; + link+=app; + if(type){ + link+=type+'/'; + } + link+=file; }else{ link+='/'; app+='/'; diff --git a/core/templates/layout.user.php b/core/templates/layout.user.php index 61eb0de9f42..a5431ab6ab3 100644 --- a/core/templates/layout.user.php +++ b/core/templates/layout.user.php @@ -9,6 +9,7 @@ -- GitLab From 9b29bc96de688f1d3289444625ce5bb7e7d37ac5 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 21:36:54 +0200 Subject: [PATCH 269/430] remove debug message --- lib/base.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/base.php b/lib/base.php index f8f9362a64a..231819b36ab 100644 --- a/lib/base.php +++ b/lib/base.php @@ -287,7 +287,7 @@ class OC{ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); }else{ - echo "WTF"; + header('404 Not Found') } } -- GitLab From fb84d0aff803c77e65d2faa49f320c6e12639593 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 21:37:19 +0200 Subject: [PATCH 270/430] fix php fail --- lib/base.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/base.php b/lib/base.php index 231819b36ab..a7b7d082460 100644 --- a/lib/base.php +++ b/lib/base.php @@ -287,7 +287,7 @@ class OC{ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); }else{ - header('404 Not Found') + header('404 Not Found'); } } -- GitLab From a85d49833b1aa4d616271cf0f168b5a4294d9810 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 21:52:44 +0200 Subject: [PATCH 271/430] fix position of Semicolon --- core/templates/layout.user.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/templates/layout.user.php b/core/templates/layout.user.php index a5431ab6ab3..df7897717f6 100644 --- a/core/templates/layout.user.php +++ b/core/templates/layout.user.php @@ -9,7 +9,7 @@ -- GitLab From d6346b5b0bece4feecc36b7b97308dd3a5a4d6cc Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Tue, 24 Apr 2012 21:54:09 +0200 Subject: [PATCH 272/430] fix OC.filePath in main js --- core/js/js.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/core/js/js.js b/core/js/js.js index 25de7c13b74..a4369deb283 100644 --- a/core/js/js.js +++ b/core/js/js.js @@ -54,15 +54,20 @@ OC={ var isCore=OC.coreApps.indexOf(app)!=-1; var link=OC.webroot; if(file.substring(file.length-3) == 'php' && !isCore){ - link+='/?app=' + app + '&getfile=' + encodeURI(type + '/' + file); + link+='/?app=' + app + '&getfile='; + if(type){ + link+=encodeURI(type + '/'); + } + link+= file; }else if(file.substring(file.length-3) != 'php' && !isCore){ link=OC.appswebroot; + link+='/'; link+='apps/'; - link+=app; + link+=app+'/'; if(type){ link+=type+'/'; } - link+=file; + link+=file; }else{ link+='/'; app+='/'; -- GitLab From fa502e160df470ffa2ab02d6a8e9e8a0d4f6f0f4 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Tue, 24 Apr 2012 23:56:51 +0200 Subject: [PATCH 273/430] allow manually scanning of specific directories --- files/ajax/scan.php | 3 ++- files/js/files.js | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/files/ajax/scan.php b/files/ajax/scan.php index db09b7d5c64..c60e34b5176 100644 --- a/files/ajax/scan.php +++ b/files/ajax/scan.php @@ -5,6 +5,7 @@ require_once '../../lib/base.php'; set_time_limit(0);//scanning can take ages $force=isset($_GET['force']) and $_GET['force']=='true'; +$dir=isset($_GET['dir'])?$_GET['dir']:''; $checkOnly=isset($_GET['checkonly']) and $_GET['checkonly']=='true'; if(!$checkOnly){ @@ -16,7 +17,7 @@ if(!$checkOnly){ if($force or !OC_FileCache::inCache('')){ if(!$checkOnly){ OC_DB::beginTransaction(); - OC_FileCache::scan('',$eventSource); + OC_FileCache::scan($dir,$eventSource); OC_FileCache::clean(); OC_DB::commit(); $eventSource->send('success',true); diff --git a/files/js/files.js b/files/js/files.js index 3ce95f992d0..73a16100a69 100644 --- a/files/js/files.js +++ b/files/js/files.js @@ -370,12 +370,12 @@ $(document).ready(function() { }, "json"); }); -function scanFiles(force){ +function scanFiles(force,dir){ force=!!force; //cast to bool scanFiles.scanning=true; $('#scanning-message').show(); $('#fileList').remove(); - var scannerEventSource=new OC.EventSource(OC.filePath('files','ajax','scan.php'),{force:force}); + var scannerEventSource=new OC.EventSource(OC.filePath('files','ajax','scan.php'),{force:force,dir:dir}); scanFiles.cancel=scannerEventSource.close.bind(scannerEventSource); scannerEventSource.listen('scanning',function(data){ $('#scan-count').text(data.count+' files scanned'); -- GitLab From 60b924c954ac880f5d17ce91f733850c5b010e0f Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 25 Apr 2012 00:08:45 +0200 Subject: [PATCH 274/430] initial mount configuration work --- lib/filesystem.php | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/lib/filesystem.php b/lib/filesystem.php index dc678fba74c..1b91eabc7c1 100644 --- a/lib/filesystem.php +++ b/lib/filesystem.php @@ -196,9 +196,57 @@ class OC_Filesystem{ return false; } self::$defaultInstance=new OC_FilesystemView($root); + + //load custom mount config + if(is_file(OC::$SERVERROOT.'/config/mount.php')){ + $mountConfig=include(OC::$SERVERROOT.'/config/mount.php'); + if(isset($mountConfig['global'])){ + foreach($mountConfig['global'] as $mountPoint=>$options){ + self::mount($options['class'],$options['options'],$mountPoint); + } + } + + if(isset($mountConfig['group'])){ + foreach($mountConfig['group'] as $group=>$mounts){ + if(OC_Group::inGroup(OC_User::getUser(),$group)){ + foreach($mounts as $mountPoint=>$options){ + $mountPoint=self::setUserVars($mountPoint); + foreach($options as &$option){ + $option=self::setUserVars($option); + } + self::mount($options['class'],$options['options'],$mountPoint); + } + } + } + } + + if(isset($mountConfig['user'])){ + foreach($mountConfig['user'] as $user=>$mounts){ + if($user==='all' or strtolower($user)===strtolower(OC_User::getUser())){ + foreach($mounts as $mountPoint=>$options){ + $mountPoint=self::setUserVars($mountPoint); + foreach($options as &$option){ + $option=self::setUserVars($option); + } + self::mount($options['class'],$options['options'],$mountPoint); + } + } + } + } + } + self::$loaded=true; } + /** + * fill in the correct values for $user, and $password placeholders + * @param string intput + * @return string + */ + private static function setUserVars($input){ + return str_replace('$user',OC_User::getUser(),$input); + } + /** * get the default filesystem view * @return OC_FilesystemView -- GitLab From 9015c46e317842184b414bce9192b62b969a5202 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 25 Apr 2012 00:09:14 +0200 Subject: [PATCH 275/430] emit the correct hooks for file_put_contents and some readfile improvements --- lib/filesystemview.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/filesystemview.php b/lib/filesystemview.php index 95873bd87cf..ac5a0a3bff5 100644 --- a/lib/filesystemview.php +++ b/lib/filesystemview.php @@ -136,15 +136,16 @@ class OC_FilesystemView { return $this->basicOperation('filesize',$path); } public function readfile($path){ + @ob_end_clean(); $handle=$this->fopen($path,'r'); if ($handle) { - $chunkSize = 1024*1024;// 1 MB chunks + $chunkSize = 8*1024;// 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); - @ob_flush(); flush(); } - return $this->filesize($path); + $size=$this->filesize($path); + return $size; } return false; } @@ -174,11 +175,23 @@ class OC_FilesystemView { } public function file_put_contents($path,$data){ if(is_resource($data)){//not having to deal with streams in file_put_contents makes life easier + $exists=$this->file_exists($path); + $run=true; + if(!$exists){ + OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_create, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); + } + OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); + if(!$run){ + return false; + } $target=$this->fopen($path,'w'); if($target){ $count=OC_Helper::streamCopy($data,$target); fclose($target); fclose($data); + if(!$exists){ + OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_create, array( OC_Filesystem::signal_param_path => $path)); + } OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array( OC_Filesystem::signal_param_path => $path)); return $count>0; }else{ -- GitLab From cc2bfd313dd8f3210e136f99606ec01a3168fe2f Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 25 Apr 2012 00:10:02 +0200 Subject: [PATCH 276/430] minor filecache improvements --- lib/filecache.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/filecache.php b/lib/filecache.php index 19286ff746b..28a9eb247a6 100644 --- a/lib/filecache.php +++ b/lib/filecache.php @@ -64,7 +64,7 @@ class OC_FileCache{ if(is_array($result)){ return $result; }else{ - OC_Log::write('get(): file not found in cache ('.$path.')','core',OC_Log::DEBUG); + OC_Log::write('files','get(): file not found in cache ('.$path.')',OC_Log::DEBUG); return false; } } @@ -257,7 +257,7 @@ class OC_FileCache{ if(is_array($result)){ return $result; }else{ - OC_Log::write('getFolderContent(): file not found in cache ('.$path.')','core',OC_Log::DEBUG); + OC_Log::write('files','getFolderContent(): file not found in cache ('.$path.')',OC_Log::DEBUG); return false; } } @@ -300,7 +300,7 @@ class OC_FileCache{ if(is_array($result)){ return $result['id']; }else{ - OC_Log::write('getFileId(): file not found in cache ('.$path.')','core',OC_Log::DEBUG); + OC_Log::write('files','getFileId(): file not found in cache ('.$path.')',OC_Log::DEBUG); return -1; } } @@ -414,8 +414,12 @@ class OC_FileCache{ } return $result; }else{ - OC_Log::write('get(): file not found in cache ('.$path.')','core',OC_Log::DEBUG); - return false; + OC_Log::write('files','getChached(): file not found in cache ('.$path.')',OC_Log::DEBUG); + if(isset(self::$savedData[$path])){ + return self::$savedData[$path]; + }else{ + return array(); + } } } @@ -553,6 +557,7 @@ class OC_FileCache{ $view=new OC_FilesystemView(($root=='/')?'':$root); } if(!$view->is_readable($path)) return; //cant read, nothing we can do + clearstatcache(); $stat=$view->stat($path); $mimetype=$view->getMimeType($path); $writable=$view->is_writable($path); -- GitLab From 5c3ea148197c20b9754a539261d4b0fa1540a3c7 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 25 Apr 2012 00:10:29 +0200 Subject: [PATCH 277/430] fix mimetypes of encrypted files --- apps/files_encryption/lib/cryptstream.php | 15 ++++----------- apps/files_encryption/lib/proxy.php | 17 +++-------------- 2 files changed, 7 insertions(+), 25 deletions(-) diff --git a/apps/files_encryption/lib/cryptstream.php b/apps/files_encryption/lib/cryptstream.php index 21fa38e4b59..07a2e523a42 100644 --- a/apps/files_encryption/lib/cryptstream.php +++ b/apps/files_encryption/lib/cryptstream.php @@ -33,6 +33,7 @@ class OC_CryptStream{ private $path; private $readBuffer;//for streams that dont support seeking private $meta=array();//header/meta for source stream + private $count; public function stream_open($path, $mode, $options, &$opened_path){ $path=str_replace('crypt://','',$path); @@ -92,16 +93,6 @@ class OC_CryptStream{ $data=substr($block,0,$currentPos%8192).$data; } while(strlen($data)>0){ - if(strlen($data)<8192){ - //fetch the current data in that block and append it to the input so we always write entire blocks - $oldPos=ftell($this->source); - $encryptedBlock=fread($this->source,8192); - fseek($this->source,$oldPos); - if($encryptedBlock){ - $block=OC_Crypt::decrypt($encryptedBlock); - $data.=substr($block,strlen($data)); - } - } $encrypted=OC_Crypt::encrypt(substr($data,0,8192)); fwrite($this->source,$encrypted); $data=substr($data,8192); @@ -139,7 +130,9 @@ class OC_CryptStream{ } public function stream_close(){ - OC_FileCache::put($this->path,array('encrypted'=>true)); + if($this->meta['mode']!='r' and $this->meta['mode']!='rb'){ + OC_FileCache::put($this->path,array('encrypted'=>true)); + } return fclose($this->source); } } \ No newline at end of file diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index e3a106d0d04..d65bcba8bfa 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -27,7 +27,6 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ private static $blackList=null; //mimetypes blacklisted from encryption - private static $metaData=array(); //metadata cache private static $enableEncryption=null; /** @@ -60,13 +59,8 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ * @return bool */ private static function isEncrypted($path){ - if(isset(self::$metaData[$path])){ - $metadata=self::$metaData[$path]; - }else{ - $metadata=OC_FileCache::getCached($path); - self::$metaData[$path]=$metadata; - } - return (bool)$metadata['encrypted']; + $metadata=OC_FileCache::getCached($path); + return isset($metadata['encrypted']) and (bool)$metadata['encrypted']; } public function preFile_put_contents($path,&$data){ @@ -98,12 +92,7 @@ class OC_FileProxy_Encryption extends OC_FileProxy{ //first encrypt the target file so we don't end up with a half encrypted file OC_Log::write('files_encryption','Decrypting '.$path.' before writing',OC_Log::DEBUG); $tmp=fopen('php://temp'); - while(!feof($result)){ - $chunk=fread($result,8192); - if($chunk){ - fwrite($tmp,$chunk); - } - } + OC_Helper::streamCopy($result,$tmp); fclose($result); OC_Filesystem::file_put_contents($path,$tmp); fclose($tmp); -- GitLab From 5b70e2fb25a3228d46eb7ceaa497b957f8755d1e Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 25 Apr 2012 00:11:10 +0200 Subject: [PATCH 278/430] some performance improvements to the openstack swift backend --- apps/files_external/lib/swift.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/files_external/lib/swift.php b/apps/files_external/lib/swift.php index e53eb1ff3b6..a987d17d799 100644 --- a/apps/files_external/lib/swift.php +++ b/apps/files_external/lib/swift.php @@ -28,6 +28,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ private $rootContainer; private static $tempFiles=array(); + private $objects=array(); + private $containers=array(); const SUBCONTAINER_FILE='.subcontainers'; @@ -38,7 +40,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ */ private function getContainerName($path){ $path=trim($this->root.$path,'/'); - return md5($path); + return str_replace('/','\\',$path); } /** @@ -50,8 +52,12 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ if($path=='' or $path=='/'){ return $this->rootContainer; } + if(isset($this->containers[$path])){ + return $this->containers[$path]; + } try{ $container=$this->conn->get_container($this->getContainerName($path)); + $this->containers[$path]=$container; return $container; }catch(NoSuchContainerException $e){ return null; @@ -87,12 +93,16 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ * @return CF_Object */ private function getObject($path){ + if(isset($this->objects[$path])){ + return $this->objects[$path]; + } $container=$this->getContainer(dirname($path)); if(is_null($container)){ return null; }else{ try{ $obj=$container->get_object(basename($path)); + $this->objects[$path]=$obj; return $obj; }catch(NoSuchObjectException $e){ return null; @@ -295,6 +305,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ } $this->conn->delete_container($this->getContainerName($path)); + unset($this->containers[$path]); return true; } } @@ -309,12 +320,14 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ if($sub){ $this->emptyContainer($path.'/'.$sub); $this->conn->delete_container($this->getContainerName($path.'/'.$sub)); + unset($this->containers[$path.'/'.$sub]); } } $objects=$this->getObjects($container); foreach($objects as $object){ $container->delete_object($object); + unset($this->objects[$path.'/'.$object]); } } @@ -381,6 +394,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ if($this->objectExists($path)){ $container=$this->getContainer(dirname($path)); $container->delete_object(basename($path)); + unset($this->objects[$path]); }else{ return false; } @@ -447,6 +461,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{ $sourceContainer=$this->getContainer(dirname($path1)); $targetContainer=$this->getContainer(dirname($path2)); $result=$sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2)); + unset($this->objects[$path1]); if($result){ $targetObj=$this->getObject($path2); $this->resetMTime($targetObj); -- GitLab From 9ee2bb97197f1f5387260f25cb7b2e276324a005 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 25 Apr 2012 09:22:19 +0200 Subject: [PATCH 279/430] fix js fail in media player --- apps/media/js/collection.js | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/media/js/collection.js b/apps/media/js/collection.js index c345d4d9944..0b5a9ef9a47 100644 --- a/apps/media/js/collection.js +++ b/apps/media/js/collection.js @@ -112,6 +112,7 @@ Collection={ Collection.parent.find('tr').removeClass('active'); $('tr[data-artist="'+artist.name+'"]').addClass('active'); }); + expander=''; if(artist.songs.length>1){ expander=$('>'); expander.data('expanded',false); -- GitLab From 476043ecb97ebf4f1a56985194c2b74b9473e276 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 25 Apr 2012 10:17:20 +0200 Subject: [PATCH 280/430] add a proper 404 --- lib/base.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/base.php b/lib/base.php index a7b7d082460..c8a99d3ac30 100644 --- a/lib/base.php +++ b/lib/base.php @@ -287,7 +287,8 @@ class OC{ if(file_exists(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE)){ require_once(OC::$APPSROOT . '/apps/' . OC::$REQUESTEDAPP . '/' . OC::$REQUESTEDFILE); }else{ - header('404 Not Found'); + header('HTTP/1.0 404 Not Found'); + exit; } } -- GitLab From 323b19a4a090b10ea55f0152180da5e6c7290776 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 25 Apr 2012 10:17:54 +0200 Subject: [PATCH 281/430] some fixes in contacts javascript files --- apps/contacts/js/contacts.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index b94bf77c5ec..d93d337e469 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -1137,7 +1137,7 @@ Contacts={ }, loadPhoto:function(force){ //if(this.data.PHOTO||force==true) { - $.getJSON(OC.filePath('contact', 'ajax', 'loadphoto.php'),{'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'loadphoto.php'),{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); $('#contacts_details_photo_wrapper').data('checksum', jsondata.data.checksum); @@ -1519,7 +1519,7 @@ $(document).ready(function(){ if(oldid != 0){ $('#leftcontent li[data-id="'+oldid+'"]').removeClass('active'); } - $.getJSON(OC.filePath('contacts', 'ajax', 'contactsdetails.php'),{'id':id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contactdetails.php'),{'id':id},function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.Card.loadContact(jsondata.data); } -- GitLab From 03f81fdd884f646f1cd9e8155de764fb2c89dce6 Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Wed, 25 Apr 2012 09:22:19 +0200 Subject: [PATCH 282/430] fix js fail in media player --- apps/media/js/collection.js | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/media/js/collection.js b/apps/media/js/collection.js index c345d4d9944..0b5a9ef9a47 100644 --- a/apps/media/js/collection.js +++ b/apps/media/js/collection.js @@ -112,6 +112,7 @@ Collection={ Collection.parent.find('tr').removeClass('active'); $('tr[data-artist="'+artist.name+'"]').addClass('active'); }); + expander=''; if(artist.songs.length>1){ expander=$('>'); expander.data('expanded',false); -- GitLab From 4795295fb16c61ff9f9c04f9570d963908d0b232 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 25 Apr 2012 10:42:54 +0200 Subject: [PATCH 283/430] Contacts: Fixed some file paths. --- apps/contacts/js/contacts.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/apps/contacts/js/contacts.js b/apps/contacts/js/contacts.js index e00e9257e65..8f2e7a0d23c 100644 --- a/apps/contacts/js/contacts.js +++ b/apps/contacts/js/contacts.js @@ -289,7 +289,7 @@ Contacts={ if (jsondata.status == 'success'){ $('#rightcontent').data('id',jsondata.data.id); var id = jsondata.data.id; - $.getJSON('ajax/contactdetails.php',{'id':id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contactdetails.php'),{'id':id},function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.loadHandlers(); Contacts.UI.Card.loadContact(jsondata.data); @@ -335,7 +335,7 @@ Contacts={ $('#contacts_deletecard').tipsy('hide'); OC.dialogs.confirm(t('contacts', 'Are you sure you want to delete this contact?'), t('contacts', 'Warning'), function(answer) { if(answer == true) { - $.getJSON('ajax/deletecard.php',{'id':Contacts.UI.Card.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'deletecard.php'),{'id':Contacts.UI.Card.id},function(jsondata){ if(jsondata.status == 'success'){ var newid = ''; var curlistitem = $('#leftcontent [data-id="'+jsondata.data.id+'"]'); @@ -357,7 +357,7 @@ Contacts={ Contacts.UI.Card.update(newid); } else { // load intro page - $.getJSON('ajax/loadintro.php',{},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'loadintro.php'),{},function(jsondata){ if(jsondata.status == 'success'){ id = ''; $('#rightcontent').data('id',''); @@ -616,7 +616,7 @@ Contacts={ q = q + '&checksum=' + checksum; console.log('Saving: ' + q); $(obj).attr('disabled', 'disabled'); - $.post('ajax/saveproperty.php',q,function(jsondata){ + $.post(OC.filePath('contacts', 'ajax', 'saveproperty.php'),q,function(jsondata){ if(jsondata.status == 'success'){ container.data('checksum', jsondata.data.checksum); Contacts.UI.Card.savePropertyInternal(name, fields, checksum, jsondata.data.checksum); @@ -634,7 +634,7 @@ Contacts={ } else { // add console.log('Adding: ' + q); $(obj).attr('disabled', 'disabled'); - $.post('ajax/addproperty.php',q,function(jsondata){ + $.post(OC.filePath('contacts', 'ajax', 'addproperty.php'),q,function(jsondata){ if(jsondata.status == 'success'){ container.data('checksum', jsondata.data.checksum); // TODO: savePropertyInternal doesn't know about new fields @@ -704,7 +704,7 @@ Contacts={ var checksum = Contacts.UI.checksumFor(obj); console.log('deleteProperty, id: ' + this.id + ', checksum: ' + checksum); if(checksum) { - $.getJSON('ajax/deleteproperty.php',{'id': this.id, 'checksum': checksum },function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'deleteproperty.php'),{'id': this.id, 'checksum': checksum },function(jsondata){ if(jsondata.status == 'success'){ if(type == 'list') { Contacts.UI.propertyContainerFor(obj).remove(); @@ -1124,7 +1124,7 @@ Contacts={ }, cloudPhotoSelected:function(path){ console.log('cloudPhotoSelected: ' + path); - $.getJSON('ajax/oc_photo.php',{'path':path,'id':Contacts.UI.Card.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'),{'path':path,'id':Contacts.UI.Card.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) @@ -1137,7 +1137,7 @@ Contacts={ }, loadPhoto:function(force){ //if(this.data.PHOTO||force==true) { - $.getJSON('ajax/loadphoto.php',{'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'loadphoto.php'),{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); $('#contacts_details_photo_wrapper').data('checksum', jsondata.data.checksum); @@ -1157,7 +1157,7 @@ Contacts={ }*/ }, editCurrentPhoto:function(){ - $.getJSON('ajax/currentphoto.php',{'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'currentphoto.php'),{'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp) @@ -1170,7 +1170,7 @@ Contacts={ }, editPhoto:function(id, tmp_path){ //alert('editPhoto: ' + tmp_path); - $.getJSON('ajax/cropphoto.php',{'tmp_path':tmp_path,'id':this.id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'cropphoto.php'),{'tmp_path':tmp_path,'id':this.id},function(jsondata){ if(jsondata.status == 'success'){ //alert(jsondata.data.page); $('#edit_photo_dialog_img').html(jsondata.data.page); @@ -1405,7 +1405,7 @@ Contacts={ } } }; - xhr.open("POST", 'ajax/uploadimport.php?file='+encodeURIComponent(file.name), true); + xhr.open('POST', OC.filePath('contacts', 'ajax', 'uploadimport.php') + '?file='+encodeURIComponent(file.name), true); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('X_FILE_NAME', encodeURIComponent(file.name)); @@ -1467,7 +1467,7 @@ Contacts={ // Reload the contacts list. update:function(){ console.log('Contacts.update, start'); - $.getJSON('ajax/contacts.php',{},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contacts.php'),{},function(jsondata){ if(jsondata.status == 'success'){ $('#contacts').html(jsondata.data.page); Contacts.UI.Card.update(); @@ -1519,7 +1519,7 @@ $(document).ready(function(){ if(oldid != 0){ $('#leftcontent li[data-id="'+oldid+'"]').removeClass('active'); } - $.getJSON('ajax/contactdetails.php',{'id':id},function(jsondata){ + $.getJSON(OC.filePath('contacts', 'ajax', 'contactdetails.php'),{'id':id},function(jsondata){ if(jsondata.status == 'success'){ Contacts.UI.Card.loadContact(jsondata.data); } @@ -1662,7 +1662,7 @@ $(document).ready(function(){ }; // Start loading indicator. //$('#contacts_details_photo_progress').show()(); - xhr.open("POST", 'ajax/uploadphoto.php?id='+Contacts.UI.Card.id+'&imagefile='+encodeURIComponent(file.name), true); + xhr.open('POST', OC.filePath('contacts', 'ajax', 'uploadphoto.php')+'?id='+Contacts.UI.Card.id+'&imagefile='+encodeURIComponent(file.name), true); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('X_FILE_NAME', encodeURIComponent(file.name)); -- GitLab From 81f549baee2078b3d5ba037e921864337edc0ea2 Mon Sep 17 00:00:00 2001 From: Sam Tuke Date: Wed, 25 Apr 2012 13:51:08 +0100 Subject: [PATCH 284/430] made code a little more readable --- apps/files_versions/history.php | 38 ++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/apps/files_versions/history.php b/apps/files_versions/history.php index 6c7626ca4ed..7f03ce0e694 100644 --- a/apps/files_versions/history.php +++ b/apps/files_versions/history.php @@ -20,40 +20,40 @@ * License along with this library. If not, see . * */ -require_once('../../lib/base.php'); +require_once( '../../lib/base.php' ); -OC_Util::checkLoggedIn(); +OC_Util::checkLoggedIn( ); -if (isset($_GET['path'])) { +if ( isset( $_GET['path'] ) ) { $path = $_GET['path']; - $path = strip_tags($path); + $path = strip_tags( $path); // roll back to old version if button clicked - if(isset($_GET['revert'])) { - \OCA_Versions\Storage::rollback($path,$_GET['revert']); + if( isset( $_GET['revert'] ) ) { + \OCA_Versions\Storage::rollback( $path, $_GET['revert'] ); } // show the history only if there is something to show - if(OCA_Versions\Storage::isversioned($path)) { + if( OCA_Versions\Storage::isversioned( $path) ) { $count=5; //show the newest revisions - $versions=OCA_Versions\Storage::getversions($path,$count); + $versions=OCA_Versions\Storage::getversions( $path, $count); - $tmpl = new OC_Template('files_versions', 'history', 'user'); - $tmpl->assign('path', $path); - $tmpl->assign('versions', array_reverse($versions)); - $tmpl->printPage(); + $tmpl = new OC_Template( 'files_versions', 'history', 'user' ); + $tmpl->assign( 'path', $path); + $tmpl->assign( 'versions', array_reverse( $versions) ); + $tmpl->printPage( ); }else{ - $tmpl = new OC_Template('files_versions', 'history', 'user'); - $tmpl->assign('path', $path); - $tmpl->assign('message', 'No old versions available'); - $tmpl->printPage(); + $tmpl = new OC_Template( 'files_versions', 'history', 'user' ); + $tmpl->assign( 'path', $path); + $tmpl->assign( 'message', 'No old versions available' ); + $tmpl->printPage( ); } }else{ - $tmpl = new OC_Template('files_versions', 'history', 'user'); - $tmpl->assign('message', 'No path specified'); - $tmpl->printPage(); + $tmpl = new OC_Template( 'files_versions', 'history', 'user' ); + $tmpl->assign( 'message', 'No path specified' ); + $tmpl->printPage( ); } -- GitLab From 8ae1430090ac19915f71f27b9a77cdc44ccfefc0 Mon Sep 17 00:00:00 2001 From: Sam Tuke Date: Wed, 25 Apr 2012 13:56:43 +0100 Subject: [PATCH 285/430] added script and loaded it for adding history button --- apps/files_versions/appinfo/app.php | 1 + apps/files_versions/js/versions.js | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/files_versions/appinfo/app.php b/apps/files_versions/appinfo/app.php index 6e7a803252e..32e4c0ce81b 100644 --- a/apps/files_versions/appinfo/app.php +++ b/apps/files_versions/appinfo/app.php @@ -9,6 +9,7 @@ OC_App::register( array( 'name' => 'Versioning' )); OC_APP::registerAdmin('files_versions', 'settings'); +OC_UTIL::addScript('files_versions', 'versions'); // Listen to write signals OC_Hook::connect(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, "OCA_Versions\Storage", "write_hook"); diff --git a/apps/files_versions/js/versions.js b/apps/files_versions/js/versions.js index 139597f9cb0..ac8b87513f2 100644 --- a/apps/files_versions/js/versions.js +++ b/apps/files_versions/js/versions.js @@ -1,2 +1,9 @@ - +$(document).ready(function(){ + + // Add history button to files/index.php + FileActions.register('file','History',function(){return OC.imagePath('core','actions/history')},function(filename){ + window.location='../apps/files_versioning/history.php?file='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename); + }); + +}); -- GitLab From 02a65f30ec2f0f1f3618f469287ee51eaef38a84 Mon Sep 17 00:00:00 2001 From: Sam Tuke Date: Wed, 25 Apr 2012 14:01:03 +0100 Subject: [PATCH 286/430] added history buttons --- core/img/actions/history.png | Bin 0 -> 370 bytes core/img/actions/history.svg | 240 +++++++++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+) create mode 100644 core/img/actions/history.png create mode 100644 core/img/actions/history.svg diff --git a/core/img/actions/history.png b/core/img/actions/history.png new file mode 100644 index 0000000000000000000000000000000000000000..b1e743651f827e9fa0b34dfdc0c7537f612b36d1 GIT binary patch literal 370 zcmeAS@N?(olHy`uVBq!ia0vp^{2(?58;~rMGjRk`EX7WqAsj$Z!;#Vf2?p zTm@l9+iMXYfr64Ht`Q}{`DrEPiAAXl<>lpinR(g8$%zH2dih1^v)|cB0TsRXba4#P zm{@zsQ2S`2$nlT;0cPDtQw%juolV*z*}I+RME8W=a0SVY5>I?3mU>7^sBCU|%QyYs z3&T7A_s^@gxgMNeaqj(hTifTB?p~feXA=3Rzjz>aJmSS?(F43C6S+RN#`64c+-S+r zwed20vdntc$F_A&>kifM<+C5QjM{3}x_N>8vk#eSH3>>vOd`MEsmMzZ)4h{=$T-bF zmMbP@9^aOau`jkdSu?wTob>W~?*=KZnj}@`;{_sJ@=yGuR@ZOsermP7Uwe=Ev%M0} z_w+4&Q)iTLF8U}h_fe&omuue!c%AI{e_mSdm3_sP+iRA){b99y&SJN22h$ax*BLxr L{an^LB{Ts5LXwmE literal 0 HcmV?d00001 diff --git a/core/img/actions/history.svg b/core/img/actions/history.svg new file mode 100644 index 00000000000..9c2838d565b --- /dev/null +++ b/core/img/actions/history.svg @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + -- GitLab From a3dff248a1f4d34ccbf7bf0120109c0d910fc548 Mon Sep 17 00:00:00 2001 From: Sam Tuke Date: Wed, 25 Apr 2012 14:27:55 +0100 Subject: [PATCH 287/430] fixed path to history script --- apps/files_versions/js/versions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/files_versions/js/versions.js b/apps/files_versions/js/versions.js index ac8b87513f2..19838cf6ad8 100644 --- a/apps/files_versions/js/versions.js +++ b/apps/files_versions/js/versions.js @@ -2,7 +2,7 @@ $(document).ready(function(){ // Add history button to files/index.php FileActions.register('file','History',function(){return OC.imagePath('core','actions/history')},function(filename){ - window.location='../apps/files_versioning/history.php?file='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename); + window.location='../apps/files_versions/history.php?path='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename); }); }); -- GitLab From b369adbd9487496d799cf04f66fcc72a002ccda5 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Wed, 25 Apr 2012 11:51:18 -0400 Subject: [PATCH 288/430] Allow admin to disable resharing of files --- apps/files_sharing/ajax/toggleresharing.php | 16 ++++++++++++++++ apps/files_sharing/appinfo/app.php | 6 +++++- apps/files_sharing/js/settings.js | 9 +++++++++ apps/files_sharing/settings.php | 9 +++++++++ apps/files_sharing/templates/settings.php | 6 ++++++ 5 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 apps/files_sharing/ajax/toggleresharing.php create mode 100644 apps/files_sharing/js/settings.js create mode 100644 apps/files_sharing/settings.php create mode 100644 apps/files_sharing/templates/settings.php diff --git a/apps/files_sharing/ajax/toggleresharing.php b/apps/files_sharing/ajax/toggleresharing.php new file mode 100644 index 00000000000..fd16b208be1 --- /dev/null +++ b/apps/files_sharing/ajax/toggleresharing.php @@ -0,0 +1,16 @@ + diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php index 8049e9b0ae3..117b65d754f 100644 --- a/apps/files_sharing/appinfo/app.php +++ b/apps/files_sharing/appinfo/app.php @@ -3,10 +3,14 @@ require_once('apps/files_sharing/sharedstorage.php'); OC::$CLASSPATH['OC_Share'] = "apps/files_sharing/lib_share.php"; +OC_APP::registerAdmin('files_sharing', 'settings'); OC_Hook::connect("OC_Filesystem", "post_delete", "OC_Share", "deleteItem"); OC_Hook::connect("OC_Filesystem", "post_rename", "OC_Share", "renameItem"); OC_Hook::connect("OC_Filesystem", "post_write", "OC_Share", "updateItem"); -OC_Util::addScript("files_sharing", "share"); +$dir = isset($_GET['dir']) ? $_GET['dir'] : '/'; +if ($dir != '/Shared' || OC_Appconfig::getValue('files_sharing', 'resharing', 'yes') == 'yes') { + OC_Util::addScript("files_sharing", "share"); +} OC_Util::addScript("3rdparty", "chosen/chosen.jquery.min"); OC_Util::addStyle( 'files_sharing', 'sharing' ); OC_Util::addStyle("3rdparty", "chosen/chosen"); diff --git a/apps/files_sharing/js/settings.js b/apps/files_sharing/js/settings.js new file mode 100644 index 00000000000..f1b1643e7d6 --- /dev/null +++ b/apps/files_sharing/js/settings.js @@ -0,0 +1,9 @@ +$(document).ready(function() { + $('#allowResharing').bind('change', function() { + var checked = 1; + if (!$('#allowResharing').attr('checked')) { + checked = 0; + } + $.post(OC.filePath('files_sharing','ajax','toggleresharing.php'), 'resharing='+checked); + }); +}); \ No newline at end of file diff --git a/apps/files_sharing/settings.php b/apps/files_sharing/settings.php new file mode 100644 index 00000000000..b30c4f45cde --- /dev/null +++ b/apps/files_sharing/settings.php @@ -0,0 +1,9 @@ +assign('allowResharing', OC_Appconfig::getValue('files_sharing', 'resharing', 'yes')); +return $tmpl->fetchPage(); + +?> \ No newline at end of file diff --git a/apps/files_sharing/templates/settings.php b/apps/files_sharing/templates/settings.php new file mode 100644 index 00000000000..5b6ba5f33ee --- /dev/null +++ b/apps/files_sharing/templates/settings.php @@ -0,0 +1,6 @@ +
    +
    + />
    + t('Allow users to reshare files they don\'t own');?> +
    + \ No newline at end of file -- GitLab From 7d9587bab339fac0f8789d57180520a7d8e0a85c Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Wed, 25 Apr 2012 11:54:16 -0400 Subject: [PATCH 289/430] Forgot to remove error log messages... --- apps/files_sharing/ajax/toggleresharing.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/apps/files_sharing/ajax/toggleresharing.php b/apps/files_sharing/ajax/toggleresharing.php index fd16b208be1..72af1eedec1 100644 --- a/apps/files_sharing/ajax/toggleresharing.php +++ b/apps/files_sharing/ajax/toggleresharing.php @@ -4,12 +4,9 @@ require_once('../../../lib/base.php'); OC_JSON::checkAppEnabled('files_sharing'); OC_JSON::checkAdminUser(); -error_log($_POST['resharing']); if ($_POST['resharing'] == true) { - error_log("enabling"); OC_Appconfig::setValue('files_sharing', 'resharing', 'yes'); } else { - error_log("disabling"); OC_Appconfig::setValue('files_sharing', 'resharing', 'no'); } -- GitLab From c00762b49b46019e47963b91185b7c131bdd3f87 Mon Sep 17 00:00:00 2001 From: Sam Tuke Date: Wed, 25 Apr 2012 17:37:45 +0100 Subject: [PATCH 290/430] added dropdown js menu for file versions, improved readability of history.php --- apps/files_versions/history.php | 2 +- apps/files_versions/js/versions.js | 60 +++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/apps/files_versions/history.php b/apps/files_versions/history.php index 7f03ce0e694..312cc734323 100644 --- a/apps/files_versions/history.php +++ b/apps/files_versions/history.php @@ -35,7 +35,7 @@ if ( isset( $_GET['path'] ) ) { } // show the history only if there is something to show - if( OCA_Versions\Storage::isversioned( $path) ) { + if( OCA_Versions\Storage::isversioned( $path ) ) { $count=5; //show the newest revisions $versions=OCA_Versions\Storage::getversions( $path, $count); diff --git a/apps/files_versions/js/versions.js b/apps/files_versions/js/versions.js index 19838cf6ad8..74a7c85070c 100644 --- a/apps/files_versions/js/versions.js +++ b/apps/files_versions/js/versions.js @@ -2,8 +2,66 @@ $(document).ready(function(){ // Add history button to files/index.php FileActions.register('file','History',function(){return OC.imagePath('core','actions/history')},function(filename){ - window.location='../apps/files_versions/history.php?path='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename); + + if (scanFiles.scanning){return;}//workaround to prevent additional http request block scanning feedback + + var file = $('#dir').val()+'/'+filename; + + createDropdown(filename, file) + + //window.location='../apps/files_versions/history.php?path='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename); + + }); }); +function createDropdown(filename, files) { + + var html = '
    t('New Address Book') ?> + t('Import from VCF') ?>
    t("CardDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Contacts.UI.Addressbooks.editAddressbook(this, " . $_['addressbook']["id"] . ");\">t("Delete") . "\" class=\"action\">t("CardDav Link") . "\" class=\"action\">t("Download") . "\" class=\"action\">t("Edit") . "\" class=\"action\" onclick=\"Contacts.UI.Addressbooks.editAddressbook(this, " . $_['addressbook']["id"] . ");\">t("Delete") . "\" class=\"action\">
    + + *dbprefix*ldap_user_mapping + + + + + ldap_dn + text + true + 255 + + + + + owncloud_name + text + true + 255 + + + + + ldap_dn + true + + ldap_dn + + + + + owncloud_name + true + + owncloud_name + ascending + + + + + +
    + + + + *dbprefix*ldap_group_mapping + + + + + ldap_dn + text + true + 255 + + + + + owncloud_name + text + true + 255 + + + + + ldap_dn + true + + ldap_dn + + + + + owncloud_name + true + + owncloud_name + ascending + + + + + +
    + + \ No newline at end of file diff --git a/apps/user_ldap/appinfo/version b/apps/user_ldap/appinfo/version index ceab6e11ece..a0d78bd347e 100644 --- a/apps/user_ldap/appinfo/version +++ b/apps/user_ldap/appinfo/version @@ -1 +1 @@ -0.1 \ No newline at end of file +0.1.90 \ No newline at end of file diff --git a/apps/user_ldap/group_ldap.php b/apps/user_ldap/group_ldap.php index df82162a67f..7773968e208 100644 --- a/apps/user_ldap/group_ldap.php +++ b/apps/user_ldap/group_ldap.php @@ -24,11 +24,9 @@ class OC_GROUP_LDAP extends OC_Group_Backend { // //group specific settings protected $ldapGroupFilter; - protected $ldapGroupDisplayName; public function __construct() { $this->ldapGroupFilter = OC_Appconfig::getValue('user_ldap', 'ldap_group_filter', '(objectClass=posixGroup)'); - $this->ldapGroupDisplayName = OC_Appconfig::getValue('user_ldap', 'ldap_group_display_name', 'cn'); } /** @@ -40,18 +38,17 @@ class OC_GROUP_LDAP extends OC_Group_Backend { * Checks whether the user is member of a group or not. */ public function inGroup($uid, $gid) { - $filter = OC_LDAP::combineFilterWithAnd(array( - $this->ldapGroupFilter, - LDAP_GROUP_MEMBER_ASSOC_ATTR.'='.$uid, - $this->ldapGroupDisplayName.'='.$gid - )); - $groups = $this->retrieveList($filter, $this->ldapGroupDisplayName); - - if(count($groups) > 0) { - return true; - } else { + $dn_user = OC_LDAP::username2dn($uid); + $dn_group = OC_LDAP::groupname2dn($gid); +// if($dn_group == 'c') {echo('#sdfsdgfds');die($gid);} + // just in case + if(!$dn_group || !$dn_user) { return false; } +// var_dump($dn_group); + $members = OC_LDAP::readAttribute($dn_group, LDAP_GROUP_MEMBER_ASSOC_ATTR); + + return in_array($dn_user, $members); } /** @@ -63,12 +60,19 @@ class OC_GROUP_LDAP extends OC_Group_Backend { * if the user exists at all. */ public function getUserGroups($uid) { + $userDN = OC_LDAP::username2dn($uid); + if(!$userDN) { + return array(); + } + $filter = OC_LDAP::combineFilterWithAnd(array( $this->ldapGroupFilter, - LDAP_GROUP_MEMBER_ASSOC_ATTR.'='.$uid + LDAP_GROUP_MEMBER_ASSOC_ATTR.'='.$userDN )); + $groups = $this->retrieveList($filter, array(OC_LDAP::conf('ldapGroupDisplayName'),'dn')); + $userGroups = OC_LDAP::ownCloudGroupNames($groups); - return $this->retrieveList($filter, $this->ldapGroupDisplayName); + return array_unique($userGroups, SORT_LOCALE_STRING); } /** @@ -76,22 +80,16 @@ class OC_GROUP_LDAP extends OC_Group_Backend { * @returns array with user ids */ public function usersInGroup($gid) { - $filter = OC_LDAP::combineFilterWithAnd(array( - $this->ldapGroupFilter, - $this->ldapGroupDisplayName.'='.$gid - )); - - $userDNs = $this->retrieveList($filter, LDAP_GROUP_MEMBER_ASSOC_ATTR, false); - $users = array(); - $attr = OC_LDAP::conf('ldapUserDisplayName'); - foreach($userDNs as $dn) { - $uid = OC_LDAP::readAttribute($dn, $attr); - if($uid) { -// if(($uid = OC_LDAP::readAttribute($dn, $attr)) != false){ - $users[] = $uid; - } + $groupDN = OC_LDAP::groupname2dn($gid); + if(!$groupDN) { + return array(); + } + $members = OC_LDAP::readAttribute($groupDN, LDAP_GROUP_MEMBER_ASSOC_ATTR); + $result = array(); + foreach($members as $member) { + $result[] = OC_LDAP::dn2username($member); } - return $users; + return array_unique($result, SORT_LOCALE_STRING); } /** @@ -101,7 +99,9 @@ class OC_GROUP_LDAP extends OC_Group_Backend { * Returns a list with all groups */ public function getGroups() { - return $this->retrieveList($this->ldapGroupFilter, $this->ldapGroupDisplayName); + $ldap_groups = $this->retrieveList($this->ldapGroupFilter, array(OC_LDAP::conf('ldapGroupDisplayName'), 'dn')); + $groups = OC_LDAP::ownCloudGroupNames($ldap_groups); + return $groups; } /** @@ -120,13 +120,18 @@ class OC_GROUP_LDAP extends OC_Group_Backend { $list = OC_LDAP::searchUsers($filter, $attr); } - if(is_array($list)) { - return array_unique($list, SORT_LOCALE_STRING); + if(count($attr) > 1){ + return $list; + } else { + return array_unique($list, SORT_LOCALE_STRING); + } } //error cause actually, maybe throw an exception in future. return array(); } + + } \ No newline at end of file diff --git a/apps/user_ldap/lib_ldap.php b/apps/user_ldap/lib_ldap.php index bd5f290779f..4efcf0c5a0d 100644 --- a/apps/user_ldap/lib_ldap.php +++ b/apps/user_ldap/lib_ldap.php @@ -21,7 +21,8 @@ * */ -define('LDAP_GROUP_MEMBER_ASSOC_ATTR','uniquemember'); +define('LDAP_GROUP_MEMBER_ASSOC_ATTR','uniqueMember'); +define('LDAP_GROUP_DISPLAY_NAME_ATTR','cn'); //needed to unbind, because we use OC_LDAP only statically class OC_LDAP_DESTRUCTOR { @@ -45,7 +46,9 @@ class OC_LDAP { static protected $ldapTLS; static protected $ldapNoCase; // user and group settings, that are needed in both backends - static public $ldapUserDisplayName; + static protected $ldapUserDisplayName; + static protected $ldapUserFilter; + static protected $ldapGroupDisplayName; static public function init() { self::readConfiguration(); @@ -56,33 +59,343 @@ class OC_LDAP { @ldap_unbind(self::$ldapConnectionRes); } + /** + * @brief returns a read-only configuration value + * @param $key the name of the configuration value + * @returns the value on success, otherwise null + * + * returns a read-only configuration values + * + * we cannot work with getters, because it is a static class + */ static public function conf($key) { + if(!self::$configured) { + self::init(); + } + $availableProperties = array( 'ldapUserDisplayName', + 'ldapGroupDisplayName', ); if(in_array($key, $availableProperties)) { return self::$$key; } + + return null; + } + + /** + * gives back the database table for the query + */ + static private function getMapTable($isUser) { + if($isUser) { + return '*PREFIX*ldap_user_mapping'; + } else { + return '*PREFIX*ldap_group_mapping'; + } + } + + /** + * @brief returns the LDAP DN for the given internal ownCloud name of the group + * @param $name the ownCloud name in question + * @returns string with the LDAP DN on success, otherwise false + * + * returns the LDAP DN for the given internal ownCloud name of the group + */ + static public function groupname2dn($name) { + return self::ocname2dn($name, false); + } + + /** + * @brief returns the LDAP DN for the given internal ownCloud name of the user + * @param $name the ownCloud name in question + * @returns string with the LDAP DN on success, otherwise false + * + * returns the LDAP DN for the given internal ownCloud name of the user + */ + static public function username2dn($name) { + $dn = self::ocname2dn($name, true); + if($dn) { + return $dn; + } else { + //fallback: user is not mapped + $filter = self::combineFilterWithAnd(array( + self::$ldapUserFilter, + self::$ldapUserDisplayName . '=' . $name, + )); + $result = self::searchUsers($filter, 'dn'); + if(isset($result[0]['dn'])) { + self::mapUser($result[0], $name); + return $result[0]; + } + } + + return false; + } + + static private function ocname2dn($name, $isUser) { + $table = self::getMapTable($isUser); + + $query = OC_DB::prepare(' + SELECT ldap_dn + FROM '.$table.' + WHERE owncloud_name = ? + '); + + $record = $query->execute(array($name))->fetchOne(); + return $record; + if($name=='Coyotes') { + echo("adsfasdf "); + var_dump($record); + die(); + } + if(isset($record['ldap_dn'])) { + return $record['ldap_dn']; + } + + return false; + } + + /** + * @brief returns the internal ownCloud name for the given LDAP DN of the group + * @param $dn the dn of the group object + * @param $ldapname optional, the display name of the object + * @returns string with with the name to use in ownCloud + * + * returns the internal ownCloud name for the given LDAP DN of the group + */ + static public function dn2groupname($dn, $ldapname = null) { + return self::dn2ocname($dn, $ldapname, false); + } + + /** + * @brief returns the internal ownCloud name for the given LDAP DN of the user + * @param $dn the dn of the user object + * @param $ldapname optional, the display name of the object + * @returns string with with the name to use in ownCloud + * + * returns the internal ownCloud name for the given LDAP DN of the user + */ + static public function dn2username($dn, $ldapname = null) { + return self::dn2ocname($dn, $ldapname, true); + } + + static public function dn2ocname($dn, $ldapname = null, $isUser = true) { + $table = self::getMapTable($isUser); + if($isUser) { + $nameAttribute = self::conf('ldapUserDisplayName'); + } else { + $nameAttribute = self::conf('ldapGroupDisplayName'); + } + + $query = OC_DB::prepare(' + SELECT owncloud_name + FROM '.$table.' + WHERE ldap_dn = ? + '); + + $component = $query->execute(array($dn))->fetchOne(); + if($component) { + return $component; + } + + if(is_null($ldapname)) { + $ldapname = self::readAttribute($dn, $nameAttribute); + $ldapname = $ldapname[0]; + } + + //a new user/group! Then let's try to add it. We're shooting into the blue with the user/group name, assuming that in most cases there will not be a conflict. Otherwise an error will occur and we will continue with our second shot. + if(self::mapComponent($dn, $ldapname, $isUser)) { + return $ldapname; + } + + //doh! There is a conflict. We need to distinguish between users/groups. Adding indexes is an idea, but not much of a help for the user. The DN is ugly, but for now the only reasonable way. But we transform it to a readable format and remove the first part to only give the path where this object is located. + $oc_name = self::alternateOwnCloudName($ldapname, $dn); + if(self::mapComponent($dn, $oc_name, $isUser)) { + return $oc_name; + } + + //and this of course should never been thrown :) + throw new Exception('LDAP backend: unexpected collision of DN and ownCloud Name.'); + } + + /** + * @brief gives back the user names as they are used ownClod internally + * @param $ldapGroups an array with the ldap Users result in style of array ( array ('dn' => foo, 'uid' => bar), ... ) + * @returns an array with the user names to use in ownCloud + * + * gives back the user names as they are used ownClod internally + */ + static public function ownCloudUserNames($ldapUsers) { + return self::ldap2ownCloudNames($ldapUsers, true); + } + + /** + * @brief gives back the group names as they are used ownClod internally + * @param $ldapGroups an array with the ldap Groups result in style of array ( array ('dn' => foo, 'cn' => bar), ... ) + * @returns an array with the group names to use in ownCloud + * + * gives back the group names as they are used ownClod internally + */ + static public function ownCloudGroupNames($ldapGroups) { + return self::ldap2ownCloudNames($ldapGroups, false); + } + + static private function ldap2ownCloudNames($ldapObjects, $isUsers) { + if($isUsers) { + $knownObjects = self::mappedUsers(); + $nameAttribute = self::conf('ldapUserDisplayName'); + } else { + $knownObjects = self::mappedGroups(); + $nameAttribute = self::conf('ldapGroupDisplayName'); + } + $ownCloudNames = array(); + + foreach($ldapObjects as $ldapObject) { + $key = self::recursiveArraySearch($knownObjects, $ldapObject['dn']); + + //everything is fine when we know the group + if($key) { + $ownCloudNames[] = $knownObjects[$key]['owncloud_name']; + continue; + } + + //a new group! Then let's try to add it. We're shooting into the blue with the group name, assuming that in most cases there will not be a conflict + if(self::mapComponent($ldapObject['dn'], $ldapObject[$nameAttribute], $isUsers)) { + $ownCloudNames[] = $ldapObject[$nameAttribute]; + continue; + } + + //doh! There is a conflict. We need to distinguish between groups. Adding indexes is an idea, but not much of a help for the user. The DN is ugly, but for now the only reasonable way. But we transform it to a readable format and remove the first part to only give the path where this entry is located. + $oc_name = self::alternateOwnCloudName($ldapObject[$nameAttribute], $ldapObject['dn']); + if(self::mapComponent($ldapObject['dn'], $oc_name, $isUsers)) { + $ownCloudNames[] = $oc_name; + continue; + } + + //and this of course should never been thrown :) + throw new Exception('LDAP backend: unexpected collision of DN and ownCloud Name.'); + } + return $ownCloudNames; + } + + /** + * @brief creates a hopefully unique name for owncloud based on the display name and the dn of the LDAP object + * @param $name the display name of the object + * @param $dn the dn of the object + * @returns string with with the name to use in ownCloud + * + * creates a hopefully unique name for owncloud based on the display name and the dn of the LDAP object + */ + static private function alternateOwnCloudName($name, $dn) { + $ufn = ldap_dn2ufn($dn); + return $name . ' (' . trim(substr_replace($ufn, '', 0, strpos($ufn, ','))) . ')'; + } + + /** + * @brief retrieves all known groups from the mappings table + * @returns array with the results + * + * retrieves all known groups from the mappings table + */ + static private function mappedGroups() { + return self::mappedComponents(false); + } + + /** + * @brief retrieves all known users from the mappings table + * @returns array with the results + * + * retrieves all known users from the mappings table + */ + static private function mappedUsers() { + return self::mappedComponents(true); + } + + static private function mappedComponents($isUsers) { + $table = self::getMapTable($isUsers); + + $query = OC_DB::prepare(' + SELECT ldap_dn, owncloud_name + FROM '. $table + ); + + return $query->execute()->fetchAll(); + } + + /** + * @brief inserts a new group into the mappings table + * @param $dn the record in question + * @param $ocname the name to use in ownCloud + * @returns true on success, false otherwise + * + * inserts a new group into the mappings table + */ + static private function mapGroup($dn, $ocname) { + return self::mapComponent($dn, $ocname, false); + } + + /** + * @brief inserts a new user into the mappings table + * @param $dn the record in question + * @param $ocname the name to use in ownCloud + * @returns true on success, false otherwise + * + * inserts a new user into the mappings table + */ + static private function mapUser($dn, $ocname) { + return self::mapComponent($dn, $ocname, true); + } + + /** + * @brief inserts a new user or group into the mappings table + * @param $dn the record in question + * @param $ocname the name to use in ownCloud + * @param $isUser is it a user or a group? + * @returns true on success, false otherwise + * + * inserts a new user or group into the mappings table + */ + static private function mapComponent($dn, $ocname, $isUser = true) { + $table = self::getMapTable($isUser); + + $insert = OC_DB::prepare(' + INSERT IGNORE INTO '.$table.' + (ldap_dn, owncloud_name) + VALUES (?,?) + '); + + $res = $insert->execute(array($dn, $ocname)); + + return !OC_DB::isError($res); } /** * @brief reads a given attribute for an LDAP record identified by a DN * @param $dn the record in question * @param $attr the attribute that shall be retrieved - * @returns the value on success, false otherwise + * @returns the values in an array on success, false otherwise * * Reads an attribute from an LDAP entry */ static public function readAttribute($dn, $attr) { - $attr = strtolower($attr); $cr = self::getConnectionResource(); - +// echo("
    ");var_dump($dn);
     		$rr = ldap_read($cr, $dn, 'objectClass=*', array($attr));
    +		if(!$rr) {
    +			echo('
    ###RA ');var_dump($dn);var_dump(debug_backtrace());die();
    +		}
     		$er = ldap_first_entry($cr, $rr);
     		$result = ldap_get_attributes($cr, $er);
    -		if($result['count'] > 0){
    -			return $result[$attr][0];
    +
    +// 		if($dn == 'cn=Coyotes,cn=groups,dc=blizzz-oc,dc=bzoc') die((var_dump($result)));
    +		if($result[$attr]['count'] > 0){
    +			$values = array();
    +			for($i=0;$i<$result[$attr]['count'];$i++) {
    +				$values[] = $result[$attr][$i];
    +			}
    +			return $values;
     		}
     		return false;
     	}
    @@ -121,15 +434,38 @@ class OC_LDAP {
     	 * Executes an LDAP search
     	 */
     	static private function search($filter, $base, $attr = null) {
    -		$sr = ldap_search(self::getConnectionResource(), $base, $filter, array($attr));
    +		if(!is_null($attr) && !is_array($attr)) {
    +			$attr = array(strtolower($attr));
    +		}
    +		$sr = ldap_search(self::getConnectionResource(), $base, $filter, $attr);
     		$findings = ldap_get_entries(self::getConnectionResource(), $sr );
     
     		if(!is_null($attr)) {
     			$selection = array();
    +			$multiarray = false;
    +			if(count($attr) > 1) {
    +				$multiarray = true;
    +				$i = 0;
    +			}
     			foreach($findings as $item) {
    -				if(isset($item[strtolower($attr)])) {
    -					$selection[] = $item[strtolower($attr)][0];
    +				if($multiarray) {
    +					foreach($attr as $key) {
    +						if(isset($item[$key])) {
    +							if($key != 'dn'){
    +								$selection[$i][$key] = $item[$key][0];
    +							} else {
    +								$selection[$i][$key] = $item[$key];
    +							}
    +						}
    +
    +					}
    +					$i++;
    +				} else {
    +					if(isset($item[$attr[0]])) {
    +						$selection[] = $item[$attr[0]];
    +					}
     				}
    +
     			}
     			return $selection;
     		}
    @@ -194,16 +530,18 @@ class OC_LDAP {
     	 */
     	static private function readConfiguration() {
     		if(!self::$configured) {
    -			self::$ldapHost            = OC_Appconfig::getValue('user_ldap', 'ldap_host', '');
    -			self::$ldapPort            = OC_Appconfig::getValue('user_ldap', 'ldap_port', OC_USER_BACKEND_LDAP_DEFAULT_PORT);
    -			self::$ldapAgentName       = OC_Appconfig::getValue('user_ldap', 'ldap_dn','');
    -			self::$ldapAgentPassword   = OC_Appconfig::getValue('user_ldap', 'ldap_password','');
    -			self::$ldapBase            = OC_Appconfig::getValue('user_ldap', 'ldap_base', '');
    -			self::$ldapBaseUsers       = OC_Appconfig::getValue('user_ldap', 'ldap_base_users',self::$ldapBase);
    -			self::$ldapBaseGroups      = OC_Appconfig::getValue('user_ldap', 'ldap_base_groups', self::$ldapBase);
    -			self::$ldapTLS             = OC_Appconfig::getValue('user_ldap', 'ldap_tls',0);
    -			self::$ldapNoCase          = OC_Appconfig::getValue('user_ldap', 'ldap_nocase', 0);
    -			self::$ldapUserDisplayName = OC_Appconfig::getValue('user_ldap', 'ldap_display_name', OC_USER_BACKEND_LDAP_DEFAULT_DISPLAY_NAME);
    +			self::$ldapHost             = OC_Appconfig::getValue('user_ldap', 'ldap_host', '');
    +			self::$ldapPort             = OC_Appconfig::getValue('user_ldap', 'ldap_port', OC_USER_BACKEND_LDAP_DEFAULT_PORT);
    +			self::$ldapAgentName        = OC_Appconfig::getValue('user_ldap', 'ldap_dn','');
    +			self::$ldapAgentPassword    = OC_Appconfig::getValue('user_ldap', 'ldap_password','');
    +			self::$ldapBase             = OC_Appconfig::getValue('user_ldap', 'ldap_base', '');
    +			self::$ldapBaseUsers        = OC_Appconfig::getValue('user_ldap', 'ldap_base_users',self::$ldapBase);
    +			self::$ldapBaseGroups       = OC_Appconfig::getValue('user_ldap', 'ldap_base_groups', self::$ldapBase);
    +			self::$ldapTLS              = OC_Appconfig::getValue('user_ldap', 'ldap_tls',0);
    +			self::$ldapNoCase           = OC_Appconfig::getValue('user_ldap', 'ldap_nocase', 0);
    +			self::$ldapUserDisplayName  = OC_Appconfig::getValue('user_ldap', 'ldap_display_name', OC_USER_BACKEND_LDAP_DEFAULT_DISPLAY_NAME);
    +			self::$ldapUserFilter       = OC_Appconfig::getValue('user_ldap', 'ldap_userlist_filter','objectClass=person');
    +			self::$ldapGroupDisplayName = OC_Appconfig::getValue('user_ldap', 'ldap_group_display_name', LDAP_GROUP_DISPLAY_NAME_ATTR);
     
     			if(
     				   !empty(self::$ldapHost)
    @@ -247,5 +585,23 @@ class OC_LDAP {
     		}
     	}
     
    +	/**
    +	* taken from http://www.php.net/manual/en/function.array-search.php#97645
    +	* TODO: move somewhere, where its better placed since it is not LDAP specific. OC_Helper maybe?
    +	*/
    +	static public function recursiveArraySearch($haystack, $needle, $index = null) {
    +		$aIt = new RecursiveArrayIterator($haystack);
    +		$it = new RecursiveIteratorIterator($aIt);
    +
    +		while($it->valid()) {
    +			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
    +				return $aIt->key();
    +			}
    +
    +			$it->next();
    +		}
    +
    +		return false;
    +	}
     
      }
    \ No newline at end of file
    -- 
    GitLab
    
    
    From 6895c54a3fe4cbc690ce0e17154bfe2e40295bb0 Mon Sep 17 00:00:00 2001
    From: Michael Gapczynski 
    Date: Wed, 25 Apr 2012 14:35:30 -0400
    Subject: [PATCH 295/430] Fix javascript checkbox toggle for resharing
    
    ---
     apps/files_sharing/js/settings.js | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/apps/files_sharing/js/settings.js b/apps/files_sharing/js/settings.js
    index f1b1643e7d6..bb7d79fecbb 100644
    --- a/apps/files_sharing/js/settings.js
    +++ b/apps/files_sharing/js/settings.js
    @@ -1,7 +1,7 @@
     $(document).ready(function() {
     	$('#allowResharing').bind('change', function() {
     		var checked = 1;
    -		if (!$('#allowResharing').attr('checked')) {
    +		if (!this.checked) {
     			checked = 0;
     		}
     		$.post(OC.filePath('files_sharing','ajax','toggleresharing.php'), 'resharing='+checked);
    -- 
    GitLab
    
    
    From 1a913ac282477c0cb13860ccb813260863ebb2ae Mon Sep 17 00:00:00 2001
    From: Georg Ehrke 
    Date: Wed, 25 Apr 2012 21:20:06 +0200
    Subject: [PATCH 296/430] bookmarks app seems to work now :)
    
    ---
     apps/bookmarks/ajax/addBookmark.php |  2 +-
     apps/bookmarks/js/bookmarks.js      | 10 +++++-----
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/apps/bookmarks/ajax/addBookmark.php b/apps/bookmarks/ajax/addBookmark.php
    index 4daed58af3b..ceeb034ec9d 100644
    --- a/apps/bookmarks/ajax/addBookmark.php
    +++ b/apps/bookmarks/ajax/addBookmark.php
    @@ -30,6 +30,6 @@ $RUNTIME_NOSETUPFS=true;
     OC_JSON::checkLoggedIn();
     OC_JSON::checkAppEnabled('bookmarks');
     
    -require_once('../bookmarksHelper.php');
    +require_once(OC::$APPSROOT . '/apps/bookmarks/bookmarksHelper.php');
     $id = addBookmark($_GET['url'], $_GET['title'], $_GET['tags']);
     OC_JSON::success(array('data' => $id));
    \ No newline at end of file
    diff --git a/apps/bookmarks/js/bookmarks.js b/apps/bookmarks/js/bookmarks.js
    index 16ed14c89b2..38b8c43eb7d 100644
    --- a/apps/bookmarks/js/bookmarks.js
    +++ b/apps/bookmarks/js/bookmarks.js
    @@ -20,7 +20,7 @@ function getBookmarks() {
     	}
     
     	$.ajax({
    -		url: 'ajax/updateList.php',
    +		url: OC.filePath('bookmarks', 'ajax', 'updateList.php'),
     		data: 'tag=' + encodeURIComponent($('#bookmarkFilterTag').val()) + '&page=' + bookmarks_page + '&sort=' + bookmarks_sorting,
     		success: function(bookmarks){
     			if (bookmarks.data.length) {
    @@ -63,7 +63,7 @@ function addOrEditBookmark(event) {
     
     	if (id == 0) {
     		$.ajax({
    -			url: 'ajax/addBookmark.php',
    +			url: OC.filePath('bookmarks', 'ajax', 'addBookmark.php'),
     			data: 'url=' + encodeURIComponent(url) + '&title=' + encodeURIComponent(title) + '&tags=' + encodeURIComponent(tags),
     			success: function(response){
     				$('.bookmarks_input').val('');
    @@ -75,7 +75,7 @@ function addOrEditBookmark(event) {
     	}
     	else {
     		$.ajax({
    -			url: 'ajax/editBookmark.php',
    +			url: OC.filePath('bookmarks', 'ajax', 'editBookmark.php'),
     			data: 'id=' + id + '&url=' + encodeURIComponent(url) + '&title=' + encodeURIComponent(title) + '&tags=' + encodeURIComponent(tags),
     			success: function(){
     				$('.bookmarks_input').val('');
    @@ -92,7 +92,7 @@ function addOrEditBookmark(event) {
     function delBookmark(event) {
     	var record = $(this).parent().parent();
     	$.ajax({
    -		url: 'ajax/delBookmark.php',
    +		url: OC.filePath('bookmarks', 'ajax', 'delBookmark.php'),
     		data: 'url=' + encodeURIComponent($(this).parent().parent().children('.bookmark_url:first').text()),
     		success: function(data){
     			record.remove();
    @@ -164,7 +164,7 @@ function updateOnBottom() {
     
     function recordClick(event) {
     	$.ajax({
    -		url: 'ajax/recordClick.php',
    +		url: OC.filePath('bookmarks', 'ajax', 'recordClick.php'),
     		data: 'url=' + encodeURIComponent($(this).attr('href')),
     	});
     }
    -- 
    GitLab
    
    
    From b75f680b8e560be82f5c63bfc5480452a3de12d9 Mon Sep 17 00:00:00 2001
    From: Georg Ehrke 
    Date: Wed, 25 Apr 2012 21:20:30 +0200
    Subject: [PATCH 297/430] gallery app seems to work now :)
    
    ---
     apps/gallery/templates/index.php | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/apps/gallery/templates/index.php b/apps/gallery/templates/index.php
    index cf654b68c0b..43ba5131864 100644
    --- a/apps/gallery/templates/index.php
    +++ b/apps/gallery/templates/index.php
    @@ -24,7 +24,7 @@ $l = OC_L10N::get('gallery');