social_stream 0.11.2 → 0.11.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (168) hide show
  1. data/Gemfile +0 -9
  2. data/base/app/assets/stylesheets/contacts.css.scss +8 -3
  3. data/base/app/assets/stylesheets/frontpage.css.scss +1 -1
  4. data/base/app/assets/stylesheets/search.css.scss +17 -1
  5. data/base/app/controllers/contacts_controller.rb +2 -5
  6. data/base/app/models/contact.rb +3 -2
  7. data/base/app/views/activities/_options.html.erb +1 -1
  8. data/base/app/views/contacts/_form.html.erb +14 -7
  9. data/base/app/views/frontpage/_social_networks.html.erb +3 -0
  10. data/base/app/views/groups/_new.html.erb +2 -2
  11. data/base/app/views/groups/_show.html.erb +1 -2
  12. data/base/app/views/groups/index.html.erb +1 -1
  13. data/base/app/views/layouts/_header_signed_out.erb +1 -3
  14. data/base/app/views/notifications/activities/_follow_subject.html.erb +5 -2
  15. data/base/app/views/notifications/activities/_like_subject.html.erb +6 -2
  16. data/base/app/views/notifications/activities/_make-friend_subject.html.erb +5 -2
  17. data/base/app/views/notifications/activities/_post_subject.html.erb +6 -1
  18. data/base/app/views/notifications/activities/_update_body.html.erb +5 -1
  19. data/base/app/views/notifications/activities/_update_subject.html.erb +5 -1
  20. data/base/app/views/posts/_post_focus_search.html.erb +37 -3
  21. data/base/app/views/posts/_post_global_search.html.erb +2 -0
  22. data/base/app/views/profiles/_contact.html.erb +1 -1
  23. data/base/app/views/search/index.js.erb +2 -0
  24. data/base/app/views/toolbar/_home.html.erb +4 -0
  25. data/base/config/locales/en.yml +26 -0
  26. data/base/config/locales/es.yml +26 -0
  27. data/base/lib/mailboxer/notification_decoder.rb +8 -6
  28. data/base/lib/social_stream-base.rb +1 -1
  29. data/base/lib/social_stream/base/version.rb +1 -1
  30. data/base/lib/social_stream/migrations/components.rb +1 -1
  31. data/base/lib/social_stream/toolbar_config/base.rb +12 -1
  32. data/base/social_stream-base.gemspec +1 -1
  33. data/base/spec/controllers/contacts_controller_spec.rb +4 -4
  34. data/events/app/assets/javascripts/social_stream-events.js +2 -2
  35. data/events/app/assets/stylesheets/social_stream-events.css +3 -0
  36. data/events/{app → vendor}/assets/javascripts/jquery.ad-gallery.js +0 -0
  37. data/events/{app → vendor}/assets/javascripts/jquery.ad-gallery.pack.js +0 -0
  38. data/events/{app → vendor}/assets/stylesheets/ad_next.png +0 -0
  39. data/events/{app → vendor}/assets/stylesheets/ad_prev.png +0 -0
  40. data/events/{app → vendor}/assets/stylesheets/ad_scroll_back.png +0 -0
  41. data/events/{app → vendor}/assets/stylesheets/ad_scroll_forward.png +0 -0
  42. data/events/{app → vendor}/assets/stylesheets/fullcalendar.css +0 -0
  43. data/events/{app → vendor}/assets/stylesheets/fullcalendar.print.css +0 -0
  44. data/events/{app → vendor}/assets/stylesheets/jquery.ad-gallery.css +0 -0
  45. data/events/{app → vendor}/assets/stylesheets/loader.gif +0 -0
  46. data/events/vendor/assets/stylesheets/social_stream-events.css +273 -0
  47. data/lib/social_stream.rb +0 -4
  48. data/lib/social_stream/version.rb +1 -1
  49. data/presence/.gitignore +4 -0
  50. data/presence/Gemfile +4 -0
  51. data/presence/Rakefile +1 -0
  52. data/presence/app/assets/audio/chat/onMessageAudio.mp3 +0 -0
  53. data/presence/app/assets/audio/chat/onMessageAudio.wav +0 -0
  54. data/presence/app/assets/images/arrow.png +0 -0
  55. data/presence/app/assets/images/black_arrow3.png +0 -0
  56. data/presence/app/assets/images/status/available.png +0 -0
  57. data/presence/app/assets/images/status/away.png +0 -0
  58. data/presence/app/assets/images/status/dnd.png +0 -0
  59. data/presence/app/assets/javascripts/jquery-ui-1.8.14.custom.min.js +789 -0
  60. data/presence/app/assets/javascripts/jquery.tools.min.js +17 -0
  61. data/presence/app/assets/javascripts/jquery.tools.tooltip.js +11 -0
  62. data/presence/app/assets/javascripts/jquery.ui.chatbox.js +260 -0
  63. data/presence/app/assets/javascripts/social_stream-presence.js +2 -0
  64. data/presence/app/assets/javascripts/store.js +27 -0
  65. data/presence/app/assets/javascripts/strophe.js +3612 -0
  66. data/presence/app/assets/javascripts/xmpp_client.js +498 -0
  67. data/presence/app/assets/stylesheets/chat.css +231 -0
  68. data/presence/app/assets/stylesheets/jquery.ui.chatbox.css +54 -0
  69. data/presence/app/assets/stylesheets/social_stream-presence.css +3 -0
  70. data/presence/app/controllers/xmpp_controller.rb +190 -0
  71. data/presence/app/helpers/xmpp_helper.rb +33 -0
  72. data/presence/app/views/xmpp/_chat.html.erb +59 -0
  73. data/presence/app/views/xmpp/_chat_connecting.html.erb +8 -0
  74. data/presence/app/views/xmpp/_chat_contacts.html.erb +46 -0
  75. data/presence/app/views/xmpp/_chat_off.html.erb +35 -0
  76. data/presence/app/views/xmpp/active_users.html.erb +33 -0
  77. data/presence/app/views/xmpp/chat.html.erb +13 -0
  78. data/presence/app/views/xmpp/index.html +19 -0
  79. data/presence/app/views/xmpp/test.html.erb +11 -0
  80. data/presence/config/routes.rb +15 -0
  81. data/presence/db/migrate/20110711111408_add_connected_column_to_user.rb +9 -0
  82. data/presence/db/migrate/20110928135031_add_status_column_to_user.rb +9 -0
  83. data/presence/ejabberd/conf/ejabberd.cfg +625 -0
  84. data/presence/ejabberd/conf/ejabberdctl.cfg +154 -0
  85. data/presence/ejabberd/conf/inetrc +3 -0
  86. data/presence/ejabberd/conf/server.pem +37 -0
  87. data/presence/ejabberd/conf/ssconfig.cfg +29 -0
  88. data/presence/ejabberd/ejabberd_scripts/authentication_script +117 -0
  89. data/presence/ejabberd/ejabberd_scripts/authentication_script_org +114 -0
  90. data/presence/ejabberd/ejabberd_scripts/compile_module +34 -0
  91. data/presence/ejabberd/ejabberd_scripts/generate_random_password +18 -0
  92. data/presence/ejabberd/ejabberd_scripts/kill_authentication_script.sh +13 -0
  93. data/presence/ejabberd/ejabberd_scripts/reset_connection_script +55 -0
  94. data/presence/ejabberd/ejabberd_scripts/reset_logs.sh +23 -0
  95. data/presence/ejabberd/ejabberd_scripts/set_connection_script +48 -0
  96. data/presence/ejabberd/ejabberd_scripts/set_presence_script +48 -0
  97. data/presence/ejabberd/ejabberd_scripts/show_config.sh +30 -0
  98. data/presence/ejabberd/ejabberd_scripts/start_ejabberd.sh +68 -0
  99. data/presence/ejabberd/ejabberd_scripts/stop_ejabberd.sh +12 -0
  100. data/presence/ejabberd/ejabberd_scripts/synchronize_presence_script +57 -0
  101. data/presence/ejabberd/ejabberd_scripts/unset_connection_script +48 -0
  102. data/presence/ejabberd/mod_admin_extra/mod_admin_extra.beam +0 -0
  103. data/presence/ejabberd/mod_admin_extra/mod_admin_extra.erl +1560 -0
  104. data/presence/ejabberd/mod_sspresence/mod_sspresence.erl +230 -0
  105. data/presence/lib/social_stream-presence.rb +13 -0
  106. data/presence/lib/social_stream/migrations/presence.rb +9 -0
  107. data/presence/lib/social_stream/presence/config.rb +9 -0
  108. data/presence/lib/social_stream/presence/engine.rb +49 -0
  109. data/presence/lib/social_stream/presence/models/buddy_manager.rb +67 -0
  110. data/presence/social_stream-presence.gemspec +28 -0
  111. data/presence/spec/demo/.gitignore +5 -0
  112. data/presence/spec/demo/.rspec +1 -0
  113. data/presence/spec/demo/README +261 -0
  114. data/presence/spec/demo/Rakefile +7 -0
  115. data/presence/spec/demo/app/assets/images/rails.png +0 -0
  116. data/presence/spec/demo/app/assets/javascripts/application.js +9 -0
  117. data/presence/spec/demo/app/assets/stylesheets/application.css +7 -0
  118. data/presence/spec/demo/app/controllers/application_controller.rb +3 -0
  119. data/presence/spec/demo/app/helpers/application_helper.rb +2 -0
  120. data/presence/spec/demo/app/mailers/.gitkeep +0 -0
  121. data/presence/spec/demo/app/models/.gitkeep +0 -0
  122. data/presence/spec/demo/app/views/layouts/application.html.erb +14 -0
  123. data/presence/spec/demo/autotest/discover.rb +2 -0
  124. data/presence/spec/demo/config.ru +4 -0
  125. data/presence/spec/demo/config/application.rb +41 -0
  126. data/presence/spec/demo/config/boot.rb +6 -0
  127. data/presence/spec/demo/config/database.yml +25 -0
  128. data/presence/spec/demo/config/environment.rb +5 -0
  129. data/presence/spec/demo/config/environments/development.rb +27 -0
  130. data/presence/spec/demo/config/environments/production.rb +54 -0
  131. data/presence/spec/demo/config/environments/test.rb +39 -0
  132. data/presence/spec/demo/config/initializers/backtrace_silencers.rb +7 -0
  133. data/presence/spec/demo/config/initializers/inflections.rb +10 -0
  134. data/presence/spec/demo/config/initializers/mime_types.rb +5 -0
  135. data/presence/spec/demo/config/initializers/secret_token.rb +7 -0
  136. data/presence/spec/demo/config/initializers/session_store.rb +8 -0
  137. data/presence/spec/demo/config/initializers/wrap_parameters.rb +12 -0
  138. data/presence/spec/demo/config/locales/en.yml +5 -0
  139. data/presence/spec/demo/config/routes.rb +58 -0
  140. data/presence/spec/demo/db/seeds.rb +7 -0
  141. data/presence/spec/demo/doc/README_FOR_APP +2 -0
  142. data/presence/spec/demo/lib/tasks/.gitkeep +0 -0
  143. data/presence/spec/demo/log/.gitkeep +0 -0
  144. data/presence/spec/demo/public/404.html +26 -0
  145. data/presence/spec/demo/public/422.html +26 -0
  146. data/presence/spec/demo/public/500.html +26 -0
  147. data/presence/spec/demo/public/favicon.ico +0 -0
  148. data/presence/spec/demo/public/index.html +241 -0
  149. data/presence/spec/demo/public/robots.txt +5 -0
  150. data/presence/spec/demo/script/rails +6 -0
  151. data/presence/spec/demo/spec/spec_helper.rb +27 -0
  152. data/presence/spec/demo/test/fixtures/.gitkeep +0 -0
  153. data/presence/spec/demo/test/functional/.gitkeep +0 -0
  154. data/presence/spec/demo/test/integration/.gitkeep +0 -0
  155. data/presence/spec/demo/test/performance/browsing_test.rb +12 -0
  156. data/presence/spec/demo/test/test_helper.rb +13 -0
  157. data/presence/spec/demo/test/unit/.gitkeep +0 -0
  158. data/presence/spec/demo/vendor/assets/stylesheets/.gitkeep +0 -0
  159. data/presence/spec/demo/vendor/plugins/.gitkeep +0 -0
  160. data/presence/spec/discover.rb +2 -0
  161. data/presence/spec/spec_helper.rb +27 -0
  162. data/social_stream.gemspec +9 -2
  163. data/spec/dummy/config/environments/{test_pg.rb → test_mysql.rb} +6 -2
  164. data/spec/dummy/config/environments/test_postgres.rb +39 -0
  165. data/spec/spec_helper.rb +1 -4
  166. metadata +135 -21
  167. data/base/app/views/groups/_new_activity.html.erb +0 -1
  168. data/base/app/views/groups/_new_activity_fields.html.erb +0 -7
@@ -0,0 +1,17 @@
1
+ /*!
2
+ * jQuery Tools v1.2.5 - The missing UI library for the Web
3
+ *
4
+ * overlay/overlay.js
5
+ * scrollable/scrollable.js
6
+ * tabs/tabs.js
7
+ * tooltip/tooltip.js
8
+ *
9
+ * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
10
+ *
11
+ * http://flowplayer.org/tools/
12
+ *
13
+ */
14
+ (function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.overlay={addEffect:function(a,b,d){c[a]=[b,d]},conf:{close:null,closeOnClick:!0,closeOnEsc:!0,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:!1,mask:null,oneInstance:!0,speed:"normal",target:null,top:"10%"}};var b=[],c={};a.tools.overlay.addEffect("default",function(b,c){var d=this.getConf(),e=a(window);d.fixed||(b.top+=e.scrollTop(),b.left+=e.scrollLeft()),b.position=d.fixed?"fixed":"absolute",this.getOverlay().css(b).fadeIn(d.speed,c)},function(a){this.getOverlay().fadeOut(this.getConf().closeSpeed,a)});function d(d,e){var f=this,g=d.add(f),h=a(window),i,j,k,l=a.tools.expose&&(e.mask||e.expose),m=Math.random().toString().slice(10);l&&(typeof l=="string"&&(l={color:l}),l.closeOnClick=l.closeOnEsc=!1);var n=e.target||d.attr("rel");j=n?a(n):null||d;if(!j.length)throw"Could not find Overlay: "+n;d&&d.index(j)==-1&&d.click(function(a){f.load(a);return a.preventDefault()}),a.extend(f,{load:function(d){if(f.isOpened())return f;var i=c[e.effect];if(!i)throw"Overlay: cannot find effect : \""+e.effect+"\"";e.oneInstance&&a.each(b,function(){this.close(d)}),d=d||a.Event(),d.type="onBeforeLoad",g.trigger(d);if(d.isDefaultPrevented())return f;k=!0,l&&a(j).expose(l);var n=e.top,o=e.left,p=j.outerWidth({margin:!0}),q=j.outerHeight({margin:!0});typeof n=="string"&&(n=n=="center"?Math.max((h.height()-q)/2,0):parseInt(n,10)/100*h.height()),o=="center"&&(o=Math.max((h.width()-p)/2,0)),i[0].call(f,{top:n,left:o},function(){k&&(d.type="onLoad",g.trigger(d))}),l&&e.closeOnClick&&a.mask.getMask().one("click",f.close),e.closeOnClick&&a(document).bind("click."+m,function(b){a(b.target).parents(j).length||f.close(b)}),e.closeOnEsc&&a(document).bind("keydown."+m,function(a){a.keyCode==27&&f.close(a)});return f},close:function(b){if(!f.isOpened())return f;b=b||a.Event(),b.type="onBeforeClose",g.trigger(b);if(!b.isDefaultPrevented()){k=!1,c[e.effect][1].call(f,function(){b.type="onClose",g.trigger(b)}),a(document).unbind("click."+m).unbind("keydown."+m),l&&a.mask.close();return f}},getOverlay:function(){return j},getTrigger:function(){return d},getClosers:function(){return i},isOpened:function(){return k},getConf:function(){return e}}),a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}}),i=j.find(e.close||".close"),!i.length&&!e.close&&(i=a("<a class=\"close\"></a>"),j.prepend(i)),i.click(function(a){f.close(a)}),e.load&&f.load()}a.fn.overlay=function(c){var e=this.data("overlay");if(e)return e;a.isFunction(c)&&(c={onBeforeLoad:c}),c=a.extend(!0,{},a.tools.overlay.conf,c),this.each(function(){e=new d(a(this),c),b.push(e),a(this).data("overlay",e)});return c.api?e:this}})(jQuery);
15
+ (function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.scrollable={conf:{activeClass:"active",circular:!1,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:!0,mousewheel:!1,next:".next",prev:".prev",speed:400,vertical:!1,touch:!0,wheelSpeed:0}};function b(a,b){var c=parseInt(a.css(b),10);if(c)return c;var d=a[0].currentStyle;return d&&d.width&&parseInt(d.width,10)}function c(b,c){var d=a(c);return d.length<2?d:b.parent().find(c)}var d;function e(b,e){var f=this,g=b.add(f),h=b.children(),i=0,j=e.vertical;d||(d=f),h.length>1&&(h=a(e.items,b)),a.extend(f,{getConf:function(){return e},getIndex:function(){return i},getSize:function(){return f.getItems().size()},getNaviButtons:function(){return m.add(n)},getRoot:function(){return b},getItemWrap:function(){return h},getItems:function(){return h.children(e.item).not("."+e.clonedClass)},move:function(a,b){return f.seekTo(i+a,b)},next:function(a){return f.move(1,a)},prev:function(a){return f.move(-1,a)},begin:function(a){return f.seekTo(0,a)},end:function(a){return f.seekTo(f.getSize()-1,a)},focus:function(){d=f;return f},addItem:function(b){b=a(b),e.circular?(h.children("."+e.clonedClass+":last").before(b),h.children("."+e.clonedClass+":first").replaceWith(b.clone().addClass(e.clonedClass))):h.append(b),g.trigger("onAddItem",[b]);return f},seekTo:function(b,c,k){b.jquery||(b*=1);if(e.circular&&b===0&&i==-1&&c!==0)return f;if(!e.circular&&b<0||b>f.getSize()||b<-1)return f;var l=b;b.jquery?b=f.getItems().index(b):l=f.getItems().eq(b);var m=a.Event("onBeforeSeek");if(!k){g.trigger(m,[b,c]);if(m.isDefaultPrevented()||!l.length)return f}var n=j?{top:-l.position().top}:{left:-l.position().left};i=b,d=f,c===undefined&&(c=e.speed),h.animate(n,c,e.easing,k||function(){g.trigger("onSeek",[b])});return f}}),a.each(["onBeforeSeek","onSeek","onAddItem"],function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}});if(e.circular){var k=f.getItems().slice(-1).clone().prependTo(h),l=f.getItems().eq(1).clone().appendTo(h);k.add(l).addClass(e.clonedClass),f.onBeforeSeek(function(a,b,c){if(!a.isDefaultPrevented()){if(b==-1){f.seekTo(k,c,function(){f.end(0)});return a.preventDefault()}b==f.getSize()&&f.seekTo(l,c,function(){f.begin(0)})}}),f.seekTo(0,0,function(){})}var m=c(b,e.prev).click(function(){f.prev()}),n=c(b,e.next).click(function(){f.next()});!e.circular&&f.getSize()>1&&(f.onBeforeSeek(function(a,b){setTimeout(function(){a.isDefaultPrevented()||(m.toggleClass(e.disabledClass,b<=0),n.toggleClass(e.disabledClass,b>=f.getSize()-1))},1)}),e.initialIndex||m.addClass(e.disabledClass)),e.mousewheel&&a.fn.mousewheel&&b.mousewheel(function(a,b){if(e.mousewheel){f.move(b<0?1:-1,e.wheelSpeed||50);return!1}});if(e.touch){var o={};h[0].ontouchstart=function(a){var b=a.touches[0];o.x=b.clientX,o.y=b.clientY},h[0].ontouchmove=function(a){if(a.touches.length==1&&!h.is(":animated")){var b=a.touches[0],c=o.x-b.clientX,d=o.y-b.clientY;f[j&&d>0||!j&&c>0?"next":"prev"](),a.preventDefault()}}}e.keyboard&&a(document).bind("keydown.scrollable",function(b){if(e.keyboard&&!b.altKey&&!b.ctrlKey&&!a(b.target).is(":input")){if(e.keyboard!="static"&&d!=f)return;var c=b.keyCode;if(j&&(c==38||c==40)){f.move(c==38?-1:1);return b.preventDefault()}if(!j&&(c==37||c==39)){f.move(c==37?-1:1);return b.preventDefault()}}}),e.initialIndex&&f.seekTo(e.initialIndex,0,function(){})}a.fn.scrollable=function(b){var c=this.data("scrollable");if(c)return c;b=a.extend({},a.tools.scrollable.conf,b),this.each(function(){c=new e(a(this),b),a(this).data("scrollable",c)});return b.api?c:this}})(jQuery);
16
+ (function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.tabs={conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",rotate:!1,history:!1},addEffect:function(a,c){b[a]=c}};var b={"default":function(a,b){this.getPanes().hide().eq(a).show(),b.call()},fade:function(a,b){var c=this.getConf(),d=c.fadeOutSpeed,e=this.getPanes();d?e.fadeOut(d):e.hide(),e.eq(a).fadeIn(c.fadeInSpeed,b)},slide:function(a,b){this.getPanes().slideUp(200),this.getPanes().eq(a).slideDown(400,b)},ajax:function(a,b){this.getPanes().eq(0).load(this.getTabs().eq(a).attr("href"),b)}},c;a.tools.tabs.addEffect("horizontal",function(b,d){c||(c=this.getPanes().eq(0).width()),this.getCurrentPane().animate({width:0},function(){a(this).hide()}),this.getPanes().eq(b).animate({width:c},function(){a(this).show(),d.call()})});function d(c,d,e){var f=this,g=c.add(this),h=c.find(e.tabs),i=d.jquery?d:c.children(d),j;h.length||(h=c.children()),i.length||(i=c.parent().find(d)),i.length||(i=a(d)),a.extend(this,{click:function(c,d){var i=h.eq(c);typeof c=="string"&&c.replace("#","")&&(i=h.filter("[href*="+c.replace("#","")+"]"),c=Math.max(h.index(i),0));if(e.rotate){var k=h.length-1;if(c<0)return f.click(k,d);if(c>k)return f.click(0,d)}if(!i.length){if(j>=0)return f;c=e.initialIndex,i=h.eq(c)}if(c===j)return f;d=d||a.Event(),d.type="onBeforeClick",g.trigger(d,[c]);if(!d.isDefaultPrevented()){b[e.effect].call(f,c,function(){d.type="onClick",g.trigger(d,[c])}),j=c,h.removeClass(e.current),i.addClass(e.current);return f}},getConf:function(){return e},getTabs:function(){return h},getPanes:function(){return i},getCurrentPane:function(){return i.eq(j)},getCurrentTab:function(){return h.eq(j)},getIndex:function(){return j},next:function(){return f.click(j+1)},prev:function(){return f.click(j-1)},destroy:function(){h.unbind(e.event).removeClass(e.current),i.find("a[href^=#]").unbind("click.T");return f}}),a.each("onBeforeClick,onClick".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}}),e.history&&a.fn.history&&(a.tools.history.init(h),e.event="history"),h.each(function(b){a(this).bind(e.event,function(a){f.click(b,a);return a.preventDefault()})}),i.find("a[href^=#]").bind("click.T",function(b){f.click(a(this).attr("href"),b)}),location.hash&&e.tabs=="a"&&c.find("[href="+location.hash+"]").length?f.click(location.hash):(e.initialIndex===0||e.initialIndex>0)&&f.click(e.initialIndex)}a.fn.tabs=function(b,c){var e=this.data("tabs");e&&(e.destroy(),this.removeData("tabs")),a.isFunction(c)&&(c={onBeforeClick:c}),c=a.extend({},a.tools.tabs.conf,c),this.each(function(){e=new d(a(this),b,c),a(this).data("tabs",e)});return c.api?e:this}})(jQuery);
17
+ (function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:!1,cancelDefault:!0,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,c,d){b[a]=[c,d]}};var b={toggle:[function(a){var b=this.getConf(),c=this.getTip(),d=b.opacity;d<1&&c.css({opacity:d}),c.show(),a.call()},function(a){this.getTip().hide(),a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};function c(b,c,d){var e=d.relative?b.position().top:b.offset().top,f=d.relative?b.position().left:b.offset().left,g=d.position[0];e-=c.outerHeight()-d.offset[0],f+=b.outerWidth()+d.offset[1],/iPad/i.test(navigator.userAgent)&&(e-=a(window).scrollTop());var h=c.outerHeight()+b.outerHeight();g=="center"&&(e+=h/2),g=="bottom"&&(e+=h),g=d.position[1];var i=c.outerWidth()+b.outerWidth();g=="center"&&(f-=i/2),g=="left"&&(f-=i);return{top:e,left:f}}function d(d,e){var f=this,g=d.add(f),h,i=0,j=0,k=d.attr("title"),l=d.attr("data-tooltip"),m=b[e.effect],n,o=d.is(":input"),p=o&&d.is(":checkbox, :radio, select, :button, :submit"),q=d.attr("type"),r=e.events[q]||e.events[o?p?"widget":"input":"def"];if(!m)throw"Nonexistent effect \""+e.effect+"\"";r=r.split(/,\s*/);if(r.length!=2)throw"Tooltip: bad events configuration for "+q;d.bind(r[0],function(a){clearTimeout(i),e.predelay?j=setTimeout(function(){f.show(a)},e.predelay):f.show(a)}).bind(r[1],function(a){clearTimeout(j),e.delay?i=setTimeout(function(){f.hide(a)},e.delay):f.hide(a)}),k&&e.cancelDefault&&(d.removeAttr("title"),d.data("title",k)),a.extend(f,{show:function(b){if(!h){l?h=a(l):e.tip?h=a(e.tip).eq(0):k?h=a(e.layout).addClass(e.tipClass).appendTo(document.body).hide().append(k):(h=d.next(),h.length||(h=d.parent().next()));if(!h.length)throw"Cannot find tooltip for "+d}if(f.isShown())return f;h.stop(!0,!0);var o=c(d,h,e);e.tip&&h.html(d.data("title")),b=b||a.Event(),b.type="onBeforeShow",g.trigger(b,[o]);if(b.isDefaultPrevented())return f;o=c(d,h,e),h.css({position:"absolute",top:o.top,left:o.left}),n=!0,m[0].call(f,function(){b.type="onShow",n="full",g.trigger(b)});var p=e.events.tooltip.split(/,\s*/);h.data("__set")||(h.bind(p[0],function(){clearTimeout(i),clearTimeout(j)}),p[1]&&!d.is("input:not(:checkbox, :radio), textarea")&&h.bind(p[1],function(a){a.relatedTarget!=d[0]&&d.trigger(r[1].split(" ")[0])}),h.data("__set",!0));return f},hide:function(c){if(!h||!f.isShown())return f;c=c||a.Event(),c.type="onBeforeHide",g.trigger(c);if(!c.isDefaultPrevented()){n=!1,b[e.effect][1].call(f,function(){c.type="onHide",g.trigger(c)});return f}},isShown:function(a){return a?n=="full":n},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return d}}),a.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}})}a.fn.tooltip=function(b){var c=this.data("tooltip");if(c)return c;b=a.extend(!0,{},a.tools.tooltip.conf,b),typeof b.position=="string"&&(b.position=b.position.split(/,?\s/)),this.each(function(){c=new d(a(this),b),a(this).data("tooltip",c)});return b.api?c:this}})(jQuery);
@@ -0,0 +1,11 @@
1
+ /*!
2
+ * jQuery Tools v1.2.5 - The missing UI library for the Web
3
+ *
4
+ * tooltip/tooltip.js
5
+ *
6
+ * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
7
+ *
8
+ * http://flowplayer.org/tools/
9
+ *
10
+ */
11
+ (function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:!1,cancelDefault:!0,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,c,d){b[a]=[c,d]}};var b={toggle:[function(a){var b=this.getConf(),c=this.getTip(),d=b.opacity;d<1&&c.css({opacity:d}),c.show(),a.call()},function(a){this.getTip().hide(),a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};function c(b,c,d){var e=d.relative?b.position().top:b.offset().top,f=d.relative?b.position().left:b.offset().left,g=d.position[0];e-=c.outerHeight()-d.offset[0],f+=b.outerWidth()+d.offset[1],/iPad/i.test(navigator.userAgent)&&(e-=a(window).scrollTop());var h=c.outerHeight()+b.outerHeight();g=="center"&&(e+=h/2),g=="bottom"&&(e+=h),g=d.position[1];var i=c.outerWidth()+b.outerWidth();g=="center"&&(f-=i/2),g=="left"&&(f-=i);return{top:e,left:f}}function d(d,e){var f=this,g=d.add(f),h,i=0,j=0,k=d.attr("title"),l=d.attr("data-tooltip"),m=b[e.effect],n,o=d.is(":input"),p=o&&d.is(":checkbox, :radio, select, :button, :submit"),q=d.attr("type"),r=e.events[q]||e.events[o?p?"widget":"input":"def"];if(!m)throw"Nonexistent effect \""+e.effect+"\"";r=r.split(/,\s*/);if(r.length!=2)throw"Tooltip: bad events configuration for "+q;d.bind(r[0],function(a){clearTimeout(i),e.predelay?j=setTimeout(function(){f.show(a)},e.predelay):f.show(a)}).bind(r[1],function(a){clearTimeout(j),e.delay?i=setTimeout(function(){f.hide(a)},e.delay):f.hide(a)}),k&&e.cancelDefault&&(d.removeAttr("title"),d.data("title",k)),a.extend(f,{show:function(b){if(!h){l?h=a(l):e.tip?h=a(e.tip).eq(0):k?h=a(e.layout).addClass(e.tipClass).appendTo(document.body).hide().append(k):(h=d.next(),h.length||(h=d.parent().next()));if(!h.length)throw"Cannot find tooltip for "+d}if(f.isShown())return f;h.stop(!0,!0);var o=c(d,h,e);e.tip&&h.html(d.data("title")),b=b||a.Event(),b.type="onBeforeShow",g.trigger(b,[o]);if(b.isDefaultPrevented())return f;o=c(d,h,e),h.css({position:"absolute",top:o.top,left:o.left}),n=!0,m[0].call(f,function(){b.type="onShow",n="full",g.trigger(b)});var p=e.events.tooltip.split(/,\s*/);h.data("__set")||(h.bind(p[0],function(){clearTimeout(i),clearTimeout(j)}),p[1]&&!d.is("input:not(:checkbox, :radio), textarea")&&h.bind(p[1],function(a){a.relatedTarget!=d[0]&&d.trigger(r[1].split(" ")[0])}),h.data("__set",!0));return f},hide:function(c){if(!h||!f.isShown())return f;c=c||a.Event(),c.type="onBeforeHide",g.trigger(c);if(!c.isDefaultPrevented()){n=!1,b[e.effect][1].call(f,function(){c.type="onHide",g.trigger(c)});return f}},isShown:function(a){return a?n=="full":n},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return d}}),a.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}})}a.fn.tooltip=function(b){var c=this.data("tooltip");if(c)return c;b=a.extend(!0,{},a.tools.tooltip.conf,b),typeof b.position=="string"&&(b.position=b.position.split(/,?\s/)),this.each(function(){c=new d(a(this),b),a(this).data("tooltip",c)});return b.api?c:this}})(jQuery);
@@ -0,0 +1,260 @@
1
+ /*
2
+ * Copyright 2010, Wen Pu (dexterpu at gmail dot com)
3
+ * Dual licensed under the MIT or GPL Version 2 licenses.
4
+ * http://jquery.org/license
5
+ *
6
+ * Check out http://www.cs.illinois.edu/homes/wenpu1/chatbox.html for document
7
+ *
8
+ * Depends on jquery.ui.core, jquery.ui.widiget, jquery.ui.effect
9
+ *
10
+ * Also uses some styles for jquery.ui.dialog
11
+ *
12
+ */
13
+
14
+
15
+ // TODO: implement destroy()
16
+ (function($){
17
+ $.widget("ui.chatbox", {
18
+ options: {
19
+ id: null, //id for the DOM element
20
+ title: null, // title of the chatbox
21
+ user: null, // can be anything associated with this chatbox
22
+ hidden: false,
23
+ offset: 0, // relative to right edge of the browser window
24
+ width: 230, // width of the chatbox
25
+ messageSent: function(id, user, msg){
26
+ // override this
27
+ this.boxManager.addMsg(user.first_name, msg);
28
+ },
29
+ boxClosed: function(id) {}, // called when the close icon is clicked
30
+ boxManager: {
31
+ // thanks to the widget factory facility
32
+ // similar to http://alexsexton.com/?p=51
33
+ init: function(elem) {
34
+ this.elem = elem;
35
+ },
36
+ addMsg: function(peer, msg) {
37
+ var self = this;
38
+ var box = self.elem.uiChatboxLog;
39
+ var e = document.createElement('div');
40
+ $(e).html("<b>" + peer +":</b> " + msg)
41
+ .addClass("ui-chatbox-msg");
42
+ box.append(e);
43
+ self._scrollToBottom();
44
+
45
+ if(!self.elem.uiChatboxTitlebar.hasClass("ui-state-focus") && !self.highlightLock) {
46
+ self.highlightLock = true;
47
+ self.highlightBox();
48
+ }
49
+ },
50
+ highlightBox: function() {
51
+ //this.elem.uiChatbox.addClass("ui-state-highlight");
52
+ var self = this;
53
+ self.elem.uiChatboxTitlebar.effect("highlight", {}, 300);
54
+ self.elem.uiChatbox.effect("bounce", {times:3}, 300, function(){
55
+ self.highlightLock = false;
56
+ self._scrollToBottom();
57
+ });
58
+ },
59
+ toggleBox: function(show) {
60
+ this.elem.uiChatbox.toggle(show);
61
+ },
62
+ _scrollToBottom: function() {
63
+ var box = this.elem.uiChatboxLog;
64
+ box.scrollTop(box.get(0).scrollHeight);
65
+ }
66
+ }
67
+ },
68
+
69
+ toggleContent: function(event) {
70
+ this.uiChatboxContent.toggle();
71
+ if(this.uiChatboxContent.is(":visible")) {
72
+ this.uiChatboxInputBox.focus();
73
+ }
74
+ },
75
+
76
+ widget: function() {
77
+ return this.uiChatbox
78
+ },
79
+
80
+ _create: function(){
81
+ var self = this,
82
+ options = self.options,
83
+ title = options.title || "No Title",
84
+ // chatbox
85
+ uiChatbox = (self.uiChatbox = $('<div></div>'))
86
+ .appendTo(document.body)
87
+ .addClass('ui-widget ' +
88
+ 'ui-corner-top ' +
89
+ 'ui-chatbox'
90
+ )
91
+ .attr('outline', 0)
92
+ .focusin(function(){
93
+ // ui-state-highlight is not really helpful here
94
+ //self.uiChatbox.removeClass('ui-state-highlight');
95
+ self.uiChatboxTitlebar.addClass('ui-state-focus');
96
+ })
97
+ .focusout(function(){
98
+ self.uiChatboxTitlebar.removeClass('ui-state-focus');
99
+ }),
100
+ // titlebar
101
+ uiChatboxTitlebar = (self.uiChatboxTitlebar = $('<div></div>'))
102
+ .addClass('ui-widget-header ' +
103
+ 'ui-corner-top ' +
104
+ 'ui-chatbox-titlebar ' +
105
+ 'ui-dialog-header' // take advantage of dialog header style
106
+ )
107
+ .click(function(event) {
108
+ self.toggleContent(event);
109
+ })
110
+ .appendTo(uiChatbox),
111
+ uiChatboxTitle = (self.uiChatboxTitle = $('<span></span>'))
112
+ .html(title)
113
+ .appendTo(uiChatboxTitlebar),
114
+ uiChatboxTitlebarClose = (self.uiChatboxTitlebarClose = $('<a href="#"></a>'))
115
+ .addClass('ui-corner-all ' +
116
+ 'ui-chatbox-icon '
117
+ )
118
+ .attr('role', 'button')
119
+ .hover(function() {uiChatboxTitlebarClose.addClass('ui-state-hover');},
120
+ function() {uiChatboxTitlebarClose.removeClass('ui-state-hover');})
121
+ // .focus(function() {
122
+ // uiChatboxTitlebarClose.addClass('ui-state-focus');
123
+ // })
124
+ // .blur(function() {
125
+ // uiChatboxTitlebarClose.removeClass('ui-state-focus');
126
+ // })
127
+ .click(function(event) {
128
+ uiChatbox.hide();
129
+ self.options.boxClosed(self.options.id);
130
+ return false;
131
+ })
132
+ .appendTo(uiChatboxTitlebar),
133
+ uiChatboxTitlebarCloseText = $('<span></span>')
134
+ .addClass('ui-icon ' +
135
+ 'ui-icon-closethick')
136
+ .text('close')
137
+ .appendTo(uiChatboxTitlebarClose),
138
+ uiChatboxTitlebarMinimize = (self.uiChatboxTitlebarMinimize = $('<a href="#"></a>'))
139
+ .addClass('ui-corner-all ' +
140
+ 'ui-chatbox-icon'
141
+ )
142
+ .attr('role', 'button')
143
+ .hover(function() {uiChatboxTitlebarMinimize.addClass('ui-state-hover');},
144
+ function() {uiChatboxTitlebarMinimize.removeClass('ui-state-hover');})
145
+ // .focus(function() {
146
+ // uiChatboxTitlebarMinimize.addClass('ui-state-focus');
147
+ // })
148
+ // .blur(function() {
149
+ // uiChatboxTitlebarMinimize.removeClass('ui-state-focus');
150
+ // })
151
+ .click(function(event) {
152
+ self.toggleContent(event);
153
+ return false;
154
+ })
155
+ .appendTo(uiChatboxTitlebar),
156
+ uiChatboxTitlebarMinimizeText = $('<span></span>')
157
+ .addClass('ui-icon ' +
158
+ 'ui-icon-minusthick')
159
+ .text('minimize')
160
+ .appendTo(uiChatboxTitlebarMinimize),
161
+ // content
162
+ uiChatboxContent = (self.uiChatboxContent = $('<div></div>'))
163
+ .addClass('ui-widget-content ' +
164
+ 'ui-chatbox-content '
165
+ )
166
+ .appendTo(uiChatbox),
167
+ uiChatboxLog = (self.uiChatboxLog = self.element)
168
+ //.show()
169
+ .addClass('ui-widget-content '+
170
+ 'ui-chatbox-log'
171
+ )
172
+ .appendTo(uiChatboxContent),
173
+ uiChatboxInput = (self.uiChatboxInput = $('<div></div>'))
174
+ .addClass('ui-widget-content ' +
175
+ 'ui-chatbox-input'
176
+ )
177
+ .click(function(event) {
178
+ // anything?
179
+ })
180
+ .appendTo(uiChatboxContent),
181
+ uiChatboxInputBox = (self.uiChatboxInputBox = $('<textarea></textarea>'))
182
+ .addClass('ui-widget-content ' +
183
+ 'ui-chatbox-input-box ' +
184
+ 'ui-corner-all'
185
+ )
186
+ .appendTo(uiChatboxInput)
187
+ .keydown(function(event) {
188
+ if(event.keyCode && event.keyCode == $.ui.keyCode.ENTER) {
189
+ msg = $.trim($(this).val());
190
+ if(msg.length > 0) {
191
+ self.options.messageSent(self.options.id, self.options.user, msg);
192
+ }
193
+ $(this).val('');
194
+ return false;
195
+ }
196
+ })
197
+ .focusin(function() {
198
+ uiChatboxInputBox.addClass('ui-chatbox-input-focus');
199
+ var box = $(this).parent().prev();
200
+ box.scrollTop(box.get(0).scrollHeight);
201
+ })
202
+ .focusout(function() {
203
+ uiChatboxInputBox.removeClass('ui-chatbox-input-focus');
204
+ });
205
+
206
+ // disable selection
207
+ uiChatboxTitlebar.find('*').add(uiChatboxTitlebar).disableSelection();
208
+
209
+ // switch focus to input box when whatever clicked
210
+ uiChatboxContent.children().click(function(){
211
+ // click on any children, set focus on input box
212
+ self.uiChatboxInputBox.focus();
213
+ });
214
+
215
+ self._setWidth(self.options.width);
216
+ self._position(self.options.offset);
217
+
218
+ self.options.boxManager.init(self);
219
+
220
+ if(!self.options.hidden) {
221
+ uiChatbox.show();
222
+ }
223
+ },
224
+
225
+ _setOption: function(option, value) {
226
+ if(value != null){
227
+ switch(option) {
228
+ case "hidden":
229
+ if(value) {
230
+ this.uiChatbox.hide();
231
+ }
232
+ else {
233
+ this.uiChatbox.show();
234
+ }
235
+ break;
236
+ case "offset":
237
+ this._position(value);
238
+ break;
239
+ case "width":
240
+ this._setWidth(value);
241
+ break;
242
+ }
243
+ }
244
+
245
+ $.Widget.prototype._setOption.apply(this, arguments);
246
+ },
247
+
248
+ _setWidth: function(width) {
249
+ this.uiChatboxTitlebar.width(width + "px");
250
+ this.uiChatboxLog.width(width + "px");
251
+ // this is a hack, but i can live with it so far
252
+ this.uiChatboxInputBox.css("width", (width - 14) + "px");
253
+ },
254
+
255
+ _position: function(offset) {
256
+ this.uiChatbox.css("right", offset);
257
+ }
258
+ });
259
+
260
+ }(jQuery));
@@ -0,0 +1,2 @@
1
+ //= require jquery
2
+ //= require_tree .
@@ -0,0 +1,27 @@
1
+ ////////////////////
2
+ //Store password with session storage
3
+ ////////////////////
4
+
5
+ function log(msg) {
6
+ console.log(msg)
7
+ }
8
+
9
+ $(document).ready(function () {
10
+
11
+ $('#sign_in_header').bind('click', function () {
12
+ storePassword();
13
+ });
14
+
15
+ $('.storePass').bind('click', function () {
16
+ storePassword();
17
+ });
18
+ });
19
+
20
+
21
+ function storePassword() {
22
+ if (window.sessionStorage) {
23
+ if (($("#user_password").length==1)&&($("#user_password").val()!="")){
24
+ sessionStorage.setItem("ss_user_pass", $('#user_password').val());
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,3612 @@
1
+ // This code was written by Tyler Akins and has been placed in the
2
+ // public domain. It would be nice if you left this header intact.
3
+ // Base64 code from Tyler Akins -- http://rumkin.com
4
+
5
+ var Base64 = (function () {
6
+ var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
7
+
8
+ var obj = {
9
+ /**
10
+ * Encodes a string in base64
11
+ * @param {String} input The string to encode in base64.
12
+ */
13
+ encode: function (input) {
14
+ var output = "";
15
+ var chr1, chr2, chr3;
16
+ var enc1, enc2, enc3, enc4;
17
+ var i = 0;
18
+
19
+ do {
20
+ chr1 = input.charCodeAt(i++);
21
+ chr2 = input.charCodeAt(i++);
22
+ chr3 = input.charCodeAt(i++);
23
+
24
+ enc1 = chr1 >> 2;
25
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
26
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
27
+ enc4 = chr3 & 63;
28
+
29
+ if (isNaN(chr2)) {
30
+ enc3 = enc4 = 64;
31
+ } else if (isNaN(chr3)) {
32
+ enc4 = 64;
33
+ }
34
+
35
+ output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
36
+ keyStr.charAt(enc3) + keyStr.charAt(enc4);
37
+ } while (i < input.length);
38
+
39
+ return output;
40
+ },
41
+
42
+ /**
43
+ * Decodes a base64 string.
44
+ * @param {String} input The string to decode.
45
+ */
46
+ decode: function (input) {
47
+ var output = "";
48
+ var chr1, chr2, chr3;
49
+ var enc1, enc2, enc3, enc4;
50
+ var i = 0;
51
+
52
+ // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
53
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
54
+
55
+ do {
56
+ enc1 = keyStr.indexOf(input.charAt(i++));
57
+ enc2 = keyStr.indexOf(input.charAt(i++));
58
+ enc3 = keyStr.indexOf(input.charAt(i++));
59
+ enc4 = keyStr.indexOf(input.charAt(i++));
60
+
61
+ chr1 = (enc1 << 2) | (enc2 >> 4);
62
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
63
+ chr3 = ((enc3 & 3) << 6) | enc4;
64
+
65
+ output = output + String.fromCharCode(chr1);
66
+
67
+ if (enc3 != 64) {
68
+ output = output + String.fromCharCode(chr2);
69
+ }
70
+ if (enc4 != 64) {
71
+ output = output + String.fromCharCode(chr3);
72
+ }
73
+ } while (i < input.length);
74
+
75
+ return output;
76
+ }
77
+ };
78
+
79
+ return obj;
80
+ })();
81
+ /*
82
+ * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
83
+ * Digest Algorithm, as defined in RFC 1321.
84
+ * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
85
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
86
+ * Distributed under the BSD License
87
+ * See http://pajhome.org.uk/crypt/md5 for more info.
88
+ */
89
+
90
+ var MD5 = (function () {
91
+ /*
92
+ * Configurable variables. You may need to tweak these to be compatible with
93
+ * the server-side, but the defaults work in most cases.
94
+ */
95
+ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
96
+ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
97
+ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
98
+
99
+ /*
100
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
101
+ * to work around bugs in some JS interpreters.
102
+ */
103
+ var safe_add = function (x, y) {
104
+ var lsw = (x & 0xFFFF) + (y & 0xFFFF);
105
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
106
+ return (msw << 16) | (lsw & 0xFFFF);
107
+ };
108
+
109
+ /*
110
+ * Bitwise rotate a 32-bit number to the left.
111
+ */
112
+ var bit_rol = function (num, cnt) {
113
+ return (num << cnt) | (num >>> (32 - cnt));
114
+ };
115
+
116
+ /*
117
+ * Convert a string to an array of little-endian words
118
+ * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
119
+ */
120
+ var str2binl = function (str) {
121
+ var bin = [];
122
+ var mask = (1 << chrsz) - 1;
123
+ for(var i = 0; i < str.length * chrsz; i += chrsz)
124
+ {
125
+ bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
126
+ }
127
+ return bin;
128
+ };
129
+
130
+ /*
131
+ * Convert an array of little-endian words to a string
132
+ */
133
+ var binl2str = function (bin) {
134
+ var str = "";
135
+ var mask = (1 << chrsz) - 1;
136
+ for(var i = 0; i < bin.length * 32; i += chrsz)
137
+ {
138
+ str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
139
+ }
140
+ return str;
141
+ };
142
+
143
+ /*
144
+ * Convert an array of little-endian words to a hex string.
145
+ */
146
+ var binl2hex = function (binarray) {
147
+ var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
148
+ var str = "";
149
+ for(var i = 0; i < binarray.length * 4; i++)
150
+ {
151
+ str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
152
+ hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
153
+ }
154
+ return str;
155
+ };
156
+
157
+ /*
158
+ * Convert an array of little-endian words to a base-64 string
159
+ */
160
+ var binl2b64 = function (binarray) {
161
+ var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
162
+ var str = "";
163
+ var triplet, j;
164
+ for(var i = 0; i < binarray.length * 4; i += 3)
165
+ {
166
+ triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) |
167
+ (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) |
168
+ ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
169
+ for(j = 0; j < 4; j++)
170
+ {
171
+ if(i * 8 + j * 6 > binarray.length * 32) { str += b64pad; }
172
+ else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); }
173
+ }
174
+ }
175
+ return str;
176
+ };
177
+
178
+ /*
179
+ * These functions implement the four basic operations the algorithm uses.
180
+ */
181
+ var md5_cmn = function (q, a, b, x, s, t) {
182
+ return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b);
183
+ };
184
+
185
+ var md5_ff = function (a, b, c, d, x, s, t) {
186
+ return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
187
+ };
188
+
189
+ var md5_gg = function (a, b, c, d, x, s, t) {
190
+ return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
191
+ };
192
+
193
+ var md5_hh = function (a, b, c, d, x, s, t) {
194
+ return md5_cmn(b ^ c ^ d, a, b, x, s, t);
195
+ };
196
+
197
+ var md5_ii = function (a, b, c, d, x, s, t) {
198
+ return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
199
+ };
200
+
201
+ /*
202
+ * Calculate the MD5 of an array of little-endian words, and a bit length
203
+ */
204
+ var core_md5 = function (x, len) {
205
+ /* append padding */
206
+ x[len >> 5] |= 0x80 << ((len) % 32);
207
+ x[(((len + 64) >>> 9) << 4) + 14] = len;
208
+
209
+ var a = 1732584193;
210
+ var b = -271733879;
211
+ var c = -1732584194;
212
+ var d = 271733878;
213
+
214
+ var olda, oldb, oldc, oldd;
215
+ for (var i = 0; i < x.length; i += 16)
216
+ {
217
+ olda = a;
218
+ oldb = b;
219
+ oldc = c;
220
+ oldd = d;
221
+
222
+ a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
223
+ d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
224
+ c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
225
+ b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
226
+ a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
227
+ d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
228
+ c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
229
+ b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
230
+ a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
231
+ d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
232
+ c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
233
+ b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
234
+ a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
235
+ d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
236
+ c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
237
+ b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
238
+
239
+ a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
240
+ d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
241
+ c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
242
+ b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
243
+ a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
244
+ d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
245
+ c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
246
+ b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
247
+ a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
248
+ d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
249
+ c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
250
+ b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
251
+ a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
252
+ d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
253
+ c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
254
+ b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
255
+
256
+ a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
257
+ d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
258
+ c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
259
+ b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
260
+ a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
261
+ d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
262
+ c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
263
+ b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
264
+ a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
265
+ d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
266
+ c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
267
+ b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
268
+ a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
269
+ d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
270
+ c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
271
+ b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
272
+
273
+ a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
274
+ d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
275
+ c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
276
+ b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
277
+ a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
278
+ d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
279
+ c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
280
+ b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
281
+ a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
282
+ d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
283
+ c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
284
+ b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
285
+ a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
286
+ d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
287
+ c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
288
+ b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
289
+
290
+ a = safe_add(a, olda);
291
+ b = safe_add(b, oldb);
292
+ c = safe_add(c, oldc);
293
+ d = safe_add(d, oldd);
294
+ }
295
+ return [a, b, c, d];
296
+ };
297
+
298
+
299
+ /*
300
+ * Calculate the HMAC-MD5, of a key and some data
301
+ */
302
+ var core_hmac_md5 = function (key, data) {
303
+ var bkey = str2binl(key);
304
+ if(bkey.length > 16) { bkey = core_md5(bkey, key.length * chrsz); }
305
+
306
+ var ipad = new Array(16), opad = new Array(16);
307
+ for(var i = 0; i < 16; i++)
308
+ {
309
+ ipad[i] = bkey[i] ^ 0x36363636;
310
+ opad[i] = bkey[i] ^ 0x5C5C5C5C;
311
+ }
312
+
313
+ var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
314
+ return core_md5(opad.concat(hash), 512 + 128);
315
+ };
316
+
317
+ var obj = {
318
+ /*
319
+ * These are the functions you'll usually want to call.
320
+ * They take string arguments and return either hex or base-64 encoded
321
+ * strings.
322
+ */
323
+ hexdigest: function (s) {
324
+ return binl2hex(core_md5(str2binl(s), s.length * chrsz));
325
+ },
326
+
327
+ b64digest: function (s) {
328
+ return binl2b64(core_md5(str2binl(s), s.length * chrsz));
329
+ },
330
+
331
+ hash: function (s) {
332
+ return binl2str(core_md5(str2binl(s), s.length * chrsz));
333
+ },
334
+
335
+ hmac_hexdigest: function (key, data) {
336
+ return binl2hex(core_hmac_md5(key, data));
337
+ },
338
+
339
+ hmac_b64digest: function (key, data) {
340
+ return binl2b64(core_hmac_md5(key, data));
341
+ },
342
+
343
+ hmac_hash: function (key, data) {
344
+ return binl2str(core_hmac_md5(key, data));
345
+ },
346
+
347
+ /*
348
+ * Perform a simple self-test to see if the VM is working
349
+ */
350
+ test: function () {
351
+ return MD5.hexdigest("abc") === "900150983cd24fb0d6963f7d28e17f72";
352
+ }
353
+ };
354
+
355
+ return obj;
356
+ })();
357
+ /*
358
+ This program is distributed under the terms of the MIT license.
359
+ Please see the LICENSE file for details.
360
+
361
+ Copyright 2006-2008, OGG, LLC
362
+ */
363
+
364
+ /* jslint configuration: */
365
+ /*global document, window, setTimeout, clearTimeout, console,
366
+ XMLHttpRequest, ActiveXObject,
367
+ Base64, MD5,
368
+ Strophe, $build, $msg, $iq, $pres */
369
+
370
+ /** File: strophe.js
371
+ * A JavaScript library for XMPP BOSH.
372
+ *
373
+ * This is the JavaScript version of the Strophe library. Since JavaScript
374
+ * has no facilities for persistent TCP connections, this library uses
375
+ * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate
376
+ * a persistent, stateful, two-way connection to an XMPP server. More
377
+ * information on BOSH can be found in XEP 124.
378
+ */
379
+
380
+ /** PrivateFunction: Function.prototype.bind
381
+ * Bind a function to an instance.
382
+ *
383
+ * This Function object extension method creates a bound method similar
384
+ * to those in Python. This means that the 'this' object will point
385
+ * to the instance you want. See
386
+ * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and
387
+ * <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a>
388
+ * for a complete explanation.
389
+ *
390
+ * This extension already exists in some browsers (namely, Firefox 3), but
391
+ * we provide it to support those that don't.
392
+ *
393
+ * Parameters:
394
+ * (Object) obj - The object that will become 'this' in the bound function.
395
+ * (Object) argN - An option argument that will be prepended to the
396
+ * arguments given for the function call
397
+ *
398
+ * Returns:
399
+ * The bound function.
400
+ */
401
+ if (!Function.prototype.bind) {
402
+ Function.prototype.bind = function (obj /*, arg1, arg2, ... */)
403
+ {
404
+ var func = this;
405
+ var _slice = Array.prototype.slice;
406
+ var _concat = Array.prototype.concat;
407
+ var _args = _slice.call(arguments, 1);
408
+
409
+ return function () {
410
+ return func.apply(obj ? obj : this,
411
+ _concat.call(_args,
412
+ _slice.call(arguments, 0)));
413
+ };
414
+ };
415
+ }
416
+
417
+ /** PrivateFunction: Array.prototype.indexOf
418
+ * Return the index of an object in an array.
419
+ *
420
+ * This function is not supplied by some JavaScript implementations, so
421
+ * we provide it if it is missing. This code is from:
422
+ * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
423
+ *
424
+ * Parameters:
425
+ * (Object) elt - The object to look for.
426
+ * (Integer) from - The index from which to start looking. (optional).
427
+ *
428
+ * Returns:
429
+ * The index of elt in the array or -1 if not found.
430
+ */
431
+ if (!Array.prototype.indexOf)
432
+ {
433
+ Array.prototype.indexOf = function(elt /*, from*/)
434
+ {
435
+ var len = this.length;
436
+
437
+ var from = Number(arguments[1]) || 0;
438
+ from = (from < 0) ? Math.ceil(from) : Math.floor(from);
439
+ if (from < 0) {
440
+ from += len;
441
+ }
442
+
443
+ for (; from < len; from++) {
444
+ if (from in this && this[from] === elt) {
445
+ return from;
446
+ }
447
+ }
448
+
449
+ return -1;
450
+ };
451
+ }
452
+
453
+ /* All of the Strophe globals are defined in this special function below so
454
+ * that references to the globals become closures. This will ensure that
455
+ * on page reload, these references will still be available to callbacks
456
+ * that are still executing.
457
+ */
458
+
459
+ (function (callback) {
460
+ var Strophe;
461
+
462
+ /** Function: $build
463
+ * Create a Strophe.Builder.
464
+ * This is an alias for 'new Strophe.Builder(name, attrs)'.
465
+ *
466
+ * Parameters:
467
+ * (String) name - The root element name.
468
+ * (Object) attrs - The attributes for the root element in object notation.
469
+ *
470
+ * Returns:
471
+ * A new Strophe.Builder object.
472
+ */
473
+ function $build(name, attrs) { return new Strophe.Builder(name, attrs); }
474
+ /** Function: $msg
475
+ * Create a Strophe.Builder with a <message/> element as the root.
476
+ *
477
+ * Parmaeters:
478
+ * (Object) attrs - The <message/> element attributes in object notation.
479
+ *
480
+ * Returns:
481
+ * A new Strophe.Builder object.
482
+ */
483
+ function $msg(attrs) { return new Strophe.Builder("message", attrs); }
484
+ /** Function: $iq
485
+ * Create a Strophe.Builder with an <iq/> element as the root.
486
+ *
487
+ * Parameters:
488
+ * (Object) attrs - The <iq/> element attributes in object notation.
489
+ *
490
+ * Returns:
491
+ * A new Strophe.Builder object.
492
+ */
493
+ function $iq(attrs) { return new Strophe.Builder("iq", attrs); }
494
+ /** Function: $pres
495
+ * Create a Strophe.Builder with a <presence/> element as the root.
496
+ *
497
+ * Parameters:
498
+ * (Object) attrs - The <presence/> element attributes in object notation.
499
+ *
500
+ * Returns:
501
+ * A new Strophe.Builder object.
502
+ */
503
+ function $pres(attrs) { return new Strophe.Builder("presence", attrs); }
504
+
505
+ /** Class: Strophe
506
+ * An object container for all Strophe library functions.
507
+ *
508
+ * This class is just a container for all the objects and constants
509
+ * used in the library. It is not meant to be instantiated, but to
510
+ * provide a namespace for library objects, constants, and functions.
511
+ */
512
+ Strophe = {
513
+ /** Constant: VERSION
514
+ * The version of the Strophe library. Unreleased builds will have
515
+ * a version of head-HASH where HASH is a partial revision.
516
+ */
517
+ VERSION: "1.0.2",
518
+
519
+ /** Constants: XMPP Namespace Constants
520
+ * Common namespace constants from the XMPP RFCs and XEPs.
521
+ *
522
+ * NS.HTTPBIND - HTTP BIND namespace from XEP 124.
523
+ * NS.BOSH - BOSH namespace from XEP 206.
524
+ * NS.CLIENT - Main XMPP client namespace.
525
+ * NS.AUTH - Legacy authentication namespace.
526
+ * NS.ROSTER - Roster operations namespace.
527
+ * NS.PROFILE - Profile namespace.
528
+ * NS.DISCO_INFO - Service discovery info namespace from XEP 30.
529
+ * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
530
+ * NS.MUC - Multi-User Chat namespace from XEP 45.
531
+ * NS.SASL - XMPP SASL namespace from RFC 3920.
532
+ * NS.STREAM - XMPP Streams namespace from RFC 3920.
533
+ * NS.BIND - XMPP Binding namespace from RFC 3920.
534
+ * NS.SESSION - XMPP Session namespace from RFC 3920.
535
+ */
536
+ NS: {
537
+ HTTPBIND: "http://jabber.org/protocol/httpbind",
538
+ BOSH: "urn:xmpp:xbosh",
539
+ CLIENT: "jabber:client",
540
+ AUTH: "jabber:iq:auth",
541
+ ROSTER: "jabber:iq:roster",
542
+ PROFILE: "jabber:iq:profile",
543
+ DISCO_INFO: "http://jabber.org/protocol/disco#info",
544
+ DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
545
+ MUC: "http://jabber.org/protocol/muc",
546
+ SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
547
+ STREAM: "http://etherx.jabber.org/streams",
548
+ BIND: "urn:ietf:params:xml:ns:xmpp-bind",
549
+ SESSION: "urn:ietf:params:xml:ns:xmpp-session",
550
+ VERSION: "jabber:iq:version",
551
+ STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas"
552
+ },
553
+
554
+ /** Function: addNamespace
555
+ * This function is used to extend the current namespaces in
556
+ * Strophe.NS. It takes a key and a value with the key being the
557
+ * name of the new namespace, with its actual value.
558
+ * For example:
559
+ * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
560
+ *
561
+ * Parameters:
562
+ * (String) name - The name under which the namespace will be
563
+ * referenced under Strophe.NS
564
+ * (String) value - The actual namespace.
565
+ */
566
+ addNamespace: function (name, value)
567
+ {
568
+ Strophe.NS[name] = value;
569
+ },
570
+
571
+ /** Constants: Connection Status Constants
572
+ * Connection status constants for use by the connection handler
573
+ * callback.
574
+ *
575
+ * Status.ERROR - An error has occurred
576
+ * Status.CONNECTING - The connection is currently being made
577
+ * Status.CONNFAIL - The connection attempt failed
578
+ * Status.AUTHENTICATING - The connection is authenticating
579
+ * Status.AUTHFAIL - The authentication attempt failed
580
+ * Status.CONNECTED - The connection has succeeded
581
+ * Status.DISCONNECTED - The connection has been terminated
582
+ * Status.DISCONNECTING - The connection is currently being terminated
583
+ * Status.ATTACHED - The connection has been attached
584
+ */
585
+ Status: {
586
+ ERROR: 0,
587
+ CONNECTING: 1,
588
+ CONNFAIL: 2,
589
+ AUTHENTICATING: 3,
590
+ AUTHFAIL: 4,
591
+ CONNECTED: 5,
592
+ DISCONNECTED: 6,
593
+ DISCONNECTING: 7,
594
+ ATTACHED: 8
595
+ },
596
+
597
+ /** Constants: Log Level Constants
598
+ * Logging level indicators.
599
+ *
600
+ * LogLevel.DEBUG - Debug output
601
+ * LogLevel.INFO - Informational output
602
+ * LogLevel.WARN - Warnings
603
+ * LogLevel.ERROR - Errors
604
+ * LogLevel.FATAL - Fatal errors
605
+ */
606
+ LogLevel: {
607
+ DEBUG: 0,
608
+ INFO: 1,
609
+ WARN: 2,
610
+ ERROR: 3,
611
+ FATAL: 4
612
+ },
613
+
614
+ /** PrivateConstants: DOM Element Type Constants
615
+ * DOM element types.
616
+ *
617
+ * ElementType.NORMAL - Normal element.
618
+ * ElementType.TEXT - Text data element.
619
+ */
620
+ ElementType: {
621
+ NORMAL: 1,
622
+ TEXT: 3,
623
+ CDATA: 4
624
+ },
625
+
626
+ /** PrivateConstants: Timeout Values
627
+ * Timeout values for error states. These values are in seconds.
628
+ * These should not be changed unless you know exactly what you are
629
+ * doing.
630
+ *
631
+ * TIMEOUT - Timeout multiplier. A waiting request will be considered
632
+ * failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
633
+ * This defaults to 1.1, and with default wait, 66 seconds.
634
+ * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
635
+ * Strophe can detect early failure, it will consider the request
636
+ * failed if it doesn't return after
637
+ * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
638
+ * This defaults to 0.1, and with default wait, 6 seconds.
639
+ */
640
+ TIMEOUT: 1.1,
641
+ SECONDARY_TIMEOUT: 0.1,
642
+
643
+ /** Function: forEachChild
644
+ * Map a function over some or all child elements of a given element.
645
+ *
646
+ * This is a small convenience function for mapping a function over
647
+ * some or all of the children of an element. If elemName is null, all
648
+ * children will be passed to the function, otherwise only children
649
+ * whose tag names match elemName will be passed.
650
+ *
651
+ * Parameters:
652
+ * (XMLElement) elem - The element to operate on.
653
+ * (String) elemName - The child element tag name filter.
654
+ * (Function) func - The function to apply to each child. This
655
+ * function should take a single argument, a DOM element.
656
+ */
657
+ forEachChild: function (elem, elemName, func)
658
+ {
659
+ var i, childNode;
660
+
661
+ for (i = 0; i < elem.childNodes.length; i++) {
662
+ childNode = elem.childNodes[i];
663
+ if (childNode.nodeType == Strophe.ElementType.NORMAL &&
664
+ (!elemName || this.isTagEqual(childNode, elemName))) {
665
+ func(childNode);
666
+ }
667
+ }
668
+ },
669
+
670
+ /** Function: isTagEqual
671
+ * Compare an element's tag name with a string.
672
+ *
673
+ * This function is case insensitive.
674
+ *
675
+ * Parameters:
676
+ * (XMLElement) el - A DOM element.
677
+ * (String) name - The element name.
678
+ *
679
+ * Returns:
680
+ * true if the element's tag name matches _el_, and false
681
+ * otherwise.
682
+ */
683
+ isTagEqual: function (el, name)
684
+ {
685
+ return el.tagName.toLowerCase() == name.toLowerCase();
686
+ },
687
+
688
+ /** PrivateVariable: _xmlGenerator
689
+ * _Private_ variable that caches a DOM document to
690
+ * generate elements.
691
+ */
692
+ _xmlGenerator: null,
693
+
694
+ /** PrivateFunction: _makeGenerator
695
+ * _Private_ function that creates a dummy XML DOM document to serve as
696
+ * an element and text node generator.
697
+ */
698
+ _makeGenerator: function () {
699
+ var doc;
700
+
701
+ if (document.implementation.createDocument === undefined) {
702
+ doc = this._getIEXmlDom();
703
+ doc.appendChild(doc.createElement('strophe'));
704
+ } else {
705
+ doc = document.implementation
706
+ .createDocument('jabber:client', 'strophe', null);
707
+ }
708
+
709
+ return doc;
710
+ },
711
+
712
+ /** Function: xmlGenerator
713
+ * Get the DOM document to generate elements.
714
+ *
715
+ * Returns:
716
+ * The currently used DOM document.
717
+ */
718
+ xmlGenerator: function () {
719
+ if (!Strophe._xmlGenerator) {
720
+ Strophe._xmlGenerator = Strophe._makeGenerator();
721
+ }
722
+ return Strophe._xmlGenerator;
723
+ },
724
+
725
+ /** PrivateFunction: _getIEXmlDom
726
+ * Gets IE xml doc object
727
+ *
728
+ * Returns:
729
+ * A Microsoft XML DOM Object
730
+ * See Also:
731
+ * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
732
+ */
733
+ _getIEXmlDom : function() {
734
+ var doc = null;
735
+ var docStrings = [
736
+ "Msxml2.DOMDocument.6.0",
737
+ "Msxml2.DOMDocument.5.0",
738
+ "Msxml2.DOMDocument.4.0",
739
+ "MSXML2.DOMDocument.3.0",
740
+ "MSXML2.DOMDocument",
741
+ "MSXML.DOMDocument",
742
+ "Microsoft.XMLDOM"
743
+ ];
744
+
745
+ for (var d = 0; d < docStrings.length; d++) {
746
+ if (doc === null) {
747
+ try {
748
+ doc = new ActiveXObject(docStrings[d]);
749
+ } catch (e) {
750
+ doc = null;
751
+ }
752
+ } else {
753
+ break;
754
+ }
755
+ }
756
+
757
+ return doc;
758
+ },
759
+
760
+ /** Function: xmlElement
761
+ * Create an XML DOM element.
762
+ *
763
+ * This function creates an XML DOM element correctly across all
764
+ * implementations. Note that these are not HTML DOM elements, which
765
+ * aren't appropriate for XMPP stanzas.
766
+ *
767
+ * Parameters:
768
+ * (String) name - The name for the element.
769
+ * (Array|Object) attrs - An optional array or object containing
770
+ * key/value pairs to use as element attributes. The object should
771
+ * be in the format {'key': 'value'} or {key: 'value'}. The array
772
+ * should have the format [['key1', 'value1'], ['key2', 'value2']].
773
+ * (String) text - The text child data for the element.
774
+ *
775
+ * Returns:
776
+ * A new XML DOM element.
777
+ */
778
+ xmlElement: function (name)
779
+ {
780
+ if (!name) { return null; }
781
+
782
+ var node = Strophe.xmlGenerator().createElement(name);
783
+
784
+ // FIXME: this should throw errors if args are the wrong type or
785
+ // there are more than two optional args
786
+ var a, i, k;
787
+ for (a = 1; a < arguments.length; a++) {
788
+ if (!arguments[a]) { continue; }
789
+ if (typeof(arguments[a]) == "string" ||
790
+ typeof(arguments[a]) == "number") {
791
+ node.appendChild(Strophe.xmlTextNode(arguments[a]));
792
+ } else if (typeof(arguments[a]) == "object" &&
793
+ typeof(arguments[a].sort) == "function") {
794
+ for (i = 0; i < arguments[a].length; i++) {
795
+ if (typeof(arguments[a][i]) == "object" &&
796
+ typeof(arguments[a][i].sort) == "function") {
797
+ node.setAttribute(arguments[a][i][0],
798
+ arguments[a][i][1]);
799
+ }
800
+ }
801
+ } else if (typeof(arguments[a]) == "object") {
802
+ for (k in arguments[a]) {
803
+ if (arguments[a].hasOwnProperty(k)) {
804
+ node.setAttribute(k, arguments[a][k]);
805
+ }
806
+ }
807
+ }
808
+ }
809
+
810
+ return node;
811
+ },
812
+
813
+ /* Function: xmlescape
814
+ * Excapes invalid xml characters.
815
+ *
816
+ * Parameters:
817
+ * (String) text - text to escape.
818
+ *
819
+ * Returns:
820
+ * Escaped text.
821
+ */
822
+ xmlescape: function(text)
823
+ {
824
+ text = text.replace(/\&/g, "&amp;");
825
+ text = text.replace(/</g, "&lt;");
826
+ text = text.replace(/>/g, "&gt;");
827
+ text = text.replace(/'/g, "&apos;");
828
+ text = text.replace(/"/g, "&quot;");
829
+ return text;
830
+ },
831
+
832
+ /** Function: xmlTextNode
833
+ * Creates an XML DOM text node.
834
+ *
835
+ * Provides a cross implementation version of document.createTextNode.
836
+ *
837
+ * Parameters:
838
+ * (String) text - The content of the text node.
839
+ *
840
+ * Returns:
841
+ * A new XML DOM text node.
842
+ */
843
+ xmlTextNode: function (text)
844
+ {
845
+ //ensure text is escaped
846
+ text = Strophe.xmlescape(text);
847
+
848
+ return Strophe.xmlGenerator().createTextNode(text);
849
+ },
850
+
851
+ /** Function: getText
852
+ * Get the concatenation of all text children of an element.
853
+ *
854
+ * Parameters:
855
+ * (XMLElement) elem - A DOM element.
856
+ *
857
+ * Returns:
858
+ * A String with the concatenated text of all text element children.
859
+ */
860
+ getText: function (elem)
861
+ {
862
+ if (!elem) { return null; }
863
+
864
+ var str = "";
865
+ if (elem.childNodes.length === 0 && elem.nodeType ==
866
+ Strophe.ElementType.TEXT) {
867
+ str += elem.nodeValue;
868
+ }
869
+
870
+ for (var i = 0; i < elem.childNodes.length; i++) {
871
+ if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) {
872
+ str += elem.childNodes[i].nodeValue;
873
+ }
874
+ }
875
+
876
+ return str;
877
+ },
878
+
879
+ /** Function: copyElement
880
+ * Copy an XML DOM element.
881
+ *
882
+ * This function copies a DOM element and all its descendants and returns
883
+ * the new copy.
884
+ *
885
+ * Parameters:
886
+ * (XMLElement) elem - A DOM element.
887
+ *
888
+ * Returns:
889
+ * A new, copied DOM element tree.
890
+ */
891
+ copyElement: function (elem)
892
+ {
893
+ var i, el;
894
+ if (elem.nodeType == Strophe.ElementType.NORMAL) {
895
+ el = Strophe.xmlElement(elem.tagName);
896
+
897
+ for (i = 0; i < elem.attributes.length; i++) {
898
+ el.setAttribute(elem.attributes[i].nodeName.toLowerCase(),
899
+ elem.attributes[i].value);
900
+ }
901
+
902
+ for (i = 0; i < elem.childNodes.length; i++) {
903
+ el.appendChild(Strophe.copyElement(elem.childNodes[i]));
904
+ }
905
+ } else if (elem.nodeType == Strophe.ElementType.TEXT) {
906
+ el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
907
+ }
908
+
909
+ return el;
910
+ },
911
+
912
+ /** Function: escapeNode
913
+ * Escape the node part (also called local part) of a JID.
914
+ *
915
+ * Parameters:
916
+ * (String) node - A node (or local part).
917
+ *
918
+ * Returns:
919
+ * An escaped node (or local part).
920
+ */
921
+ escapeNode: function (node)
922
+ {
923
+ return node.replace(/^\s+|\s+$/g, '')
924
+ .replace(/\\/g, "\\5c")
925
+ .replace(/ /g, "\\20")
926
+ .replace(/\"/g, "\\22")
927
+ .replace(/\&/g, "\\26")
928
+ .replace(/\'/g, "\\27")
929
+ .replace(/\//g, "\\2f")
930
+ .replace(/:/g, "\\3a")
931
+ .replace(/</g, "\\3c")
932
+ .replace(/>/g, "\\3e")
933
+ .replace(/@/g, "\\40");
934
+ },
935
+
936
+ /** Function: unescapeNode
937
+ * Unescape a node part (also called local part) of a JID.
938
+ *
939
+ * Parameters:
940
+ * (String) node - A node (or local part).
941
+ *
942
+ * Returns:
943
+ * An unescaped node (or local part).
944
+ */
945
+ unescapeNode: function (node)
946
+ {
947
+ return node.replace(/\\20/g, " ")
948
+ .replace(/\\22/g, '"')
949
+ .replace(/\\26/g, "&")
950
+ .replace(/\\27/g, "'")
951
+ .replace(/\\2f/g, "/")
952
+ .replace(/\\3a/g, ":")
953
+ .replace(/\\3c/g, "<")
954
+ .replace(/\\3e/g, ">")
955
+ .replace(/\\40/g, "@")
956
+ .replace(/\\5c/g, "\\");
957
+ },
958
+
959
+ /** Function: getNodeFromJid
960
+ * Get the node portion of a JID String.
961
+ *
962
+ * Parameters:
963
+ * (String) jid - A JID.
964
+ *
965
+ * Returns:
966
+ * A String containing the node.
967
+ */
968
+ getNodeFromJid: function (jid)
969
+ {
970
+ if (jid.indexOf("@") < 0) { return null; }
971
+ return jid.split("@")[0];
972
+ },
973
+
974
+ /** Function: getDomainFromJid
975
+ * Get the domain portion of a JID String.
976
+ *
977
+ * Parameters:
978
+ * (String) jid - A JID.
979
+ *
980
+ * Returns:
981
+ * A String containing the domain.
982
+ */
983
+ getDomainFromJid: function (jid)
984
+ {
985
+ var bare = Strophe.getBareJidFromJid(jid);
986
+ if (bare.indexOf("@") < 0) {
987
+ return bare;
988
+ } else {
989
+ var parts = bare.split("@");
990
+ parts.splice(0, 1);
991
+ return parts.join('@');
992
+ }
993
+ },
994
+
995
+ /** Function: getResourceFromJid
996
+ * Get the resource portion of a JID String.
997
+ *
998
+ * Parameters:
999
+ * (String) jid - A JID.
1000
+ *
1001
+ * Returns:
1002
+ * A String containing the resource.
1003
+ */
1004
+ getResourceFromJid: function (jid)
1005
+ {
1006
+ var s = jid.split("/");
1007
+ if (s.length < 2) { return null; }
1008
+ s.splice(0, 1);
1009
+ return s.join('/');
1010
+ },
1011
+
1012
+ /** Function: getBareJidFromJid
1013
+ * Get the bare JID from a JID String.
1014
+ *
1015
+ * Parameters:
1016
+ * (String) jid - A JID.
1017
+ *
1018
+ * Returns:
1019
+ * A String containing the bare JID.
1020
+ */
1021
+ getBareJidFromJid: function (jid)
1022
+ {
1023
+ return jid ? jid.split("/")[0] : null;
1024
+ },
1025
+
1026
+ /** Function: log
1027
+ * User overrideable logging function.
1028
+ *
1029
+ * This function is called whenever the Strophe library calls any
1030
+ * of the logging functions. The default implementation of this
1031
+ * function does nothing. If client code wishes to handle the logging
1032
+ * messages, it should override this with
1033
+ * > Strophe.log = function (level, msg) {
1034
+ * > (user code here)
1035
+ * > };
1036
+ *
1037
+ * Please note that data sent and received over the wire is logged
1038
+ * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
1039
+ *
1040
+ * The different levels and their meanings are
1041
+ *
1042
+ * DEBUG - Messages useful for debugging purposes.
1043
+ * INFO - Informational messages. This is mostly information like
1044
+ * 'disconnect was called' or 'SASL auth succeeded'.
1045
+ * WARN - Warnings about potential problems. This is mostly used
1046
+ * to report transient connection errors like request timeouts.
1047
+ * ERROR - Some error occurred.
1048
+ * FATAL - A non-recoverable fatal error occurred.
1049
+ *
1050
+ * Parameters:
1051
+ * (Integer) level - The log level of the log message. This will
1052
+ * be one of the values in Strophe.LogLevel.
1053
+ * (String) msg - The log message.
1054
+ */
1055
+ log: function (level, msg)
1056
+ {
1057
+ return;
1058
+ },
1059
+
1060
+ /** Function: debug
1061
+ * Log a message at the Strophe.LogLevel.DEBUG level.
1062
+ *
1063
+ * Parameters:
1064
+ * (String) msg - The log message.
1065
+ */
1066
+ debug: function(msg)
1067
+ {
1068
+ this.log(this.LogLevel.DEBUG, msg);
1069
+ },
1070
+
1071
+ /** Function: info
1072
+ * Log a message at the Strophe.LogLevel.INFO level.
1073
+ *
1074
+ * Parameters:
1075
+ * (String) msg - The log message.
1076
+ */
1077
+ info: function (msg)
1078
+ {
1079
+ this.log(this.LogLevel.INFO, msg);
1080
+ },
1081
+
1082
+ /** Function: warn
1083
+ * Log a message at the Strophe.LogLevel.WARN level.
1084
+ *
1085
+ * Parameters:
1086
+ * (String) msg - The log message.
1087
+ */
1088
+ warn: function (msg)
1089
+ {
1090
+ this.log(this.LogLevel.WARN, msg);
1091
+ },
1092
+
1093
+ /** Function: error
1094
+ * Log a message at the Strophe.LogLevel.ERROR level.
1095
+ *
1096
+ * Parameters:
1097
+ * (String) msg - The log message.
1098
+ */
1099
+ error: function (msg)
1100
+ {
1101
+ this.log(this.LogLevel.ERROR, msg);
1102
+ },
1103
+
1104
+ /** Function: fatal
1105
+ * Log a message at the Strophe.LogLevel.FATAL level.
1106
+ *
1107
+ * Parameters:
1108
+ * (String) msg - The log message.
1109
+ */
1110
+ fatal: function (msg)
1111
+ {
1112
+ this.log(this.LogLevel.FATAL, msg);
1113
+ },
1114
+
1115
+ /** Function: serialize
1116
+ * Render a DOM element and all descendants to a String.
1117
+ *
1118
+ * Parameters:
1119
+ * (XMLElement) elem - A DOM element.
1120
+ *
1121
+ * Returns:
1122
+ * The serialized element tree as a String.
1123
+ */
1124
+ serialize: function (elem)
1125
+ {
1126
+ var result;
1127
+
1128
+ if (!elem) { return null; }
1129
+
1130
+ if (typeof(elem.tree) === "function") {
1131
+ elem = elem.tree();
1132
+ }
1133
+
1134
+ var nodeName = elem.nodeName;
1135
+ var i, child;
1136
+
1137
+ if (elem.getAttribute("_realname")) {
1138
+ nodeName = elem.getAttribute("_realname");
1139
+ }
1140
+
1141
+ result = "<" + nodeName;
1142
+ for (i = 0; i < elem.attributes.length; i++) {
1143
+ if(elem.attributes[i].nodeName != "_realname") {
1144
+ result += " " + elem.attributes[i].nodeName.toLowerCase() +
1145
+ "='" + elem.attributes[i].value
1146
+ .replace(/&/g, "&amp;")
1147
+ .replace(/\'/g, "&apos;")
1148
+ .replace(/</g, "&lt;") + "'";
1149
+ }
1150
+ }
1151
+
1152
+ if (elem.childNodes.length > 0) {
1153
+ result += ">";
1154
+ for (i = 0; i < elem.childNodes.length; i++) {
1155
+ child = elem.childNodes[i];
1156
+ switch( child.nodeType ){
1157
+ case Strophe.ElementType.NORMAL:
1158
+ // normal element, so recurse
1159
+ result += Strophe.serialize(child);
1160
+ break;
1161
+ case Strophe.ElementType.TEXT:
1162
+ // text element to escape values
1163
+ result += Strophe.xmlescape(child.nodeValue);
1164
+ break;
1165
+ case Strophe.ElementType.CDATA:
1166
+ // cdata section so don't escape values
1167
+ result += "<![CDATA["+child.nodeValue+"]]>";
1168
+ }
1169
+ }
1170
+ result += "</" + nodeName + ">";
1171
+ } else {
1172
+ result += "/>";
1173
+ }
1174
+
1175
+ return result;
1176
+ },
1177
+
1178
+ /** PrivateVariable: _requestId
1179
+ * _Private_ variable that keeps track of the request ids for
1180
+ * connections.
1181
+ */
1182
+ _requestId: 0,
1183
+
1184
+ /** PrivateVariable: Strophe.connectionPlugins
1185
+ * _Private_ variable Used to store plugin names that need
1186
+ * initialization on Strophe.Connection construction.
1187
+ */
1188
+ _connectionPlugins: {},
1189
+
1190
+ /** Function: addConnectionPlugin
1191
+ * Extends the Strophe.Connection object with the given plugin.
1192
+ *
1193
+ * Parameters:
1194
+ * (String) name - The name of the extension.
1195
+ * (Object) ptype - The plugin's prototype.
1196
+ */
1197
+ addConnectionPlugin: function (name, ptype)
1198
+ {
1199
+ Strophe._connectionPlugins[name] = ptype;
1200
+ }
1201
+ };
1202
+
1203
+ /** Class: Strophe.Builder
1204
+ * XML DOM builder.
1205
+ *
1206
+ * This object provides an interface similar to JQuery but for building
1207
+ * DOM element easily and rapidly. All the functions except for toString()
1208
+ * and tree() return the object, so calls can be chained. Here's an
1209
+ * example using the $iq() builder helper.
1210
+ * > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
1211
+ * > .c('query', {xmlns: 'strophe:example'})
1212
+ * > .c('example')
1213
+ * > .toString()
1214
+ * The above generates this XML fragment
1215
+ * > <iq to='you' from='me' type='get' id='1'>
1216
+ * > <query xmlns='strophe:example'>
1217
+ * > <example/>
1218
+ * > </query>
1219
+ * > </iq>
1220
+ * The corresponding DOM manipulations to get a similar fragment would be
1221
+ * a lot more tedious and probably involve several helper variables.
1222
+ *
1223
+ * Since adding children makes new operations operate on the child, up()
1224
+ * is provided to traverse up the tree. To add two children, do
1225
+ * > builder.c('child1', ...).up().c('child2', ...)
1226
+ * The next operation on the Builder will be relative to the second child.
1227
+ */
1228
+
1229
+ /** Constructor: Strophe.Builder
1230
+ * Create a Strophe.Builder object.
1231
+ *
1232
+ * The attributes should be passed in object notation. For example
1233
+ * > var b = new Builder('message', {to: 'you', from: 'me'});
1234
+ * or
1235
+ * > var b = new Builder('messsage', {'xml:lang': 'en'});
1236
+ *
1237
+ * Parameters:
1238
+ * (String) name - The name of the root element.
1239
+ * (Object) attrs - The attributes for the root element in object notation.
1240
+ *
1241
+ * Returns:
1242
+ * A new Strophe.Builder.
1243
+ */
1244
+ Strophe.Builder = function (name, attrs)
1245
+ {
1246
+ // Set correct namespace for jabber:client elements
1247
+ if (name == "presence" || name == "message" || name == "iq") {
1248
+ if (attrs && !attrs.xmlns) {
1249
+ attrs.xmlns = Strophe.NS.CLIENT;
1250
+ } else if (!attrs) {
1251
+ attrs = {xmlns: Strophe.NS.CLIENT};
1252
+ }
1253
+ }
1254
+
1255
+ // Holds the tree being built.
1256
+ this.nodeTree = Strophe.xmlElement(name, attrs);
1257
+
1258
+ // Points to the current operation node.
1259
+ this.node = this.nodeTree;
1260
+ };
1261
+
1262
+ Strophe.Builder.prototype = {
1263
+ /** Function: tree
1264
+ * Return the DOM tree.
1265
+ *
1266
+ * This function returns the current DOM tree as an element object. This
1267
+ * is suitable for passing to functions like Strophe.Connection.send().
1268
+ *
1269
+ * Returns:
1270
+ * The DOM tree as a element object.
1271
+ */
1272
+ tree: function ()
1273
+ {
1274
+ return this.nodeTree;
1275
+ },
1276
+
1277
+ /** Function: toString
1278
+ * Serialize the DOM tree to a String.
1279
+ *
1280
+ * This function returns a string serialization of the current DOM
1281
+ * tree. It is often used internally to pass data to a
1282
+ * Strophe.Request object.
1283
+ *
1284
+ * Returns:
1285
+ * The serialized DOM tree in a String.
1286
+ */
1287
+ toString: function ()
1288
+ {
1289
+ return Strophe.serialize(this.nodeTree);
1290
+ },
1291
+
1292
+ /** Function: up
1293
+ * Make the current parent element the new current element.
1294
+ *
1295
+ * This function is often used after c() to traverse back up the tree.
1296
+ * For example, to add two children to the same element
1297
+ * > builder.c('child1', {}).up().c('child2', {});
1298
+ *
1299
+ * Returns:
1300
+ * The Stophe.Builder object.
1301
+ */
1302
+ up: function ()
1303
+ {
1304
+ this.node = this.node.parentNode;
1305
+ return this;
1306
+ },
1307
+
1308
+ /** Function: attrs
1309
+ * Add or modify attributes of the current element.
1310
+ *
1311
+ * The attributes should be passed in object notation. This function
1312
+ * does not move the current element pointer.
1313
+ *
1314
+ * Parameters:
1315
+ * (Object) moreattrs - The attributes to add/modify in object notation.
1316
+ *
1317
+ * Returns:
1318
+ * The Strophe.Builder object.
1319
+ */
1320
+ attrs: function (moreattrs)
1321
+ {
1322
+ for (var k in moreattrs) {
1323
+ if (moreattrs.hasOwnProperty(k)) {
1324
+ this.node.setAttribute(k, moreattrs[k]);
1325
+ }
1326
+ }
1327
+ return this;
1328
+ },
1329
+
1330
+ /** Function: c
1331
+ * Add a child to the current element and make it the new current
1332
+ * element.
1333
+ *
1334
+ * This function moves the current element pointer to the child,
1335
+ * unless text is provided. If you need to add another child, it
1336
+ * is necessary to use up() to go back to the parent in the tree.
1337
+ *
1338
+ * Parameters:
1339
+ * (String) name - The name of the child.
1340
+ * (Object) attrs - The attributes of the child in object notation.
1341
+ * (String) text - The text to add to the child.
1342
+ *
1343
+ * Returns:
1344
+ * The Strophe.Builder object.
1345
+ */
1346
+ c: function (name, attrs, text)
1347
+ {
1348
+ var child = Strophe.xmlElement(name, attrs, text);
1349
+ this.node.appendChild(child);
1350
+ if (!text) {
1351
+ this.node = child;
1352
+ }
1353
+ return this;
1354
+ },
1355
+
1356
+ /** Function: cnode
1357
+ * Add a child to the current element and make it the new current
1358
+ * element.
1359
+ *
1360
+ * This function is the same as c() except that instead of using a
1361
+ * name and an attributes object to create the child it uses an
1362
+ * existing DOM element object.
1363
+ *
1364
+ * Parameters:
1365
+ * (XMLElement) elem - A DOM element.
1366
+ *
1367
+ * Returns:
1368
+ * The Strophe.Builder object.
1369
+ */
1370
+ cnode: function (elem)
1371
+ {
1372
+ var xmlGen = Strophe.xmlGenerator();
1373
+ try {
1374
+ var impNode = (xmlGen.importNode !== undefined);
1375
+ }
1376
+ catch (e) {
1377
+ var impNode = false;
1378
+ }
1379
+ var newElem = impNode ?
1380
+ xmlGen.importNode(elem, true) :
1381
+ Strophe.copyElement(elem);
1382
+ this.node.appendChild(newElem);
1383
+ this.node = newElem;
1384
+ return this;
1385
+ },
1386
+
1387
+ /** Function: t
1388
+ * Add a child text element.
1389
+ *
1390
+ * This *does not* make the child the new current element since there
1391
+ * are no children of text elements.
1392
+ *
1393
+ * Parameters:
1394
+ * (String) text - The text data to append to the current element.
1395
+ *
1396
+ * Returns:
1397
+ * The Strophe.Builder object.
1398
+ */
1399
+ t: function (text)
1400
+ {
1401
+ var child = Strophe.xmlTextNode(text);
1402
+ this.node.appendChild(child);
1403
+ return this;
1404
+ }
1405
+ };
1406
+
1407
+
1408
+ /** PrivateClass: Strophe.Handler
1409
+ * _Private_ helper class for managing stanza handlers.
1410
+ *
1411
+ * A Strophe.Handler encapsulates a user provided callback function to be
1412
+ * executed when matching stanzas are received by the connection.
1413
+ * Handlers can be either one-off or persistant depending on their
1414
+ * return value. Returning true will cause a Handler to remain active, and
1415
+ * returning false will remove the Handler.
1416
+ *
1417
+ * Users will not use Strophe.Handler objects directly, but instead they
1418
+ * will use Strophe.Connection.addHandler() and
1419
+ * Strophe.Connection.deleteHandler().
1420
+ */
1421
+
1422
+ /** PrivateConstructor: Strophe.Handler
1423
+ * Create and initialize a new Strophe.Handler.
1424
+ *
1425
+ * Parameters:
1426
+ * (Function) handler - A function to be executed when the handler is run.
1427
+ * (String) ns - The namespace to match.
1428
+ * (String) name - The element name to match.
1429
+ * (String) type - The element type to match.
1430
+ * (String) id - The element id attribute to match.
1431
+ * (String) from - The element from attribute to match.
1432
+ * (Object) options - Handler options
1433
+ *
1434
+ * Returns:
1435
+ * A new Strophe.Handler object.
1436
+ */
1437
+ Strophe.Handler = function (handler, ns, name, type, id, from, options)
1438
+ {
1439
+ this.handler = handler;
1440
+ this.ns = ns;
1441
+ this.name = name;
1442
+ this.type = type;
1443
+ this.id = id;
1444
+ this.options = options || {matchbare: false};
1445
+
1446
+ // default matchBare to false if undefined
1447
+ if (!this.options.matchBare) {
1448
+ this.options.matchBare = false;
1449
+ }
1450
+
1451
+ if (this.options.matchBare) {
1452
+ this.from = from ? Strophe.getBareJidFromJid(from) : null;
1453
+ } else {
1454
+ this.from = from;
1455
+ }
1456
+
1457
+ // whether the handler is a user handler or a system handler
1458
+ this.user = true;
1459
+ };
1460
+
1461
+ Strophe.Handler.prototype = {
1462
+ /** PrivateFunction: isMatch
1463
+ * Tests if a stanza matches the Strophe.Handler.
1464
+ *
1465
+ * Parameters:
1466
+ * (XMLElement) elem - The XML element to test.
1467
+ *
1468
+ * Returns:
1469
+ * true if the stanza matches and false otherwise.
1470
+ */
1471
+ isMatch: function (elem)
1472
+ {
1473
+ var nsMatch;
1474
+ var from = null;
1475
+
1476
+ if (this.options.matchBare) {
1477
+ from = Strophe.getBareJidFromJid(elem.getAttribute('from'));
1478
+ } else {
1479
+ from = elem.getAttribute('from');
1480
+ }
1481
+
1482
+ nsMatch = false;
1483
+ if (!this.ns) {
1484
+ nsMatch = true;
1485
+ } else {
1486
+ var that = this;
1487
+ Strophe.forEachChild(elem, null, function (elem) {
1488
+ if (elem.getAttribute("xmlns") == that.ns) {
1489
+ nsMatch = true;
1490
+ }
1491
+ });
1492
+
1493
+ nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns;
1494
+ }
1495
+
1496
+ if (nsMatch &&
1497
+ (!this.name || Strophe.isTagEqual(elem, this.name)) &&
1498
+ (!this.type || elem.getAttribute("type") == this.type) &&
1499
+ (!this.id || elem.getAttribute("id") == this.id) &&
1500
+ (!this.from || from == this.from)) {
1501
+ return true;
1502
+ }
1503
+
1504
+ return false;
1505
+ },
1506
+
1507
+ /** PrivateFunction: run
1508
+ * Run the callback on a matching stanza.
1509
+ *
1510
+ * Parameters:
1511
+ * (XMLElement) elem - The DOM element that triggered the
1512
+ * Strophe.Handler.
1513
+ *
1514
+ * Returns:
1515
+ * A boolean indicating if the handler should remain active.
1516
+ */
1517
+ run: function (elem)
1518
+ {
1519
+ var result = null;
1520
+ try {
1521
+ result = this.handler(elem);
1522
+ } catch (e) {
1523
+ if (e.sourceURL) {
1524
+ Strophe.fatal("error: " + this.handler +
1525
+ " " + e.sourceURL + ":" +
1526
+ e.line + " - " + e.name + ": " + e.message);
1527
+ } else if (e.fileName) {
1528
+ if (typeof(console) != "undefined") {
1529
+ console.trace();
1530
+ console.error(this.handler, " - error - ", e, e.message);
1531
+ }
1532
+ Strophe.fatal("error: " + this.handler + " " +
1533
+ e.fileName + ":" + e.lineNumber + " - " +
1534
+ e.name + ": " + e.message);
1535
+ } else {
1536
+ Strophe.fatal("error: " + this.handler);
1537
+ }
1538
+
1539
+ throw e;
1540
+ }
1541
+
1542
+ return result;
1543
+ },
1544
+
1545
+ /** PrivateFunction: toString
1546
+ * Get a String representation of the Strophe.Handler object.
1547
+ *
1548
+ * Returns:
1549
+ * A String.
1550
+ */
1551
+ toString: function ()
1552
+ {
1553
+ return "{Handler: " + this.handler + "(" + this.name + "," +
1554
+ this.id + "," + this.ns + ")}";
1555
+ }
1556
+ };
1557
+
1558
+ /** PrivateClass: Strophe.TimedHandler
1559
+ * _Private_ helper class for managing timed handlers.
1560
+ *
1561
+ * A Strophe.TimedHandler encapsulates a user provided callback that
1562
+ * should be called after a certain period of time or at regular
1563
+ * intervals. The return value of the callback determines whether the
1564
+ * Strophe.TimedHandler will continue to fire.
1565
+ *
1566
+ * Users will not use Strophe.TimedHandler objects directly, but instead
1567
+ * they will use Strophe.Connection.addTimedHandler() and
1568
+ * Strophe.Connection.deleteTimedHandler().
1569
+ */
1570
+
1571
+ /** PrivateConstructor: Strophe.TimedHandler
1572
+ * Create and initialize a new Strophe.TimedHandler object.
1573
+ *
1574
+ * Parameters:
1575
+ * (Integer) period - The number of milliseconds to wait before the
1576
+ * handler is called.
1577
+ * (Function) handler - The callback to run when the handler fires. This
1578
+ * function should take no arguments.
1579
+ *
1580
+ * Returns:
1581
+ * A new Strophe.TimedHandler object.
1582
+ */
1583
+ Strophe.TimedHandler = function (period, handler)
1584
+ {
1585
+ this.period = period;
1586
+ this.handler = handler;
1587
+
1588
+ this.lastCalled = new Date().getTime();
1589
+ this.user = true;
1590
+ };
1591
+
1592
+ Strophe.TimedHandler.prototype = {
1593
+ /** PrivateFunction: run
1594
+ * Run the callback for the Strophe.TimedHandler.
1595
+ *
1596
+ * Returns:
1597
+ * true if the Strophe.TimedHandler should be called again, and false
1598
+ * otherwise.
1599
+ */
1600
+ run: function ()
1601
+ {
1602
+ this.lastCalled = new Date().getTime();
1603
+ return this.handler();
1604
+ },
1605
+
1606
+ /** PrivateFunction: reset
1607
+ * Reset the last called time for the Strophe.TimedHandler.
1608
+ */
1609
+ reset: function ()
1610
+ {
1611
+ this.lastCalled = new Date().getTime();
1612
+ },
1613
+
1614
+ /** PrivateFunction: toString
1615
+ * Get a string representation of the Strophe.TimedHandler object.
1616
+ *
1617
+ * Returns:
1618
+ * The string representation.
1619
+ */
1620
+ toString: function ()
1621
+ {
1622
+ return "{TimedHandler: " + this.handler + "(" + this.period +")}";
1623
+ }
1624
+ };
1625
+
1626
+ /** PrivateClass: Strophe.Request
1627
+ * _Private_ helper class that provides a cross implementation abstraction
1628
+ * for a BOSH related XMLHttpRequest.
1629
+ *
1630
+ * The Strophe.Request class is used internally to encapsulate BOSH request
1631
+ * information. It is not meant to be used from user's code.
1632
+ */
1633
+
1634
+ /** PrivateConstructor: Strophe.Request
1635
+ * Create and initialize a new Strophe.Request object.
1636
+ *
1637
+ * Parameters:
1638
+ * (XMLElement) elem - The XML data to be sent in the request.
1639
+ * (Function) func - The function that will be called when the
1640
+ * XMLHttpRequest readyState changes.
1641
+ * (Integer) rid - The BOSH rid attribute associated with this request.
1642
+ * (Integer) sends - The number of times this same request has been
1643
+ * sent.
1644
+ */
1645
+ Strophe.Request = function (elem, func, rid, sends)
1646
+ {
1647
+ this.id = ++Strophe._requestId;
1648
+ this.xmlData = elem;
1649
+ this.data = Strophe.serialize(elem);
1650
+ // save original function in case we need to make a new request
1651
+ // from this one.
1652
+ this.origFunc = func;
1653
+ this.func = func;
1654
+ this.rid = rid;
1655
+ this.date = NaN;
1656
+ this.sends = sends || 0;
1657
+ this.abort = false;
1658
+ this.dead = null;
1659
+ this.age = function () {
1660
+ if (!this.date) { return 0; }
1661
+ var now = new Date();
1662
+ return (now - this.date) / 1000;
1663
+ };
1664
+ this.timeDead = function () {
1665
+ if (!this.dead) { return 0; }
1666
+ var now = new Date();
1667
+ return (now - this.dead) / 1000;
1668
+ };
1669
+ this.xhr = this._newXHR();
1670
+ };
1671
+
1672
+ Strophe.Request.prototype = {
1673
+ /** PrivateFunction: getResponse
1674
+ * Get a response from the underlying XMLHttpRequest.
1675
+ *
1676
+ * This function attempts to get a response from the request and checks
1677
+ * for errors.
1678
+ *
1679
+ * Throws:
1680
+ * "parsererror" - A parser error occured.
1681
+ *
1682
+ * Returns:
1683
+ * The DOM element tree of the response.
1684
+ */
1685
+ getResponse: function ()
1686
+ {
1687
+ var node = null;
1688
+ if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
1689
+ node = this.xhr.responseXML.documentElement;
1690
+ if (node.tagName == "parsererror") {
1691
+ Strophe.error("invalid response received");
1692
+ Strophe.error("responseText: " + this.xhr.responseText);
1693
+ Strophe.error("responseXML: " +
1694
+ Strophe.serialize(this.xhr.responseXML));
1695
+ throw "parsererror";
1696
+ }
1697
+ } else if (this.xhr.responseText) {
1698
+ Strophe.error("invalid response received");
1699
+ Strophe.error("responseText: " + this.xhr.responseText);
1700
+ Strophe.error("responseXML: " +
1701
+ Strophe.serialize(this.xhr.responseXML));
1702
+ }
1703
+
1704
+ return node;
1705
+ },
1706
+
1707
+ /** PrivateFunction: _newXHR
1708
+ * _Private_ helper function to create XMLHttpRequests.
1709
+ *
1710
+ * This function creates XMLHttpRequests across all implementations.
1711
+ *
1712
+ * Returns:
1713
+ * A new XMLHttpRequest.
1714
+ */
1715
+ _newXHR: function ()
1716
+ {
1717
+ var xhr = null;
1718
+ if (window.XMLHttpRequest) {
1719
+ xhr = new XMLHttpRequest();
1720
+ if (xhr.overrideMimeType) {
1721
+ xhr.overrideMimeType("text/xml");
1722
+ }
1723
+ } else if (window.ActiveXObject) {
1724
+ xhr = new ActiveXObject("Microsoft.XMLHTTP");
1725
+ }
1726
+
1727
+ // use Function.bind() to prepend ourselves as an argument
1728
+ xhr.onreadystatechange = this.func.bind(null, this);
1729
+
1730
+ return xhr;
1731
+ }
1732
+ };
1733
+
1734
+ /** Class: Strophe.Connection
1735
+ * XMPP Connection manager.
1736
+ *
1737
+ * Thie class is the main part of Strophe. It manages a BOSH connection
1738
+ * to an XMPP server and dispatches events to the user callbacks as
1739
+ * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, and legacy
1740
+ * authentication.
1741
+ *
1742
+ * After creating a Strophe.Connection object, the user will typically
1743
+ * call connect() with a user supplied callback to handle connection level
1744
+ * events like authentication failure, disconnection, or connection
1745
+ * complete.
1746
+ *
1747
+ * The user will also have several event handlers defined by using
1748
+ * addHandler() and addTimedHandler(). These will allow the user code to
1749
+ * respond to interesting stanzas or do something periodically with the
1750
+ * connection. These handlers will be active once authentication is
1751
+ * finished.
1752
+ *
1753
+ * To send data to the connection, use send().
1754
+ */
1755
+
1756
+ /** Constructor: Strophe.Connection
1757
+ * Create and initialize a Strophe.Connection object.
1758
+ *
1759
+ * Parameters:
1760
+ * (String) service - The BOSH service URL.
1761
+ *
1762
+ * Returns:
1763
+ * A new Strophe.Connection object.
1764
+ */
1765
+ Strophe.Connection = function (service)
1766
+ {
1767
+ /* The path to the httpbind service. */
1768
+ this.service = service;
1769
+ /* The connected JID. */
1770
+ this.jid = "";
1771
+ /* request id for body tags */
1772
+ this.rid = Math.floor(Math.random() * 4294967295);
1773
+ /* The current session ID. */
1774
+ this.sid = null;
1775
+ this.streamId = null;
1776
+ /* stream:features */
1777
+ this.features = null;
1778
+
1779
+ // SASL
1780
+ this.do_session = false;
1781
+ this.do_bind = false;
1782
+
1783
+ // handler lists
1784
+ this.timedHandlers = [];
1785
+ this.handlers = [];
1786
+ this.removeTimeds = [];
1787
+ this.removeHandlers = [];
1788
+ this.addTimeds = [];
1789
+ this.addHandlers = [];
1790
+
1791
+ this._idleTimeout = null;
1792
+ this._disconnectTimeout = null;
1793
+
1794
+ this.authenticated = false;
1795
+ this.disconnecting = false;
1796
+ this.connected = false;
1797
+
1798
+ this.errors = 0;
1799
+
1800
+ this.paused = false;
1801
+
1802
+ // default BOSH values
1803
+ this.hold = 1;
1804
+ this.wait = 60;
1805
+ this.window = 5;
1806
+
1807
+ this._data = [];
1808
+ this._requests = [];
1809
+ this._uniqueId = Math.round(Math.random() * 10000);
1810
+
1811
+ this._sasl_success_handler = null;
1812
+ this._sasl_failure_handler = null;
1813
+ this._sasl_challenge_handler = null;
1814
+
1815
+ // setup onIdle callback every 1/10th of a second
1816
+ this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
1817
+
1818
+ // initialize plugins
1819
+ for (var k in Strophe._connectionPlugins) {
1820
+ if (Strophe._connectionPlugins.hasOwnProperty(k)) {
1821
+ var ptype = Strophe._connectionPlugins[k];
1822
+ // jslint complaints about the below line, but this is fine
1823
+ var F = function () {};
1824
+ F.prototype = ptype;
1825
+ this[k] = new F();
1826
+ this[k].init(this);
1827
+ }
1828
+ }
1829
+ };
1830
+
1831
+ Strophe.Connection.prototype = {
1832
+ /** Function: reset
1833
+ * Reset the connection.
1834
+ *
1835
+ * This function should be called after a connection is disconnected
1836
+ * before that connection is reused.
1837
+ */
1838
+ reset: function ()
1839
+ {
1840
+ this.rid = Math.floor(Math.random() * 4294967295);
1841
+
1842
+ this.sid = null;
1843
+ this.streamId = null;
1844
+
1845
+ // SASL
1846
+ this.do_session = false;
1847
+ this.do_bind = false;
1848
+
1849
+ // handler lists
1850
+ this.timedHandlers = [];
1851
+ this.handlers = [];
1852
+ this.removeTimeds = [];
1853
+ this.removeHandlers = [];
1854
+ this.addTimeds = [];
1855
+ this.addHandlers = [];
1856
+
1857
+ this.authenticated = false;
1858
+ this.disconnecting = false;
1859
+ this.connected = false;
1860
+
1861
+ this.errors = 0;
1862
+
1863
+ this._requests = [];
1864
+ this._uniqueId = Math.round(Math.random()*10000);
1865
+ },
1866
+
1867
+ /** Function: pause
1868
+ * Pause the request manager.
1869
+ *
1870
+ * This will prevent Strophe from sending any more requests to the
1871
+ * server. This is very useful for temporarily pausing while a lot
1872
+ * of send() calls are happening quickly. This causes Strophe to
1873
+ * send the data in a single request, saving many request trips.
1874
+ */
1875
+ pause: function ()
1876
+ {
1877
+ this.paused = true;
1878
+ },
1879
+
1880
+ /** Function: resume
1881
+ * Resume the request manager.
1882
+ *
1883
+ * This resumes after pause() has been called.
1884
+ */
1885
+ resume: function ()
1886
+ {
1887
+ this.paused = false;
1888
+ },
1889
+
1890
+ /** Function: getUniqueId
1891
+ * Generate a unique ID for use in <iq/> elements.
1892
+ *
1893
+ * All <iq/> stanzas are required to have unique id attributes. This
1894
+ * function makes creating these easy. Each connection instance has
1895
+ * a counter which starts from zero, and the value of this counter
1896
+ * plus a colon followed by the suffix becomes the unique id. If no
1897
+ * suffix is supplied, the counter is used as the unique id.
1898
+ *
1899
+ * Suffixes are used to make debugging easier when reading the stream
1900
+ * data, and their use is recommended. The counter resets to 0 for
1901
+ * every new connection for the same reason. For connections to the
1902
+ * same server that authenticate the same way, all the ids should be
1903
+ * the same, which makes it easy to see changes. This is useful for
1904
+ * automated testing as well.
1905
+ *
1906
+ * Parameters:
1907
+ * (String) suffix - A optional suffix to append to the id.
1908
+ *
1909
+ * Returns:
1910
+ * A unique string to be used for the id attribute.
1911
+ */
1912
+ getUniqueId: function (suffix)
1913
+ {
1914
+ if (typeof(suffix) == "string" || typeof(suffix) == "number") {
1915
+ return ++this._uniqueId + ":" + suffix;
1916
+ } else {
1917
+ return ++this._uniqueId + "";
1918
+ }
1919
+ },
1920
+
1921
+ /** Function: connect
1922
+ * Starts the connection process.
1923
+ *
1924
+ * As the connection process proceeds, the user supplied callback will
1925
+ * be triggered multiple times with status updates. The callback
1926
+ * should take two arguments - the status code and the error condition.
1927
+ *
1928
+ * The status code will be one of the values in the Strophe.Status
1929
+ * constants. The error condition will be one of the conditions
1930
+ * defined in RFC 3920 or the condition 'strophe-parsererror'.
1931
+ *
1932
+ * Please see XEP 124 for a more detailed explanation of the optional
1933
+ * parameters below.
1934
+ *
1935
+ * Parameters:
1936
+ * (String) jid - The user's JID. This may be a bare JID,
1937
+ * or a full JID. If a node is not supplied, SASL ANONYMOUS
1938
+ * authentication will be attempted.
1939
+ * (String) pass - The user's password.
1940
+ * (Function) callback - The connect callback function.
1941
+ * (Integer) wait - The optional HTTPBIND wait value. This is the
1942
+ * time the server will wait before returning an empty result for
1943
+ * a request. The default setting of 60 seconds is recommended.
1944
+ * Other settings will require tweaks to the Strophe.TIMEOUT value.
1945
+ * (Integer) hold - The optional HTTPBIND hold value. This is the
1946
+ * number of connections the server will hold at one time. This
1947
+ * should almost always be set to 1 (the default).
1948
+ */
1949
+ connect: function (jid, pass, callback, wait, hold)
1950
+ {
1951
+ this.jid = jid;
1952
+ this.pass = pass;
1953
+ this.connect_callback = callback;
1954
+ this.disconnecting = false;
1955
+ this.connected = false;
1956
+ this.authenticated = false;
1957
+ this.errors = 0;
1958
+
1959
+ this.wait = wait || this.wait;
1960
+ this.hold = hold || this.hold;
1961
+
1962
+ // parse jid for domain and resource
1963
+ this.domain = Strophe.getDomainFromJid(this.jid);
1964
+
1965
+ // build the body tag
1966
+ var body = this._buildBody().attrs({
1967
+ to: this.domain,
1968
+ "xml:lang": "en",
1969
+ wait: this.wait,
1970
+ hold: this.hold,
1971
+ content: "text/xml; charset=utf-8",
1972
+ ver: "1.6",
1973
+ "xmpp:version": "1.0",
1974
+ "xmlns:xmpp": Strophe.NS.BOSH
1975
+ });
1976
+
1977
+ this._changeConnectStatus(Strophe.Status.CONNECTING, null);
1978
+
1979
+ this._requests.push(
1980
+ new Strophe.Request(body.tree(),
1981
+ this._onRequestStateChange.bind(
1982
+ this, this._connect_cb.bind(this)),
1983
+ body.tree().getAttribute("rid")));
1984
+ this._throttledRequestHandler();
1985
+ },
1986
+
1987
+ /** Function: attach
1988
+ * Attach to an already created and authenticated BOSH session.
1989
+ *
1990
+ * This function is provided to allow Strophe to attach to BOSH
1991
+ * sessions which have been created externally, perhaps by a Web
1992
+ * application. This is often used to support auto-login type features
1993
+ * without putting user credentials into the page.
1994
+ *
1995
+ * Parameters:
1996
+ * (String) jid - The full JID that is bound by the session.
1997
+ * (String) sid - The SID of the BOSH session.
1998
+ * (String) rid - The current RID of the BOSH session. This RID
1999
+ * will be used by the next request.
2000
+ * (Function) callback The connect callback function.
2001
+ * (Integer) wait - The optional HTTPBIND wait value. This is the
2002
+ * time the server will wait before returning an empty result for
2003
+ * a request. The default setting of 60 seconds is recommended.
2004
+ * Other settings will require tweaks to the Strophe.TIMEOUT value.
2005
+ * (Integer) hold - The optional HTTPBIND hold value. This is the
2006
+ * number of connections the server will hold at one time. This
2007
+ * should almost always be set to 1 (the default).
2008
+ * (Integer) wind - The optional HTTBIND window value. This is the
2009
+ * allowed range of request ids that are valid. The default is 5.
2010
+ */
2011
+ attach: function (jid, sid, rid, callback, wait, hold, wind)
2012
+ {
2013
+ this.jid = jid;
2014
+ this.sid = sid;
2015
+ this.rid = rid;
2016
+ this.connect_callback = callback;
2017
+
2018
+ this.domain = Strophe.getDomainFromJid(this.jid);
2019
+
2020
+ this.authenticated = true;
2021
+ this.connected = true;
2022
+
2023
+ this.wait = wait || this.wait;
2024
+ this.hold = hold || this.hold;
2025
+ this.window = wind || this.window;
2026
+
2027
+ this._changeConnectStatus(Strophe.Status.ATTACHED, null);
2028
+ },
2029
+
2030
+ /** Function: xmlInput
2031
+ * User overrideable function that receives XML data coming into the
2032
+ * connection.
2033
+ *
2034
+ * The default function does nothing. User code can override this with
2035
+ * > Strophe.Connection.xmlInput = function (elem) {
2036
+ * > (user code)
2037
+ * > };
2038
+ *
2039
+ * Parameters:
2040
+ * (XMLElement) elem - The XML data received by the connection.
2041
+ */
2042
+ xmlInput: function (elem)
2043
+ {
2044
+ return;
2045
+ },
2046
+
2047
+ /** Function: xmlOutput
2048
+ * User overrideable function that receives XML data sent to the
2049
+ * connection.
2050
+ *
2051
+ * The default function does nothing. User code can override this with
2052
+ * > Strophe.Connection.xmlOutput = function (elem) {
2053
+ * > (user code)
2054
+ * > };
2055
+ *
2056
+ * Parameters:
2057
+ * (XMLElement) elem - The XMLdata sent by the connection.
2058
+ */
2059
+ xmlOutput: function (elem)
2060
+ {
2061
+ return;
2062
+ },
2063
+
2064
+ /** Function: rawInput
2065
+ * User overrideable function that receives raw data coming into the
2066
+ * connection.
2067
+ *
2068
+ * The default function does nothing. User code can override this with
2069
+ * > Strophe.Connection.rawInput = function (data) {
2070
+ * > (user code)
2071
+ * > };
2072
+ *
2073
+ * Parameters:
2074
+ * (String) data - The data received by the connection.
2075
+ */
2076
+ rawInput: function (data)
2077
+ {
2078
+ return;
2079
+ },
2080
+
2081
+ /** Function: rawOutput
2082
+ * User overrideable function that receives raw data sent to the
2083
+ * connection.
2084
+ *
2085
+ * The default function does nothing. User code can override this with
2086
+ * > Strophe.Connection.rawOutput = function (data) {
2087
+ * > (user code)
2088
+ * > };
2089
+ *
2090
+ * Parameters:
2091
+ * (String) data - The data sent by the connection.
2092
+ */
2093
+ rawOutput: function (data)
2094
+ {
2095
+ return;
2096
+ },
2097
+
2098
+ /** Function: send
2099
+ * Send a stanza.
2100
+ *
2101
+ * This function is called to push data onto the send queue to
2102
+ * go out over the wire. Whenever a request is sent to the BOSH
2103
+ * server, all pending data is sent and the queue is flushed.
2104
+ *
2105
+ * Parameters:
2106
+ * (XMLElement |
2107
+ * [XMLElement] |
2108
+ * Strophe.Builder) elem - The stanza to send.
2109
+ */
2110
+ send: function (elem)
2111
+ {
2112
+ if (elem === null) { return ; }
2113
+ if (typeof(elem.sort) === "function") {
2114
+ for (var i = 0; i < elem.length; i++) {
2115
+ this._queueData(elem[i]);
2116
+ }
2117
+ } else if (typeof(elem.tree) === "function") {
2118
+ this._queueData(elem.tree());
2119
+ } else {
2120
+ this._queueData(elem);
2121
+ }
2122
+
2123
+ this._throttledRequestHandler();
2124
+ clearTimeout(this._idleTimeout);
2125
+ this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
2126
+ },
2127
+
2128
+ /** Function: flush
2129
+ * Immediately send any pending outgoing data.
2130
+ *
2131
+ * Normally send() queues outgoing data until the next idle period
2132
+ * (100ms), which optimizes network use in the common cases when
2133
+ * several send()s are called in succession. flush() can be used to
2134
+ * immediately send all pending data.
2135
+ */
2136
+ flush: function ()
2137
+ {
2138
+ // cancel the pending idle period and run the idle function
2139
+ // immediately
2140
+ clearTimeout(this._idleTimeout);
2141
+ this._onIdle();
2142
+ },
2143
+
2144
+ /** Function: sendIQ
2145
+ * Helper function to send IQ stanzas.
2146
+ *
2147
+ * Parameters:
2148
+ * (XMLElement) elem - The stanza to send.
2149
+ * (Function) callback - The callback function for a successful request.
2150
+ * (Function) errback - The callback function for a failed or timed
2151
+ * out request. On timeout, the stanza will be null.
2152
+ * (Integer) timeout - The time specified in milliseconds for a
2153
+ * timeout to occur.
2154
+ *
2155
+ * Returns:
2156
+ * The id used to send the IQ.
2157
+ */
2158
+ sendIQ: function(elem, callback, errback, timeout) {
2159
+ var timeoutHandler = null;
2160
+ var that = this;
2161
+
2162
+ if (typeof(elem.tree) === "function") {
2163
+ elem = elem.tree();
2164
+ }
2165
+ var id = elem.getAttribute('id');
2166
+
2167
+ // inject id if not found
2168
+ if (!id) {
2169
+ id = this.getUniqueId("sendIQ");
2170
+ elem.setAttribute("id", id);
2171
+ }
2172
+
2173
+ var handler = this.addHandler(function (stanza) {
2174
+ // remove timeout handler if there is one
2175
+ if (timeoutHandler) {
2176
+ that.deleteTimedHandler(timeoutHandler);
2177
+ }
2178
+
2179
+ var iqtype = stanza.getAttribute('type');
2180
+ if (iqtype == 'result') {
2181
+ if (callback) {
2182
+ callback(stanza);
2183
+ }
2184
+ } else if (iqtype == 'error') {
2185
+ if (errback) {
2186
+ errback(stanza);
2187
+ }
2188
+ } else {
2189
+ throw {
2190
+ name: "StropheError",
2191
+ message: "Got bad IQ type of " + iqtype
2192
+ };
2193
+ }
2194
+ }, null, 'iq', null, id);
2195
+
2196
+ // if timeout specified, setup timeout handler.
2197
+ if (timeout) {
2198
+ timeoutHandler = this.addTimedHandler(timeout, function () {
2199
+ // get rid of normal handler
2200
+ that.deleteHandler(handler);
2201
+
2202
+ // call errback on timeout with null stanza
2203
+ if (errback) {
2204
+ errback(null);
2205
+ }
2206
+ return false;
2207
+ });
2208
+ }
2209
+
2210
+ this.send(elem);
2211
+
2212
+ return id;
2213
+ },
2214
+
2215
+ /** PrivateFunction: _queueData
2216
+ * Queue outgoing data for later sending. Also ensures that the data
2217
+ * is a DOMElement.
2218
+ */
2219
+ _queueData: function (element) {
2220
+ if (element === null ||
2221
+ !element.tagName ||
2222
+ !element.childNodes) {
2223
+ throw {
2224
+ name: "StropheError",
2225
+ message: "Cannot queue non-DOMElement."
2226
+ };
2227
+ }
2228
+
2229
+ this._data.push(element);
2230
+ },
2231
+
2232
+ /** PrivateFunction: _sendRestart
2233
+ * Send an xmpp:restart stanza.
2234
+ */
2235
+ _sendRestart: function ()
2236
+ {
2237
+ this._data.push("restart");
2238
+
2239
+ this._throttledRequestHandler();
2240
+ clearTimeout(this._idleTimeout);
2241
+ this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
2242
+ },
2243
+
2244
+ /** Function: addTimedHandler
2245
+ * Add a timed handler to the connection.
2246
+ *
2247
+ * This function adds a timed handler. The provided handler will
2248
+ * be called every period milliseconds until it returns false,
2249
+ * the connection is terminated, or the handler is removed. Handlers
2250
+ * that wish to continue being invoked should return true.
2251
+ *
2252
+ * Because of method binding it is necessary to save the result of
2253
+ * this function if you wish to remove a handler with
2254
+ * deleteTimedHandler().
2255
+ *
2256
+ * Note that user handlers are not active until authentication is
2257
+ * successful.
2258
+ *
2259
+ * Parameters:
2260
+ * (Integer) period - The period of the handler.
2261
+ * (Function) handler - The callback function.
2262
+ *
2263
+ * Returns:
2264
+ * A reference to the handler that can be used to remove it.
2265
+ */
2266
+ addTimedHandler: function (period, handler)
2267
+ {
2268
+ var thand = new Strophe.TimedHandler(period, handler);
2269
+ this.addTimeds.push(thand);
2270
+ return thand;
2271
+ },
2272
+
2273
+ /** Function: deleteTimedHandler
2274
+ * Delete a timed handler for a connection.
2275
+ *
2276
+ * This function removes a timed handler from the connection. The
2277
+ * handRef parameter is *not* the function passed to addTimedHandler(),
2278
+ * but is the reference returned from addTimedHandler().
2279
+ *
2280
+ * Parameters:
2281
+ * (Strophe.TimedHandler) handRef - The handler reference.
2282
+ */
2283
+ deleteTimedHandler: function (handRef)
2284
+ {
2285
+ // this must be done in the Idle loop so that we don't change
2286
+ // the handlers during iteration
2287
+ this.removeTimeds.push(handRef);
2288
+ },
2289
+
2290
+ /** Function: addHandler
2291
+ * Add a stanza handler for the connection.
2292
+ *
2293
+ * This function adds a stanza handler to the connection. The
2294
+ * handler callback will be called for any stanza that matches
2295
+ * the parameters. Note that if multiple parameters are supplied,
2296
+ * they must all match for the handler to be invoked.
2297
+ *
2298
+ * The handler will receive the stanza that triggered it as its argument.
2299
+ * The handler should return true if it is to be invoked again;
2300
+ * returning false will remove the handler after it returns.
2301
+ *
2302
+ * As a convenience, the ns parameters applies to the top level element
2303
+ * and also any of its immediate children. This is primarily to make
2304
+ * matching /iq/query elements easy.
2305
+ *
2306
+ * The options argument contains handler matching flags that affect how
2307
+ * matches are determined. Currently the only flag is matchBare (a
2308
+ * boolean). When matchBare is true, the from parameter and the from
2309
+ * attribute on the stanza will be matched as bare JIDs instead of
2310
+ * full JIDs. To use this, pass {matchBare: true} as the value of
2311
+ * options. The default value for matchBare is false.
2312
+ *
2313
+ * The return value should be saved if you wish to remove the handler
2314
+ * with deleteHandler().
2315
+ *
2316
+ * Parameters:
2317
+ * (Function) handler - The user callback.
2318
+ * (String) ns - The namespace to match.
2319
+ * (String) name - The stanza name to match.
2320
+ * (String) type - The stanza type attribute to match.
2321
+ * (String) id - The stanza id attribute to match.
2322
+ * (String) from - The stanza from attribute to match.
2323
+ * (String) options - The handler options
2324
+ *
2325
+ * Returns:
2326
+ * A reference to the handler that can be used to remove it.
2327
+ */
2328
+ addHandler: function (handler, ns, name, type, id, from, options)
2329
+ {
2330
+ var hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
2331
+ this.addHandlers.push(hand);
2332
+ return hand;
2333
+ },
2334
+
2335
+ /** Function: deleteHandler
2336
+ * Delete a stanza handler for a connection.
2337
+ *
2338
+ * This function removes a stanza handler from the connection. The
2339
+ * handRef parameter is *not* the function passed to addHandler(),
2340
+ * but is the reference returned from addHandler().
2341
+ *
2342
+ * Parameters:
2343
+ * (Strophe.Handler) handRef - The handler reference.
2344
+ */
2345
+ deleteHandler: function (handRef)
2346
+ {
2347
+ // this must be done in the Idle loop so that we don't change
2348
+ // the handlers during iteration
2349
+ this.removeHandlers.push(handRef);
2350
+ },
2351
+
2352
+ /** Function: disconnect
2353
+ * Start the graceful disconnection process.
2354
+ *
2355
+ * This function starts the disconnection process. This process starts
2356
+ * by sending unavailable presence and sending BOSH body of type
2357
+ * terminate. A timeout handler makes sure that disconnection happens
2358
+ * even if the BOSH server does not respond.
2359
+ *
2360
+ * The user supplied connection callback will be notified of the
2361
+ * progress as this process happens.
2362
+ *
2363
+ * Parameters:
2364
+ * (String) reason - The reason the disconnect is occuring.
2365
+ */
2366
+ disconnect: function (reason)
2367
+ {
2368
+ this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
2369
+
2370
+ Strophe.info("Disconnect was called because: " + reason);
2371
+ if (this.connected) {
2372
+ // setup timeout handler
2373
+ this._disconnectTimeout = this._addSysTimedHandler(
2374
+ 3000, this._onDisconnectTimeout.bind(this));
2375
+ this._sendTerminate();
2376
+ }
2377
+ },
2378
+
2379
+ /** PrivateFunction: _changeConnectStatus
2380
+ * _Private_ helper function that makes sure plugins and the user's
2381
+ * callback are notified of connection status changes.
2382
+ *
2383
+ * Parameters:
2384
+ * (Integer) status - the new connection status, one of the values
2385
+ * in Strophe.Status
2386
+ * (String) condition - the error condition or null
2387
+ */
2388
+ _changeConnectStatus: function (status, condition)
2389
+ {
2390
+ // notify all plugins listening for status changes
2391
+ for (var k in Strophe._connectionPlugins) {
2392
+ if (Strophe._connectionPlugins.hasOwnProperty(k)) {
2393
+ var plugin = this[k];
2394
+ if (plugin.statusChanged) {
2395
+ try {
2396
+ plugin.statusChanged(status, condition);
2397
+ } catch (err) {
2398
+ Strophe.error("" + k + " plugin caused an exception " +
2399
+ "changing status: " + err);
2400
+ }
2401
+ }
2402
+ }
2403
+ }
2404
+
2405
+ // notify the user's callback
2406
+ if (this.connect_callback) {
2407
+ try {
2408
+ this.connect_callback(status, condition);
2409
+ } catch (e) {
2410
+ Strophe.error("User connection callback caused an " +
2411
+ "exception: " + e);
2412
+ }
2413
+ }
2414
+ },
2415
+
2416
+ /** PrivateFunction: _buildBody
2417
+ * _Private_ helper function to generate the <body/> wrapper for BOSH.
2418
+ *
2419
+ * Returns:
2420
+ * A Strophe.Builder with a <body/> element.
2421
+ */
2422
+ _buildBody: function ()
2423
+ {
2424
+ var bodyWrap = $build('body', {
2425
+ rid: this.rid++,
2426
+ xmlns: Strophe.NS.HTTPBIND
2427
+ });
2428
+
2429
+ if (this.sid !== null) {
2430
+ bodyWrap.attrs({sid: this.sid});
2431
+ }
2432
+
2433
+ return bodyWrap;
2434
+ },
2435
+
2436
+ /** PrivateFunction: _removeRequest
2437
+ * _Private_ function to remove a request from the queue.
2438
+ *
2439
+ * Parameters:
2440
+ * (Strophe.Request) req - The request to remove.
2441
+ */
2442
+ _removeRequest: function (req)
2443
+ {
2444
+ Strophe.debug("removing request");
2445
+
2446
+ var i;
2447
+ for (i = this._requests.length - 1; i >= 0; i--) {
2448
+ if (req == this._requests[i]) {
2449
+ this._requests.splice(i, 1);
2450
+ }
2451
+ }
2452
+
2453
+ // IE6 fails on setting to null, so set to empty function
2454
+ req.xhr.onreadystatechange = function () {};
2455
+
2456
+ this._throttledRequestHandler();
2457
+ },
2458
+
2459
+ /** PrivateFunction: _restartRequest
2460
+ * _Private_ function to restart a request that is presumed dead.
2461
+ *
2462
+ * Parameters:
2463
+ * (Integer) i - The index of the request in the queue.
2464
+ */
2465
+ _restartRequest: function (i)
2466
+ {
2467
+ var req = this._requests[i];
2468
+ if (req.dead === null) {
2469
+ req.dead = new Date();
2470
+ }
2471
+
2472
+ this._processRequest(i);
2473
+ },
2474
+
2475
+ /** PrivateFunction: _processRequest
2476
+ * _Private_ function to process a request in the queue.
2477
+ *
2478
+ * This function takes requests off the queue and sends them and
2479
+ * restarts dead requests.
2480
+ *
2481
+ * Parameters:
2482
+ * (Integer) i - The index of the request in the queue.
2483
+ */
2484
+ _processRequest: function (i)
2485
+ {
2486
+ var req = this._requests[i];
2487
+ var reqStatus = -1;
2488
+
2489
+ try {
2490
+ if (req.xhr.readyState == 4) {
2491
+ reqStatus = req.xhr.status;
2492
+ }
2493
+ } catch (e) {
2494
+ Strophe.error("caught an error in _requests[" + i +
2495
+ "], reqStatus: " + reqStatus);
2496
+ }
2497
+
2498
+ if (typeof(reqStatus) == "undefined") {
2499
+ reqStatus = -1;
2500
+ }
2501
+
2502
+ // make sure we limit the number of retries
2503
+ if (req.sends > 5) {
2504
+ this._onDisconnectTimeout();
2505
+ return;
2506
+ }
2507
+
2508
+ var time_elapsed = req.age();
2509
+ var primaryTimeout = (!isNaN(time_elapsed) &&
2510
+ time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
2511
+ var secondaryTimeout = (req.dead !== null &&
2512
+ req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
2513
+ var requestCompletedWithServerError = (req.xhr.readyState == 4 &&
2514
+ (reqStatus < 1 ||
2515
+ reqStatus >= 500));
2516
+ if (primaryTimeout || secondaryTimeout ||
2517
+ requestCompletedWithServerError) {
2518
+ if (secondaryTimeout) {
2519
+ Strophe.error("Request " +
2520
+ this._requests[i].id +
2521
+ " timed out (secondary), restarting");
2522
+ }
2523
+ req.abort = true;
2524
+ req.xhr.abort();
2525
+ // setting to null fails on IE6, so set to empty function
2526
+ req.xhr.onreadystatechange = function () {};
2527
+ this._requests[i] = new Strophe.Request(req.xmlData,
2528
+ req.origFunc,
2529
+ req.rid,
2530
+ req.sends);
2531
+ req = this._requests[i];
2532
+ }
2533
+
2534
+ if (req.xhr.readyState === 0) {
2535
+ Strophe.debug("request id " + req.id +
2536
+ "." + req.sends + " posting");
2537
+
2538
+ try {
2539
+ req.xhr.open("POST", this.service, true);
2540
+ } catch (e2) {
2541
+ Strophe.error("XHR open failed.");
2542
+ if (!this.connected) {
2543
+ this._changeConnectStatus(Strophe.Status.CONNFAIL,
2544
+ "bad-service");
2545
+ }
2546
+ this.disconnect();
2547
+ return;
2548
+ }
2549
+
2550
+ // Fires the XHR request -- may be invoked immediately
2551
+ // or on a gradually expanding retry window for reconnects
2552
+ var sendFunc = function () {
2553
+ req.date = new Date();
2554
+ req.xhr.send(req.data);
2555
+ };
2556
+
2557
+ // Implement progressive backoff for reconnects --
2558
+ // First retry (send == 1) should also be instantaneous
2559
+ if (req.sends > 1) {
2560
+ // Using a cube of the retry number creates a nicely
2561
+ // expanding retry window
2562
+ var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
2563
+ Math.pow(req.sends, 3)) * 1000;
2564
+ setTimeout(sendFunc, backoff);
2565
+ } else {
2566
+ sendFunc();
2567
+ }
2568
+
2569
+ req.sends++;
2570
+
2571
+ if (this.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
2572
+ this.xmlOutput(req.xmlData);
2573
+ }
2574
+ if (this.rawOutput !== Strophe.Connection.prototype.rawOutput) {
2575
+ this.rawOutput(req.data);
2576
+ }
2577
+ } else {
2578
+ Strophe.debug("_processRequest: " +
2579
+ (i === 0 ? "first" : "second") +
2580
+ " request has readyState of " +
2581
+ req.xhr.readyState);
2582
+ }
2583
+ },
2584
+
2585
+ /** PrivateFunction: _throttledRequestHandler
2586
+ * _Private_ function to throttle requests to the connection window.
2587
+ *
2588
+ * This function makes sure we don't send requests so fast that the
2589
+ * request ids overflow the connection window in the case that one
2590
+ * request died.
2591
+ */
2592
+ _throttledRequestHandler: function ()
2593
+ {
2594
+ if (!this._requests) {
2595
+ Strophe.debug("_throttledRequestHandler called with " +
2596
+ "undefined requests");
2597
+ } else {
2598
+ Strophe.debug("_throttledRequestHandler called with " +
2599
+ this._requests.length + " requests");
2600
+ }
2601
+
2602
+ if (!this._requests || this._requests.length === 0) {
2603
+ return;
2604
+ }
2605
+
2606
+ if (this._requests.length > 0) {
2607
+ this._processRequest(0);
2608
+ }
2609
+
2610
+ if (this._requests.length > 1 &&
2611
+ Math.abs(this._requests[0].rid -
2612
+ this._requests[1].rid) < this.window) {
2613
+ this._processRequest(1);
2614
+ }
2615
+ },
2616
+
2617
+ /** PrivateFunction: _onRequestStateChange
2618
+ * _Private_ handler for Strophe.Request state changes.
2619
+ *
2620
+ * This function is called when the XMLHttpRequest readyState changes.
2621
+ * It contains a lot of error handling logic for the many ways that
2622
+ * requests can fail, and calls the request callback when requests
2623
+ * succeed.
2624
+ *
2625
+ * Parameters:
2626
+ * (Function) func - The handler for the request.
2627
+ * (Strophe.Request) req - The request that is changing readyState.
2628
+ */
2629
+ _onRequestStateChange: function (func, req)
2630
+ {
2631
+ Strophe.debug("request id " + req.id +
2632
+ "." + req.sends + " state changed to " +
2633
+ req.xhr.readyState);
2634
+
2635
+ if (req.abort) {
2636
+ req.abort = false;
2637
+ return;
2638
+ }
2639
+
2640
+ // request complete
2641
+ var reqStatus;
2642
+ if (req.xhr.readyState == 4) {
2643
+ reqStatus = 0;
2644
+ try {
2645
+ reqStatus = req.xhr.status;
2646
+ } catch (e) {
2647
+ // ignore errors from undefined status attribute. works
2648
+ // around a browser bug
2649
+ }
2650
+
2651
+ if (typeof(reqStatus) == "undefined") {
2652
+ reqStatus = 0;
2653
+ }
2654
+
2655
+ if (this.disconnecting) {
2656
+ if (reqStatus >= 400) {
2657
+ this._hitError(reqStatus);
2658
+ return;
2659
+ }
2660
+ }
2661
+
2662
+ var reqIs0 = (this._requests[0] == req);
2663
+ var reqIs1 = (this._requests[1] == req);
2664
+
2665
+ if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) {
2666
+ // remove from internal queue
2667
+ this._removeRequest(req);
2668
+ Strophe.debug("request id " +
2669
+ req.id +
2670
+ " should now be removed");
2671
+ }
2672
+
2673
+ // request succeeded
2674
+ if (reqStatus == 200) {
2675
+ // if request 1 finished, or request 0 finished and request
2676
+ // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
2677
+ // restart the other - both will be in the first spot, as the
2678
+ // completed request has been removed from the queue already
2679
+ if (reqIs1 ||
2680
+ (reqIs0 && this._requests.length > 0 &&
2681
+ this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) {
2682
+ this._restartRequest(0);
2683
+ }
2684
+ // call handler
2685
+ Strophe.debug("request id " +
2686
+ req.id + "." +
2687
+ req.sends + " got 200");
2688
+ func(req);
2689
+ this.errors = 0;
2690
+ } else {
2691
+ Strophe.error("request id " +
2692
+ req.id + "." +
2693
+ req.sends + " error " + reqStatus +
2694
+ " happened");
2695
+ if (reqStatus === 0 ||
2696
+ (reqStatus >= 400 && reqStatus < 600) ||
2697
+ reqStatus >= 12000) {
2698
+ this._hitError(reqStatus);
2699
+ if (reqStatus >= 400 && reqStatus < 500) {
2700
+ this._changeConnectStatus(Strophe.Status.DISCONNECTING,
2701
+ null);
2702
+ this._doDisconnect();
2703
+ }
2704
+ }
2705
+ }
2706
+
2707
+ if (!((reqStatus > 0 && reqStatus < 500) ||
2708
+ req.sends > 5)) {
2709
+ this._throttledRequestHandler();
2710
+ }
2711
+ }
2712
+ },
2713
+
2714
+ /** PrivateFunction: _hitError
2715
+ * _Private_ function to handle the error count.
2716
+ *
2717
+ * Requests are resent automatically until their error count reaches
2718
+ * 5. Each time an error is encountered, this function is called to
2719
+ * increment the count and disconnect if the count is too high.
2720
+ *
2721
+ * Parameters:
2722
+ * (Integer) reqStatus - The request status.
2723
+ */
2724
+ _hitError: function (reqStatus)
2725
+ {
2726
+ this.errors++;
2727
+ Strophe.warn("request errored, status: " + reqStatus +
2728
+ ", number of errors: " + this.errors);
2729
+ if (this.errors > 4) {
2730
+ this._onDisconnectTimeout();
2731
+ }
2732
+ },
2733
+
2734
+ /** PrivateFunction: _doDisconnect
2735
+ * _Private_ function to disconnect.
2736
+ *
2737
+ * This is the last piece of the disconnection logic. This resets the
2738
+ * connection and alerts the user's connection callback.
2739
+ */
2740
+ _doDisconnect: function ()
2741
+ {
2742
+ Strophe.info("_doDisconnect was called");
2743
+ this.authenticated = false;
2744
+ this.disconnecting = false;
2745
+ this.sid = null;
2746
+ this.streamId = null;
2747
+ this.rid = Math.floor(Math.random() * 4294967295);
2748
+
2749
+ // tell the parent we disconnected
2750
+ if (this.connected) {
2751
+ this._changeConnectStatus(Strophe.Status.DISCONNECTED, null);
2752
+ this.connected = false;
2753
+ }
2754
+
2755
+ // delete handlers
2756
+ this.handlers = [];
2757
+ this.timedHandlers = [];
2758
+ this.removeTimeds = [];
2759
+ this.removeHandlers = [];
2760
+ this.addTimeds = [];
2761
+ this.addHandlers = [];
2762
+ },
2763
+
2764
+ /** PrivateFunction: _dataRecv
2765
+ * _Private_ handler to processes incoming data from the the connection.
2766
+ *
2767
+ * Except for _connect_cb handling the initial connection request,
2768
+ * this function handles the incoming data for all requests. This
2769
+ * function also fires stanza handlers that match each incoming
2770
+ * stanza.
2771
+ *
2772
+ * Parameters:
2773
+ * (Strophe.Request) req - The request that has data ready.
2774
+ */
2775
+ _dataRecv: function (req)
2776
+ {
2777
+ try {
2778
+ var elem = req.getResponse();
2779
+ } catch (e) {
2780
+ if (e != "parsererror") { throw e; }
2781
+ this.disconnect("strophe-parsererror");
2782
+ }
2783
+ if (elem === null) { return; }
2784
+
2785
+ if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
2786
+ this.xmlInput(elem);
2787
+ }
2788
+ if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
2789
+ this.rawInput(Strophe.serialize(elem));
2790
+ }
2791
+
2792
+ // remove handlers scheduled for deletion
2793
+ var i, hand;
2794
+ while (this.removeHandlers.length > 0) {
2795
+ hand = this.removeHandlers.pop();
2796
+ i = this.handlers.indexOf(hand);
2797
+ if (i >= 0) {
2798
+ this.handlers.splice(i, 1);
2799
+ }
2800
+ }
2801
+
2802
+ // add handlers scheduled for addition
2803
+ while (this.addHandlers.length > 0) {
2804
+ this.handlers.push(this.addHandlers.pop());
2805
+ }
2806
+
2807
+ // handle graceful disconnect
2808
+ if (this.disconnecting && this._requests.length === 0) {
2809
+ this.deleteTimedHandler(this._disconnectTimeout);
2810
+ this._disconnectTimeout = null;
2811
+ this._doDisconnect();
2812
+ return;
2813
+ }
2814
+
2815
+ var typ = elem.getAttribute("type");
2816
+ var cond, conflict;
2817
+ if (typ !== null && typ == "terminate") {
2818
+ // Don't process stanzas that come in after disconnect
2819
+ if (this.disconnecting) {
2820
+ return;
2821
+ }
2822
+
2823
+ // an error occurred
2824
+ cond = elem.getAttribute("condition");
2825
+ conflict = elem.getElementsByTagName("conflict");
2826
+ if (cond !== null) {
2827
+ if (cond == "remote-stream-error" && conflict.length > 0) {
2828
+ cond = "conflict";
2829
+ }
2830
+ this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
2831
+ } else {
2832
+ this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
2833
+ }
2834
+ this.disconnect();
2835
+ return;
2836
+ }
2837
+
2838
+ // send each incoming stanza through the handler chain
2839
+ var that = this;
2840
+ Strophe.forEachChild(elem, null, function (child) {
2841
+ var i, newList;
2842
+ // process handlers
2843
+ newList = that.handlers;
2844
+ that.handlers = [];
2845
+ for (i = 0; i < newList.length; i++) {
2846
+ var hand = newList[i];
2847
+ // encapsulate 'handler.run' not to lose the whole handler list if
2848
+ // one of the handlers throws an exception
2849
+ try {
2850
+ if (hand.isMatch(child) &&
2851
+ (that.authenticated || !hand.user)) {
2852
+ if (hand.run(child)) {
2853
+ that.handlers.push(hand);
2854
+ }
2855
+ } else {
2856
+ that.handlers.push(hand);
2857
+ }
2858
+ } catch(e) {
2859
+ //if the handler throws an exception, we consider it as false
2860
+ }
2861
+ }
2862
+ });
2863
+ },
2864
+
2865
+ /** PrivateFunction: _sendTerminate
2866
+ * _Private_ function to send initial disconnect sequence.
2867
+ *
2868
+ * This is the first step in a graceful disconnect. It sends
2869
+ * the BOSH server a terminate body and includes an unavailable
2870
+ * presence if authentication has completed.
2871
+ */
2872
+ _sendTerminate: function ()
2873
+ {
2874
+ Strophe.info("_sendTerminate was called");
2875
+ var body = this._buildBody().attrs({type: "terminate"});
2876
+
2877
+ if (this.authenticated) {
2878
+ body.c('presence', {
2879
+ xmlns: Strophe.NS.CLIENT,
2880
+ type: 'unavailable'
2881
+ });
2882
+ }
2883
+
2884
+ this.disconnecting = true;
2885
+
2886
+ var req = new Strophe.Request(body.tree(),
2887
+ this._onRequestStateChange.bind(
2888
+ this, this._dataRecv.bind(this)),
2889
+ body.tree().getAttribute("rid"));
2890
+
2891
+ this._requests.push(req);
2892
+ this._throttledRequestHandler();
2893
+ },
2894
+
2895
+ /** PrivateFunction: _connect_cb
2896
+ * _Private_ handler for initial connection request.
2897
+ *
2898
+ * This handler is used to process the initial connection request
2899
+ * response from the BOSH server. It is used to set up authentication
2900
+ * handlers and start the authentication process.
2901
+ *
2902
+ * SASL authentication will be attempted if available, otherwise
2903
+ * the code will fall back to legacy authentication.
2904
+ *
2905
+ * Parameters:
2906
+ * (Strophe.Request) req - The current request.
2907
+ */
2908
+ _connect_cb: function (req)
2909
+ {
2910
+ Strophe.info("_connect_cb was called");
2911
+
2912
+ this.connected = true;
2913
+ var bodyWrap = req.getResponse();
2914
+ if (!bodyWrap) { return; }
2915
+
2916
+ if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
2917
+ this.xmlInput(bodyWrap);
2918
+ }
2919
+ if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
2920
+ this.rawInput(Strophe.serialize(bodyWrap));
2921
+ }
2922
+
2923
+ var typ = bodyWrap.getAttribute("type");
2924
+ var cond, conflict;
2925
+ if (typ !== null && typ == "terminate") {
2926
+ // an error occurred
2927
+ cond = bodyWrap.getAttribute("condition");
2928
+ conflict = bodyWrap.getElementsByTagName("conflict");
2929
+ if (cond !== null) {
2930
+ if (cond == "remote-stream-error" && conflict.length > 0) {
2931
+ cond = "conflict";
2932
+ }
2933
+ this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
2934
+ } else {
2935
+ this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
2936
+ }
2937
+ return;
2938
+ }
2939
+
2940
+ // check to make sure we don't overwrite these if _connect_cb is
2941
+ // called multiple times in the case of missing stream:features
2942
+ if (!this.sid) {
2943
+ this.sid = bodyWrap.getAttribute("sid");
2944
+ }
2945
+ if (!this.stream_id) {
2946
+ this.stream_id = bodyWrap.getAttribute("authid");
2947
+ }
2948
+ var wind = bodyWrap.getAttribute('requests');
2949
+ if (wind) { this.window = parseInt(wind, 10); }
2950
+ var hold = bodyWrap.getAttribute('hold');
2951
+ if (hold) { this.hold = parseInt(hold, 10); }
2952
+ var wait = bodyWrap.getAttribute('wait');
2953
+ if (wait) { this.wait = parseInt(wait, 10); }
2954
+
2955
+
2956
+ var do_sasl_plain = false;
2957
+ var do_sasl_digest_md5 = false;
2958
+ var do_sasl_anonymous = false;
2959
+
2960
+ var mechanisms = bodyWrap.getElementsByTagName("mechanism");
2961
+ var i, mech, auth_str, hashed_auth_str;
2962
+ if (mechanisms.length > 0) {
2963
+ for (i = 0; i < mechanisms.length; i++) {
2964
+ mech = Strophe.getText(mechanisms[i]);
2965
+ if (mech == 'DIGEST-MD5') {
2966
+ do_sasl_digest_md5 = true;
2967
+ } else if (mech == 'PLAIN') {
2968
+ do_sasl_plain = true;
2969
+ } else if (mech == 'ANONYMOUS') {
2970
+ do_sasl_anonymous = true;
2971
+ }
2972
+ }
2973
+ } else {
2974
+ // we didn't get stream:features yet, so we need wait for it
2975
+ // by sending a blank poll request
2976
+ var body = this._buildBody();
2977
+ this._requests.push(
2978
+ new Strophe.Request(body.tree(),
2979
+ this._onRequestStateChange.bind(
2980
+ this, this._connect_cb.bind(this)),
2981
+ body.tree().getAttribute("rid")));
2982
+ this._throttledRequestHandler();
2983
+ return;
2984
+ }
2985
+
2986
+ if (Strophe.getNodeFromJid(this.jid) === null &&
2987
+ do_sasl_anonymous) {
2988
+ this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
2989
+ this._sasl_success_handler = this._addSysHandler(
2990
+ this._sasl_success_cb.bind(this), null,
2991
+ "success", null, null);
2992
+ this._sasl_failure_handler = this._addSysHandler(
2993
+ this._sasl_failure_cb.bind(this), null,
2994
+ "failure", null, null);
2995
+
2996
+ this.send($build("auth", {
2997
+ xmlns: Strophe.NS.SASL,
2998
+ mechanism: "ANONYMOUS"
2999
+ }).tree());
3000
+ } else if (Strophe.getNodeFromJid(this.jid) === null) {
3001
+ // we don't have a node, which is required for non-anonymous
3002
+ // client connections
3003
+ this._changeConnectStatus(Strophe.Status.CONNFAIL,
3004
+ 'x-strophe-bad-non-anon-jid');
3005
+ this.disconnect();
3006
+ } else if (do_sasl_digest_md5) {
3007
+ this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
3008
+ this._sasl_challenge_handler = this._addSysHandler(
3009
+ this._sasl_challenge1_cb.bind(this), null,
3010
+ "challenge", null, null);
3011
+ this._sasl_failure_handler = this._addSysHandler(
3012
+ this._sasl_failure_cb.bind(this), null,
3013
+ "failure", null, null);
3014
+
3015
+ this.send($build("auth", {
3016
+ xmlns: Strophe.NS.SASL,
3017
+ mechanism: "DIGEST-MD5"
3018
+ }).tree());
3019
+ } else if (do_sasl_plain) {
3020
+ // Build the plain auth string (barejid null
3021
+ // username null password) and base 64 encoded.
3022
+ auth_str = Strophe.getBareJidFromJid(this.jid);
3023
+ auth_str = auth_str + "\u0000";
3024
+ auth_str = auth_str + Strophe.getNodeFromJid(this.jid);
3025
+ auth_str = auth_str + "\u0000";
3026
+ auth_str = auth_str + this.pass;
3027
+
3028
+ this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
3029
+ this._sasl_success_handler = this._addSysHandler(
3030
+ this._sasl_success_cb.bind(this), null,
3031
+ "success", null, null);
3032
+ this._sasl_failure_handler = this._addSysHandler(
3033
+ this._sasl_failure_cb.bind(this), null,
3034
+ "failure", null, null);
3035
+
3036
+ hashed_auth_str = Base64.encode(auth_str);
3037
+ this.send($build("auth", {
3038
+ xmlns: Strophe.NS.SASL,
3039
+ mechanism: "PLAIN"
3040
+ }).t(hashed_auth_str).tree());
3041
+ } else {
3042
+ this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
3043
+ this._addSysHandler(this._auth1_cb.bind(this), null, null,
3044
+ null, "_auth_1");
3045
+
3046
+ this.send($iq({
3047
+ type: "get",
3048
+ to: this.domain,
3049
+ id: "_auth_1"
3050
+ }).c("query", {
3051
+ xmlns: Strophe.NS.AUTH
3052
+ }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
3053
+ }
3054
+ },
3055
+
3056
+ /** PrivateFunction: _sasl_challenge1_cb
3057
+ * _Private_ handler for DIGEST-MD5 SASL authentication.
3058
+ *
3059
+ * Parameters:
3060
+ * (XMLElement) elem - The challenge stanza.
3061
+ *
3062
+ * Returns:
3063
+ * false to remove the handler.
3064
+ */
3065
+ _sasl_challenge1_cb: function (elem)
3066
+ {
3067
+ var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;
3068
+
3069
+ var challenge = Base64.decode(Strophe.getText(elem));
3070
+ var cnonce = MD5.hexdigest("" + (Math.random() * 1234567890));
3071
+ var realm = "";
3072
+ var host = null;
3073
+ var nonce = "";
3074
+ var qop = "";
3075
+ var matches;
3076
+
3077
+ // remove unneeded handlers
3078
+ this.deleteHandler(this._sasl_failure_handler);
3079
+
3080
+ while (challenge.match(attribMatch)) {
3081
+ matches = challenge.match(attribMatch);
3082
+ challenge = challenge.replace(matches[0], "");
3083
+ matches[2] = matches[2].replace(/^"(.+)"$/, "$1");
3084
+ switch (matches[1]) {
3085
+ case "realm":
3086
+ realm = matches[2];
3087
+ break;
3088
+ case "nonce":
3089
+ nonce = matches[2];
3090
+ break;
3091
+ case "qop":
3092
+ qop = matches[2];
3093
+ break;
3094
+ case "host":
3095
+ host = matches[2];
3096
+ break;
3097
+ }
3098
+ }
3099
+
3100
+ var digest_uri = "xmpp/" + this.domain;
3101
+ if (host !== null) {
3102
+ digest_uri = digest_uri + "/" + host;
3103
+ }
3104
+
3105
+ var A1 = MD5.hash(Strophe.getNodeFromJid(this.jid) +
3106
+ ":" + realm + ":" + this.pass) +
3107
+ ":" + nonce + ":" + cnonce;
3108
+ var A2 = 'AUTHENTICATE:' + digest_uri;
3109
+
3110
+ var responseText = "";
3111
+ responseText += 'username=' +
3112
+ this._quote(Strophe.getNodeFromJid(this.jid)) + ',';
3113
+ responseText += 'realm=' + this._quote(realm) + ',';
3114
+ responseText += 'nonce=' + this._quote(nonce) + ',';
3115
+ responseText += 'cnonce=' + this._quote(cnonce) + ',';
3116
+ responseText += 'nc="00000001",';
3117
+ responseText += 'qop="auth",';
3118
+ responseText += 'digest-uri=' + this._quote(digest_uri) + ',';
3119
+ responseText += 'response=' + this._quote(
3120
+ MD5.hexdigest(MD5.hexdigest(A1) + ":" +
3121
+ nonce + ":00000001:" +
3122
+ cnonce + ":auth:" +
3123
+ MD5.hexdigest(A2))) + ',';
3124
+ responseText += 'charset="utf-8"';
3125
+
3126
+ this._sasl_challenge_handler = this._addSysHandler(
3127
+ this._sasl_challenge2_cb.bind(this), null,
3128
+ "challenge", null, null);
3129
+ this._sasl_success_handler = this._addSysHandler(
3130
+ this._sasl_success_cb.bind(this), null,
3131
+ "success", null, null);
3132
+ this._sasl_failure_handler = this._addSysHandler(
3133
+ this._sasl_failure_cb.bind(this), null,
3134
+ "failure", null, null);
3135
+
3136
+ this.send($build('response', {
3137
+ xmlns: Strophe.NS.SASL
3138
+ }).t(Base64.encode(responseText)).tree());
3139
+
3140
+ return false;
3141
+ },
3142
+
3143
+ /** PrivateFunction: _quote
3144
+ * _Private_ utility function to backslash escape and quote strings.
3145
+ *
3146
+ * Parameters:
3147
+ * (String) str - The string to be quoted.
3148
+ *
3149
+ * Returns:
3150
+ * quoted string
3151
+ */
3152
+ _quote: function (str)
3153
+ {
3154
+ return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
3155
+ //" end string workaround for emacs
3156
+ },
3157
+
3158
+
3159
+ /** PrivateFunction: _sasl_challenge2_cb
3160
+ * _Private_ handler for second step of DIGEST-MD5 SASL authentication.
3161
+ *
3162
+ * Parameters:
3163
+ * (XMLElement) elem - The challenge stanza.
3164
+ *
3165
+ * Returns:
3166
+ * false to remove the handler.
3167
+ */
3168
+ _sasl_challenge2_cb: function (elem)
3169
+ {
3170
+ // remove unneeded handlers
3171
+ this.deleteHandler(this._sasl_success_handler);
3172
+ this.deleteHandler(this._sasl_failure_handler);
3173
+
3174
+ this._sasl_success_handler = this._addSysHandler(
3175
+ this._sasl_success_cb.bind(this), null,
3176
+ "success", null, null);
3177
+ this._sasl_failure_handler = this._addSysHandler(
3178
+ this._sasl_failure_cb.bind(this), null,
3179
+ "failure", null, null);
3180
+ this.send($build('response', {xmlns: Strophe.NS.SASL}).tree());
3181
+ return false;
3182
+ },
3183
+
3184
+ /** PrivateFunction: _auth1_cb
3185
+ * _Private_ handler for legacy authentication.
3186
+ *
3187
+ * This handler is called in response to the initial <iq type='get'/>
3188
+ * for legacy authentication. It builds an authentication <iq/> and
3189
+ * sends it, creating a handler (calling back to _auth2_cb()) to
3190
+ * handle the result
3191
+ *
3192
+ * Parameters:
3193
+ * (XMLElement) elem - The stanza that triggered the callback.
3194
+ *
3195
+ * Returns:
3196
+ * false to remove the handler.
3197
+ */
3198
+ _auth1_cb: function (elem)
3199
+ {
3200
+ // build plaintext auth iq
3201
+ var iq = $iq({type: "set", id: "_auth_2"})
3202
+ .c('query', {xmlns: Strophe.NS.AUTH})
3203
+ .c('username', {}).t(Strophe.getNodeFromJid(this.jid))
3204
+ .up()
3205
+ .c('password').t(this.pass);
3206
+
3207
+ if (!Strophe.getResourceFromJid(this.jid)) {
3208
+ // since the user has not supplied a resource, we pick
3209
+ // a default one here. unlike other auth methods, the server
3210
+ // cannot do this for us.
3211
+ this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
3212
+ }
3213
+ iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
3214
+
3215
+ this._addSysHandler(this._auth2_cb.bind(this), null,
3216
+ null, null, "_auth_2");
3217
+
3218
+ this.send(iq.tree());
3219
+
3220
+ return false;
3221
+ },
3222
+
3223
+ /** PrivateFunction: _sasl_success_cb
3224
+ * _Private_ handler for succesful SASL authentication.
3225
+ *
3226
+ * Parameters:
3227
+ * (XMLElement) elem - The matching stanza.
3228
+ *
3229
+ * Returns:
3230
+ * false to remove the handler.
3231
+ */
3232
+ _sasl_success_cb: function (elem)
3233
+ {
3234
+ Strophe.info("SASL authentication succeeded.");
3235
+
3236
+ // remove old handlers
3237
+ this.deleteHandler(this._sasl_failure_handler);
3238
+ this._sasl_failure_handler = null;
3239
+ if (this._sasl_challenge_handler) {
3240
+ this.deleteHandler(this._sasl_challenge_handler);
3241
+ this._sasl_challenge_handler = null;
3242
+ }
3243
+
3244
+ this._addSysHandler(this._sasl_auth1_cb.bind(this), null,
3245
+ "stream:features", null, null);
3246
+
3247
+ // we must send an xmpp:restart now
3248
+ this._sendRestart();
3249
+
3250
+ return false;
3251
+ },
3252
+
3253
+ /** PrivateFunction: _sasl_auth1_cb
3254
+ * _Private_ handler to start stream binding.
3255
+ *
3256
+ * Parameters:
3257
+ * (XMLElement) elem - The matching stanza.
3258
+ *
3259
+ * Returns:
3260
+ * false to remove the handler.
3261
+ */
3262
+ _sasl_auth1_cb: function (elem)
3263
+ {
3264
+ // save stream:features for future usage
3265
+ this.features = elem;
3266
+
3267
+ var i, child;
3268
+
3269
+ for (i = 0; i < elem.childNodes.length; i++) {
3270
+ child = elem.childNodes[i];
3271
+ if (child.nodeName == 'bind') {
3272
+ this.do_bind = true;
3273
+ }
3274
+
3275
+ if (child.nodeName == 'session') {
3276
+ this.do_session = true;
3277
+ }
3278
+ }
3279
+
3280
+ if (!this.do_bind) {
3281
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3282
+ return false;
3283
+ } else {
3284
+ this._addSysHandler(this._sasl_bind_cb.bind(this), null, null,
3285
+ null, "_bind_auth_2");
3286
+
3287
+ var resource = Strophe.getResourceFromJid(this.jid);
3288
+ if (resource) {
3289
+ this.send($iq({type: "set", id: "_bind_auth_2"})
3290
+ .c('bind', {xmlns: Strophe.NS.BIND})
3291
+ .c('resource', {}).t(resource).tree());
3292
+ } else {
3293
+ this.send($iq({type: "set", id: "_bind_auth_2"})
3294
+ .c('bind', {xmlns: Strophe.NS.BIND})
3295
+ .tree());
3296
+ }
3297
+ }
3298
+
3299
+ return false;
3300
+ },
3301
+
3302
+ /** PrivateFunction: _sasl_bind_cb
3303
+ * _Private_ handler for binding result and session start.
3304
+ *
3305
+ * Parameters:
3306
+ * (XMLElement) elem - The matching stanza.
3307
+ *
3308
+ * Returns:
3309
+ * false to remove the handler.
3310
+ */
3311
+ _sasl_bind_cb: function (elem)
3312
+ {
3313
+ if (elem.getAttribute("type") == "error") {
3314
+ Strophe.info("SASL binding failed.");
3315
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3316
+ return false;
3317
+ }
3318
+
3319
+ // TODO - need to grab errors
3320
+ var bind = elem.getElementsByTagName("bind");
3321
+ var jidNode;
3322
+ if (bind.length > 0) {
3323
+ // Grab jid
3324
+ jidNode = bind[0].getElementsByTagName("jid");
3325
+ if (jidNode.length > 0) {
3326
+ this.jid = Strophe.getText(jidNode[0]);
3327
+
3328
+ if (this.do_session) {
3329
+ this._addSysHandler(this._sasl_session_cb.bind(this),
3330
+ null, null, null, "_session_auth_2");
3331
+
3332
+ this.send($iq({type: "set", id: "_session_auth_2"})
3333
+ .c('session', {xmlns: Strophe.NS.SESSION})
3334
+ .tree());
3335
+ } else {
3336
+ this.authenticated = true;
3337
+ this._changeConnectStatus(Strophe.Status.CONNECTED, null);
3338
+ }
3339
+ }
3340
+ } else {
3341
+ Strophe.info("SASL binding failed.");
3342
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3343
+ return false;
3344
+ }
3345
+ },
3346
+
3347
+ /** PrivateFunction: _sasl_session_cb
3348
+ * _Private_ handler to finish successful SASL connection.
3349
+ *
3350
+ * This sets Connection.authenticated to true on success, which
3351
+ * starts the processing of user handlers.
3352
+ *
3353
+ * Parameters:
3354
+ * (XMLElement) elem - The matching stanza.
3355
+ *
3356
+ * Returns:
3357
+ * false to remove the handler.
3358
+ */
3359
+ _sasl_session_cb: function (elem)
3360
+ {
3361
+ if (elem.getAttribute("type") == "result") {
3362
+ this.authenticated = true;
3363
+ this._changeConnectStatus(Strophe.Status.CONNECTED, null);
3364
+ } else if (elem.getAttribute("type") == "error") {
3365
+ Strophe.info("Session creation failed.");
3366
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3367
+ return false;
3368
+ }
3369
+
3370
+ return false;
3371
+ },
3372
+
3373
+ /** PrivateFunction: _sasl_failure_cb
3374
+ * _Private_ handler for SASL authentication failure.
3375
+ *
3376
+ * Parameters:
3377
+ * (XMLElement) elem - The matching stanza.
3378
+ *
3379
+ * Returns:
3380
+ * false to remove the handler.
3381
+ */
3382
+ _sasl_failure_cb: function (elem)
3383
+ {
3384
+ // delete unneeded handlers
3385
+ if (this._sasl_success_handler) {
3386
+ this.deleteHandler(this._sasl_success_handler);
3387
+ this._sasl_success_handler = null;
3388
+ }
3389
+ if (this._sasl_challenge_handler) {
3390
+ this.deleteHandler(this._sasl_challenge_handler);
3391
+ this._sasl_challenge_handler = null;
3392
+ }
3393
+
3394
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3395
+ return false;
3396
+ },
3397
+
3398
+ /** PrivateFunction: _auth2_cb
3399
+ * _Private_ handler to finish legacy authentication.
3400
+ *
3401
+ * This handler is called when the result from the jabber:iq:auth
3402
+ * <iq/> stanza is returned.
3403
+ *
3404
+ * Parameters:
3405
+ * (XMLElement) elem - The stanza that triggered the callback.
3406
+ *
3407
+ * Returns:
3408
+ * false to remove the handler.
3409
+ */
3410
+ _auth2_cb: function (elem)
3411
+ {
3412
+ if (elem.getAttribute("type") == "result") {
3413
+ this.authenticated = true;
3414
+ this._changeConnectStatus(Strophe.Status.CONNECTED, null);
3415
+ } else if (elem.getAttribute("type") == "error") {
3416
+ this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
3417
+ this.disconnect();
3418
+ }
3419
+
3420
+ return false;
3421
+ },
3422
+
3423
+ /** PrivateFunction: _addSysTimedHandler
3424
+ * _Private_ function to add a system level timed handler.
3425
+ *
3426
+ * This function is used to add a Strophe.TimedHandler for the
3427
+ * library code. System timed handlers are allowed to run before
3428
+ * authentication is complete.
3429
+ *
3430
+ * Parameters:
3431
+ * (Integer) period - The period of the handler.
3432
+ * (Function) handler - The callback function.
3433
+ */
3434
+ _addSysTimedHandler: function (period, handler)
3435
+ {
3436
+ var thand = new Strophe.TimedHandler(period, handler);
3437
+ thand.user = false;
3438
+ this.addTimeds.push(thand);
3439
+ return thand;
3440
+ },
3441
+
3442
+ /** PrivateFunction: _addSysHandler
3443
+ * _Private_ function to add a system level stanza handler.
3444
+ *
3445
+ * This function is used to add a Strophe.Handler for the
3446
+ * library code. System stanza handlers are allowed to run before
3447
+ * authentication is complete.
3448
+ *
3449
+ * Parameters:
3450
+ * (Function) handler - The callback function.
3451
+ * (String) ns - The namespace to match.
3452
+ * (String) name - The stanza name to match.
3453
+ * (String) type - The stanza type attribute to match.
3454
+ * (String) id - The stanza id attribute to match.
3455
+ */
3456
+ _addSysHandler: function (handler, ns, name, type, id)
3457
+ {
3458
+ var hand = new Strophe.Handler(handler, ns, name, type, id);
3459
+ hand.user = false;
3460
+ this.addHandlers.push(hand);
3461
+ return hand;
3462
+ },
3463
+
3464
+ /** PrivateFunction: _onDisconnectTimeout
3465
+ * _Private_ timeout handler for handling non-graceful disconnection.
3466
+ *
3467
+ * If the graceful disconnect process does not complete within the
3468
+ * time allotted, this handler finishes the disconnect anyway.
3469
+ *
3470
+ * Returns:
3471
+ * false to remove the handler.
3472
+ */
3473
+ _onDisconnectTimeout: function ()
3474
+ {
3475
+ Strophe.info("_onDisconnectTimeout was called");
3476
+
3477
+ // cancel all remaining requests and clear the queue
3478
+ var req;
3479
+ while (this._requests.length > 0) {
3480
+ req = this._requests.pop();
3481
+ req.abort = true;
3482
+ req.xhr.abort();
3483
+ // jslint complains, but this is fine. setting to empty func
3484
+ // is necessary for IE6
3485
+ req.xhr.onreadystatechange = function () {};
3486
+ }
3487
+
3488
+ // actually disconnect
3489
+ this._doDisconnect();
3490
+
3491
+ return false;
3492
+ },
3493
+
3494
+ /** PrivateFunction: _onIdle
3495
+ * _Private_ handler to process events during idle cycle.
3496
+ *
3497
+ * This handler is called every 100ms to fire timed handlers that
3498
+ * are ready and keep poll requests going.
3499
+ */
3500
+ _onIdle: function ()
3501
+ {
3502
+ var i, thand, since, newList;
3503
+
3504
+ // add timed handlers scheduled for addition
3505
+ // NOTE: we add before remove in the case a timed handler is
3506
+ // added and then deleted before the next _onIdle() call.
3507
+ while (this.addTimeds.length > 0) {
3508
+ this.timedHandlers.push(this.addTimeds.pop());
3509
+ }
3510
+
3511
+ // remove timed handlers that have been scheduled for deletion
3512
+ while (this.removeTimeds.length > 0) {
3513
+ thand = this.removeTimeds.pop();
3514
+ i = this.timedHandlers.indexOf(thand);
3515
+ if (i >= 0) {
3516
+ this.timedHandlers.splice(i, 1);
3517
+ }
3518
+ }
3519
+
3520
+ // call ready timed handlers
3521
+ var now = new Date().getTime();
3522
+ newList = [];
3523
+ for (i = 0; i < this.timedHandlers.length; i++) {
3524
+ thand = this.timedHandlers[i];
3525
+ if (this.authenticated || !thand.user) {
3526
+ since = thand.lastCalled + thand.period;
3527
+ if (since - now <= 0) {
3528
+ if (thand.run()) {
3529
+ newList.push(thand);
3530
+ }
3531
+ } else {
3532
+ newList.push(thand);
3533
+ }
3534
+ }
3535
+ }
3536
+ this.timedHandlers = newList;
3537
+
3538
+ var body, time_elapsed;
3539
+
3540
+ // if no requests are in progress, poll
3541
+ if (this.authenticated && this._requests.length === 0 &&
3542
+ this._data.length === 0 && !this.disconnecting) {
3543
+ Strophe.info("no requests during idle cycle, sending " +
3544
+ "blank request");
3545
+ this._data.push(null);
3546
+ }
3547
+
3548
+ if (this._requests.length < 2 && this._data.length > 0 &&
3549
+ !this.paused) {
3550
+ body = this._buildBody();
3551
+ for (i = 0; i < this._data.length; i++) {
3552
+ if (this._data[i] !== null) {
3553
+ if (this._data[i] === "restart") {
3554
+ body.attrs({
3555
+ to: this.domain,
3556
+ "xml:lang": "en",
3557
+ "xmpp:restart": "true",
3558
+ "xmlns:xmpp": Strophe.NS.BOSH
3559
+ });
3560
+ } else {
3561
+ body.cnode(this._data[i]).up();
3562
+ }
3563
+ }
3564
+ }
3565
+ delete this._data;
3566
+ this._data = [];
3567
+ this._requests.push(
3568
+ new Strophe.Request(body.tree(),
3569
+ this._onRequestStateChange.bind(
3570
+ this, this._dataRecv.bind(this)),
3571
+ body.tree().getAttribute("rid")));
3572
+ this._processRequest(this._requests.length - 1);
3573
+ }
3574
+
3575
+ if (this._requests.length > 0) {
3576
+ time_elapsed = this._requests[0].age();
3577
+ if (this._requests[0].dead !== null) {
3578
+ if (this._requests[0].timeDead() >
3579
+ Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
3580
+ this._throttledRequestHandler();
3581
+ }
3582
+ }
3583
+
3584
+ if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
3585
+ Strophe.warn("Request " +
3586
+ this._requests[0].id +
3587
+ " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
3588
+ " seconds since last activity");
3589
+ this._throttledRequestHandler();
3590
+ }
3591
+ }
3592
+
3593
+ clearTimeout(this._idleTimeout);
3594
+
3595
+ // reactivate the timer only if connected
3596
+ if (this.connected) {
3597
+ this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
3598
+ }
3599
+ }
3600
+ };
3601
+
3602
+ if (callback) {
3603
+ callback(Strophe, $build, $msg, $iq, $pres);
3604
+ }
3605
+
3606
+ })(function () {
3607
+ window.Strophe = arguments[0];
3608
+ window.$build = arguments[1];
3609
+ window.$msg = arguments[2];
3610
+ window.$iq = arguments[3];
3611
+ window.$pres = arguments[4];
3612
+ });