Slimstat Analytics - Version 4.7

Version Description

  • [New] After receiving a few requests to implement a REST API within Slimstat, and given that WordPress now offers a mature and stable interface for extending its built-in REST API, we decided to finally move forward and implement this feature. Please refer to our online knowledge base to learn more about how to use it.
  • [Update] The Add-on Update Checker library has been updated to version 4.2, to solve an incompatibility issue with PHP 7.0 (thank you, Sasa and Per).
  • [Update] Bootstrap Switch (which we use on our Settings panels) has been updated to version 3.3.4.
  • [Fix] Apparently, there was an issue where our XMLHttpRequest didn't send the cookie for Cross-Origin URLs (thank you, Sasa).
  • [Fix] Solved issue with pagination, triggered when certain long time ranges were being selected.
  • [Fix] The autorefresh countdown timer was not working as expected if Async Mode was enabled (thank you, scruffy1 and service4).
Download this release

Release Info

Developer coolmann
Plugin Icon 128x128 Slimstat Analytics
Version 4.7
Comparing to
See all releases

Code changes from version 4.6.9.1 to 4.7

Files changed (39) hide show
  1. admin/config/index.php +5 -1
  2. admin/js/slimstat.admin.js +39 -30
  3. admin/update-checker/Puc/v4/Factory.php +271 -0
  4. admin/update-checker/Puc/v4p2/Autoloader.php +49 -0
  5. admin/update-checker/Puc/v4p2/Metadata.php +132 -0
  6. admin/update-checker/Puc/v4p2/Plugin/Info.php +127 -0
  7. admin/update-checker/Puc/v4p2/Plugin/Update.php +91 -0
  8. admin/update-checker/Puc/v4p2/Plugin/UpdateChecker.php +546 -0
  9. admin/update-checker/Puc/v4p2/Scheduler.php +177 -0
  10. admin/update-checker/Puc/v4p2/StateStore.php +207 -0
  11. admin/update-checker/Puc/v4p2/Theme/Update.php +84 -0
  12. admin/update-checker/Puc/v4p2/Theme/UpdateChecker.php +167 -0
  13. admin/update-checker/Puc/v4p2/Update.php +34 -0
  14. admin/update-checker/Puc/v4p2/UpdateChecker.php +827 -0
  15. admin/update-checker/Puc/v4p2/UpgraderStatus.php +199 -0
  16. admin/update-checker/Puc/v4p2/Utils.php +69 -0
  17. admin/update-checker/Puc/v4p2/Vcs/Api.php +243 -0
  18. admin/update-checker/Puc/v4p2/Vcs/BaseChecker.php +22 -0
  19. admin/update-checker/Puc/v4p2/Vcs/BitBucketApi.php +251 -0
  20. admin/update-checker/Puc/v4p2/Vcs/GitHubApi.php +302 -0
  21. admin/update-checker/Puc/v4p2/Vcs/PluginUpdateChecker.php +200 -0
  22. admin/update-checker/Puc/v4p2/Vcs/Reference.php +49 -0
  23. admin/update-checker/Puc/v4p2/Vcs/ThemeUpdateChecker.php +101 -0
  24. admin/update-checker/css/puc-debug-bar.css +0 -62
  25. admin/update-checker/debug-bar-panel.php +0 -146
  26. admin/update-checker/debug-bar-plugin.php +0 -102
  27. admin/update-checker/github-checker.php +0 -463
  28. admin/update-checker/js/debug-bar.js +0 -52
  29. admin/update-checker/plugin-update-checker.php +22 -1494
  30. admin/update-checker/vendor/Parsedown.php +46 -43
  31. admin/update-checker/vendor/readme-parser.php +8 -5
  32. admin/view/wp-slimstat-db.php +5 -5
  33. admin/view/wp-slimstat-reports.php +13 -18
  34. admin/wp-slimstat-admin.php +7 -9
  35. maxmind.php +27 -35
  36. readme.txt +11 -2
  37. wp-slimstat.js +1 -0
  38. wp-slimstat.min.js +1 -1
  39. wp-slimstat.php +99 -3
admin/config/index.php CHANGED
@@ -28,7 +28,7 @@ if ( isset( $_POST[ 'options' ][ 'can_view' ] ) ) {
28
  $post_data = trim( $_POST[ 'options' ][ 'can_view' ] );
29
  $user_array = wp_slimstat::string_to_array( $_POST[ 'options' ][ 'can_view' ] );
30
 
31
- if ( is_array( $user_array ) && !empty( $post_data ) ) {
32
  $sql_user_placeholders = implode( ', ', array_fill( 0, count( $user_array ), '%s' ) );
33
  if ( $GLOBALS[ 'wpdb' ]->get_var( $GLOBALS[ 'wpdb' ]->prepare( "SELECT COUNT( * ) FROM {$GLOBALS[ 'wpdb' ]->users} WHERE user_login IN ( $sql_user_placeholders )", $user_array ) ) == count( $user_array ) ) {
34
  wp_slimstat::$settings[ 'can_view' ] = $_POST[ 'options' ][ 'can_view' ];
@@ -37,6 +37,9 @@ if ( isset( $_POST[ 'options' ][ 'can_view' ] ) ) {
37
  wp_slimstat_admin::$faulty_fields[] = __( 'Read access: username not found', 'wp-slimstat' );
38
  }
39
  }
 
 
 
40
  }
41
 
42
  if ( isset( $_POST[ 'options' ][ 'capability_can_view' ] ) ) {
@@ -193,6 +196,7 @@ $settings = array(
193
  'restrict_authors_view' => array('description' => __('Restrict Authors','wp-slimstat'), 'type' => 'toggle', 'long_description' => __('Enable this option if you want your authors to only see stats related to their own content.','wp-slimstat')),
194
  'capability_can_view' => array('description' => __('Capability','wp-slimstat'), 'type' => 'text', 'long_description' => __("Specify the minimum <a href='http://codex.wordpress.org/Roles_and_Capabilities' target='_new'>capability</a> needed to access the reports (default: <code>activate_plugins</code>). If this field is empty, <strong>all your users</strong> (including subscribers) will have access to the reports, unless a 'Read access' whitelist has been specified here below. In this case, the list has precedence over the capability.",'wp-slimstat')),
195
  'can_view' => array('description' => __('Whitelist','wp-slimstat'), 'type' => 'textarea', 'long_description' => __("List all the users who should have access to the reports. Administrators are implicitly allowed, so you don't need to list them in here. Usernames are case sensitive.",'wp-slimstat'), 'skip_update' => true),
 
196
 
197
  'permissions_config_header' => array('description' => __('Settings','wp-slimstat'), 'type' => 'section_header'),
198
  'capability_can_admin' => array('description' => __('Capability','wp-slimstat'), 'type' => 'text', 'long_description' => __("Specify the minimum <a href='http://codex.wordpress.org/Roles_and_Capabilities' target='_new'>capability</a> required to configure Slimstat (default: <code>activate_plugins</code>). The whitelist here below can be used to override this option for specific users.",'wp-slimstat')),
28
  $post_data = trim( $_POST[ 'options' ][ 'can_view' ] );
29
  $user_array = wp_slimstat::string_to_array( $_POST[ 'options' ][ 'can_view' ] );
30
 
31
+ if ( !empty( $post_data ) ) {
32
  $sql_user_placeholders = implode( ', ', array_fill( 0, count( $user_array ), '%s' ) );
33
  if ( $GLOBALS[ 'wpdb' ]->get_var( $GLOBALS[ 'wpdb' ]->prepare( "SELECT COUNT( * ) FROM {$GLOBALS[ 'wpdb' ]->users} WHERE user_login IN ( $sql_user_placeholders )", $user_array ) ) == count( $user_array ) ) {
34
  wp_slimstat::$settings[ 'can_view' ] = $_POST[ 'options' ][ 'can_view' ];
37
  wp_slimstat_admin::$faulty_fields[] = __( 'Read access: username not found', 'wp-slimstat' );
38
  }
39
  }
40
+ else {
41
+ wp_slimstat::$settings[ 'can_view' ] = '';
42
+ }
43
  }
44
 
45
  if ( isset( $_POST[ 'options' ][ 'capability_can_view' ] ) ) {
196
  'restrict_authors_view' => array('description' => __('Restrict Authors','wp-slimstat'), 'type' => 'toggle', 'long_description' => __('Enable this option if you want your authors to only see stats related to their own content.','wp-slimstat')),
197
  'capability_can_view' => array('description' => __('Capability','wp-slimstat'), 'type' => 'text', 'long_description' => __("Specify the minimum <a href='http://codex.wordpress.org/Roles_and_Capabilities' target='_new'>capability</a> needed to access the reports (default: <code>activate_plugins</code>). If this field is empty, <strong>all your users</strong> (including subscribers) will have access to the reports, unless a 'Read access' whitelist has been specified here below. In this case, the list has precedence over the capability.",'wp-slimstat')),
198
  'can_view' => array('description' => __('Whitelist','wp-slimstat'), 'type' => 'textarea', 'long_description' => __("List all the users who should have access to the reports. Administrators are implicitly allowed, so you don't need to list them in here. Usernames are case sensitive.",'wp-slimstat'), 'skip_update' => true),
199
+ 'rest_api_tokens' => array( 'description' => __( 'REST API Tokens', 'wp-slimstat' ), 'type' => 'textarea', 'long_description' => __( "In order to send requests to the Slimstat REST API, you will need to pass a valid token to the endpoint (param ?token=XXX). Using the field here below, you can define as many tokens as you like, to distribute them to your API users. Please note: treat these tokens as passwords, as they will grant read access to your reports to anyone who knows them. Use a service like <a href='https://randomkeygen.com/#ci_key' target='_blank'>RandomKeyGen.com</a> to generate unique secure tokens.", 'wp-slimstat' ) ),
200
 
201
  'permissions_config_header' => array('description' => __('Settings','wp-slimstat'), 'type' => 'section_header'),
202
  'capability_can_admin' => array('description' => __('Capability','wp-slimstat'), 'type' => 'text', 'long_description' => __("Specify the minimum <a href='http://codex.wordpress.org/Roles_and_Capabilities' target='_new'>capability</a> required to configure Slimstat (default: <code>activate_plugins</code>). The whitelist here below can be used to override this option for specific users.",'wp-slimstat')),
admin/js/slimstat.admin.js CHANGED
@@ -50,52 +50,64 @@ var SlimStatAdmin = {
50
  }
51
  },
52
 
53
- refresh_countdown: function(){
54
- SlimStatAdmin._refresh_timer[1]--;
55
- if (SlimStatAdmin._refresh_timer[1] == -1){
56
- SlimStatAdmin._refresh_timer[1] = 59;
57
- SlimStatAdmin._refresh_timer[0] = SlimStatAdmin._refresh_timer[0]-1;
58
  }
59
- jQuery('.refresh-timer').html(SlimStatAdmin._refresh_timer[0]+':'+((SlimStatAdmin._refresh_timer[1]<10)?'0':'')+SlimStatAdmin._refresh_timer[1]);
60
- if (SlimStatAdmin._refresh_timer[0] > 0 || SlimStatAdmin._refresh_timer[1] > 0){
61
- refresh_handle = window.setTimeout("SlimStatAdmin.refresh_countdown();", 1000);
62
  }
63
- else{
64
  report_id = 'slim_p7_02';
65
  data = {action: 'slimstat_load_report', report_id: report_id, security: jQuery('#meta-box-order-nonce').val(), page: SlimStatAdmin.get_query_string_value( 'page' ) };
66
  jQuery('#'+report_id+' .inside').html('<p class="loading"><i class="slimstat-font-spin4 animate-spin"></i></p>');
67
  SlimStatAdmin.refresh_report(report_id, data);
68
 
69
  window.clearTimeout(refresh_handle);
70
- SlimStatAdmin._refresh_timer[0] = parseInt(SlimStatAdminParams.refresh_interval/60);
71
- SlimStatAdmin._refresh_timer[1] = SlimStatAdminParams.refresh_interval%60;
72
- refresh_handle = window.setTimeout("SlimStatAdmin.refresh_countdown();", 1000);
73
  }
74
  },
75
 
76
- refresh_report: function(report_id, data){
77
  // Get the data from the hidden form
78
- filters_input = jQuery('#slimstat-filters-form .slimstat-post-filter').toArray();
79
- for (i in filters_input){
80
- data[filters_input[i]['name']] = filters_input[i]['value'];
81
  }
82
 
83
  jQuery('#'+report_id+' .inside').html('<p class="loading"><i class="slimstat-font-spin4 animate-spin"></i></p>');
84
 
85
  jQuery.post(ajaxurl, data, function(response){
86
  if (report_id.indexOf('_01') > 0){
87
- jQuery('#'+report_id + ' .inside').html(response);
88
- // SlimStatAdmin.chart_init();
89
  }
90
  else{
91
- jQuery('#'+report_id + ' .inside').fadeOut(700, function(){
92
- jQuery(this).html(response).fadeIn(700);
 
 
 
 
 
 
 
 
 
93
  });
94
  }
95
  });
96
 
97
  // Remove filters set by other Ajax buttons
98
  jQuery('.slimstat-temp-filter').remove();
 
 
 
 
99
  },
100
 
101
  get_query_string_value: function( key ) {
@@ -118,7 +130,7 @@ var SlimStatAdmin = {
118
 
119
  jQuery(function(){
120
  // Refresh page every X seconds
121
- if ( SlimStatAdminParams.refresh_interval > 0 && jQuery( '.refresh-timer' ).length ) {
122
  SlimStatAdmin._refresh_timer[ 0 ] = parseInt( SlimStatAdminParams.refresh_interval / 60 );
123
  SlimStatAdmin._refresh_timer[ 1 ] = SlimStatAdminParams.refresh_interval % 60;
124
  refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
@@ -238,11 +250,8 @@ jQuery(function(){
238
 
239
  jQuery('#'+report_id+' .inside').slimScroll({scrollTo : '0px'});
240
 
241
- if ( typeof refresh_handle != 'undefined' && jQuery( '.refresh-timer' ).length ) {
242
- window.clearTimeout(refresh_handle);
243
- SlimStatAdmin._refresh_timer[ 0 ] = parseInt( SlimStatAdminParams.refresh_interval / 60 );
244
- SlimStatAdmin._refresh_timer[ 1 ] = SlimStatAdminParams.refresh_interval % 60;
245
- refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
246
  }
247
  });
248
 
@@ -485,11 +494,11 @@ jQuery(function(){
485
  /* qTip2 v3.0.3 | http://qtip2.com | Released under the MIT and GPL licenses. */
486
  !function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=D,this.elements={target:a},this._id=Q+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:C,attr:e,onTooltip:C,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=C}function f(a){return a===D||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?C:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?(c=g(b)?C:b,b=a.content={text:c}):c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==C,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,D,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(d.isPlainObject(b.title)&&(b.button=b.title.button,b.title=b.title.text),g(b.title||C)&&(b.title=C))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===B?{ready:B}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(P,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)if(this.checks.hasOwnProperty(c))for(d in this.checks[c])this.checks[c].hasOwnProperty(d)&&(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return T.concat("").join(a?"-"+a+" ":" ")}function l(a,b){return b>0?setTimeout(d.proxy(a,this),b):void a.call(this)}function m(a){this.tooltip.hasClass($)||(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=l.call(this,function(){this.toggle(B,a)},this.options.show.delay))}function n(a){if(!this.tooltip.hasClass($)&&!this.destroyed){var b=d(a.relatedTarget),c=b.closest(U)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=l.call(this,function(){this.toggle(C,a)},this.options.hide.delay,this)}}function o(a){!this.tooltip.hasClass($)&&this.options.hide.inactive&&(clearTimeout(this.timers.inactive),this.timers.inactive=l.call(this,function(){this.hide(a)},this.options.hide.inactive))}function p(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function q(a,c,e){d(b.body).delegate(a,(c.split?c:c.join("."+Q+" "))+"."+Q,function(){var a=w.api[d.attr(this,S)];a&&!a.disabled&&e.apply(a,arguments)})}function r(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):D,p="html5"===f.metadata.type&&o?o[f.metadata.name]:D,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(B,{},w.defaults,f,"object"==typeof q?h(q):D,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===C||!j)return C;k.content.text=j}if(i.container.length||(i.container=m),i.target===C&&(i.target=n),k.show.target===C&&(k.show.target=n),k.show.solo===B&&(k.show.solo=i.container.closest("body")),k.hide.target===C&&(k.hide.target=n),k.position.viewport===B&&(k.position.viewport=i.container),i.container=i.container.eq(0),i.at=new y(i.at,B),i.my=new y(i.my),a.data(Q))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===C)return C;return a.attr(R,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(aa,l).attr("title",""),g=new e(a,k,c,!!j),a.data(Q,g),g}function s(a){return a.charAt(0).toUpperCase()+a.slice(1)}function t(a,b){var d,e,f=b.charAt(0).toUpperCase()+b.slice(1),g=(b+" "+ta.join(f+" ")+f).split(" "),h=0;if(sa[b])return a.css(sa[b]);for(;d=g[h++];)if((e=a.css(d))!==c)return sa[b]=d,e}function u(a,b){return Math.ceil(parseFloat(t(a,b)))}function v(a,b){this._ns="tip",this.options=b,this.offset=b.offset,this.size=[b.width,b.height],this.qtip=a,this.init(a)}var w,x,y,z,A,B=!0,C=!1,D=null,E="x",F="y",G="width",H="height",I="top",J="left",K="bottom",L="right",M="center",N="flipinvert",O="shift",P={},Q="qtip",R="data-hasqtip",S="data-qtip-id",T=["ui-widget","ui-tooltip"],U="."+Q,V="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),W=Q+"-fixed",X=Q+"-default",Y=Q+"-focus",Z=Q+"-hover",$=Q+"-disabled",_="_replacedByqTip",aa="oldtitle",ba={ie:function(){var a,c;for(a=4,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];a+=1);return a>4?a:NaN}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||C};x=e.prototype,x._when=function(a){return d.when.apply(d,a)},x.render=function(a){if(this.rendered||this.destroyed)return this;var b=this,c=this.options,e=this.cache,f=this.elements,g=c.content.text,h=c.content.title,i=c.content.button,j=c.position,k=[];return d.attr(this.target[0],"aria-describedby",this._id),e.posClass=this._createPosClass((this.position={my:j.my,at:j.at}).my),this.tooltip=f.tooltip=d("<div/>",{id:this._id,"class":[Q,X,c.style.classes,e.posClass].join(" "),width:c.style.width||"",height:c.style.height||"",tracking:"mouse"===j.target&&j.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":C,"aria-describedby":this._id+"-content","aria-hidden":B}).toggleClass($,this.disabled).attr(S,this.id).data(Q,this).appendTo(j.container).append(f.content=d("<div />",{"class":Q+"-content",id:this._id+"-content","aria-atomic":B})),this.rendered=-1,this.positioning=B,h&&(this._createTitle(),d.isFunction(h)||k.push(this._updateTitle(h,C))),i&&this._createButton(),d.isFunction(g)||k.push(this._updateContent(g,C)),this.rendered=B,this._setWidget(),d.each(P,function(a){var c;"render"===this.initialize&&(c=this(b))&&(b.plugins[a]=c)}),this._unassignEvents(),this._assignEvents(),this._when(k).then(function(){b._trigger("render"),b.positioning=C,b.hiddenDuringWait||!c.show.ready&&!a||b.toggle(B,e.event,C),b.hiddenDuringWait=C}),w.api[this.id]=this,this},x.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=B;var a,b=this.target,c=b.attr(aa);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()});for(a in this.timers)this.timers.hasOwnProperty(a)&&clearTimeout(this.timers[a]);b.removeData(Q).removeAttr(S).removeAttr(R).removeAttr("aria-describedby"),this.options.suppress&&c&&b.attr("title",c).removeAttr(aa),this._unassignEvents(),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=D,delete w.api[this.id]}}return this.destroyed?this.target:(a===B&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},z=x.checks={builtin:{"^id$":function(a,b,c,e){var f=c===B?w.nextid:c,g=Q+"-"+f;f!==C&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),void this._updateTitle(c)):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)},"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(this.position[b]=a[b]=new y(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(B)||this.toggle(B))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(X,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},x.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var ca=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,da=/^prerender|show\.ready/i;x.set=function(a,b){if(this.destroyed)return this;var c,e=this.rendered,f=C,g=this.options;return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&da.test(b))return void delete a[b];var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=ca.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=B,d.each(a,d.proxy(j,this)),this.positioning=C,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?D:this.cache.event),this},x._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=B,a.then(function(a){return e.waiting=C,c._update(a,b)},D,function(a){return c._update(a,b)})):a===C||!a&&""!==a?C:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):C},x._waitForContent=function(a){var b=this.cache;return b.waiting=B,(d.fn.imagesLoaded?a.imagesLoaded():(new d.Deferred).resolve([])).done(function(){b.waiting=C}).promise()},x._updateContent=function(a,b){this._update(a,this.elements.content,b)},x._updateTitle=function(a,b){this._update(a,this.elements.title,b)===C&&this._removeTitle(C)},x._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":Q+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":Q+"-title","aria-atomic":B})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},x._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=D,a!==C&&this.reposition())},x._createPosClass=function(a){return Q+"-pos-"+(a||this.options.position.my).abbrev()},x.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=B;var f,g,h,i,j=this.cache,k=this.tooltip,l=this.options.position,m=l.target,n=l.my,o=l.at,p=l.viewport,q=l.container,r=l.adjust,s=r.method.split(" "),t=k.outerWidth(C),u=k.outerHeight(C),v=0,w=0,x=k.css("position"),y={left:0,top:0},z=k[0].offsetWidth>0,A=c&&"scroll"===c.type,D=d(a),E=q[0].ownerDocument,F=this.mouse;if(d.isArray(m)&&2===m.length)o={x:J,y:I},y={left:m[0],top:m[1]};else if("mouse"===m)o={x:J,y:I},(!r.mouse||this.options.hide.distance)&&j.origin&&j.origin.pageX?c=j.origin:!c||c&&("resize"===c.type||"scroll"===c.type)?c=j.event:F&&F.pageX&&(c=F),"static"!==x&&(y=q.offset()),E.body.offsetWidth!==(a.innerWidth||E.documentElement.clientWidth)&&(g=d(b.body).offset()),y={left:c.pageX-y.left+(g&&g.left||0),top:c.pageY-y.top+(g&&g.top||0)},r.mouse&&A&&F&&(y.left-=(F.scrollX||0)-D.scrollLeft(),y.top-=(F.scrollY||0)-D.scrollTop());else{if("event"===m?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?j.target=d(c.target):c.target||(j.target=this.elements.target):"event"!==m&&(j.target=d(m.jquery?m:this.elements.target)),m=j.target,m=d(m).eq(0),0===m.length)return this;m[0]===b||m[0]===a?(v=ba.iOS?a.innerWidth:m.width(),w=ba.iOS?a.innerHeight:m.height(),m[0]===a&&(y={top:(p||m).scrollTop(),left:(p||m).scrollLeft()})):P.imagemap&&m.is("area")?f=P.imagemap(this,m,o,P.viewport?s:C):P.svg&&m&&m[0].ownerSVGElement?f=P.svg(this,m,o,P.viewport?s:C):(v=m.outerWidth(C),w=m.outerHeight(C),y=m.offset()),f&&(v=f.width,w=f.height,g=f.offset,y=f.position),y=this.reposition.offset(m,y,q),(ba.iOS>3.1&&ba.iOS<4.1||ba.iOS>=4.3&&ba.iOS<4.33||!ba.iOS&&"fixed"===x)&&(y.left-=D.scrollLeft(),y.top-=D.scrollTop()),(!f||f&&f.adjustable!==C)&&(y.left+=o.x===L?v:o.x===M?v/2:0,y.top+=o.y===K?w:o.y===M?w/2:0)}return y.left+=r.x+(n.x===L?-t:n.x===M?-t/2:0),y.top+=r.y+(n.y===K?-u:n.y===M?-u/2:0),P.viewport?(h=y.adjusted=P.viewport(this,y,l,v,w,t,u),g&&h.left&&(y.left+=g.left),g&&h.top&&(y.top+=g.top),h.my&&(this.position.my=h.my)):y.adjusted={left:0,top:0},j.posClass!==(i=this._createPosClass(this.position.my))&&(j.posClass=i,k.removeClass(j.posClass).addClass(i)),this._trigger("move",[y,p.elem||p],c)?(delete y.adjusted,e===C||!z||isNaN(y.left)||isNaN(y.top)||"mouse"===m||!d.isFunction(l.effect)?k.css(y):d.isFunction(l.effect)&&(l.effect.call(k,this,d.extend({},y)),k.queue(function(a){d(this).css({opacity:"",height:""}),ba.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=C,this):this},x.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!ba.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var ea=(y=x.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,M).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?F:E}).prototype;ea.invert=function(a,b){this[a]=this[a]===J?L:this[a]===L?J:b||this[a]},ea.string=function(a){var b=this.x,c=this.y,d=b!==c?"center"===b||"center"!==c&&(this.precedance===F||this.forceY)?[c,b]:[b,c]:[b];return a!==!1?d.join(" "):d},ea.abbrev=function(){var a=this.string(!1);return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},ea.clone=function(){return new y(this.string(),this.forceY)},x.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&e.event&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=d.event.fix(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=B),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",l=this.options[k],m=this.options.position,n=this.options.content,o=this.tooltip.css("width"),p=this.tooltip.is(":visible"),q=a||1===l.target.length,r=!c||l.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!p),h=!g.is(":animated")&&p===a&&r,i=h?D:!!this._trigger(k,[90]),this.destroyed?this:(i!==C&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(this.mouse&&(e.origin=d.event.fix(this.mouse)),d.isFunction(n.text)&&this._updateContent(n.text,C),d.isFunction(n.title)&&this._updateTitle(n.title,C),!A&&"mouse"===m.target&&m.adjust.mouse&&(d(b).bind("mousemove."+Q,this._storeMouse),A=B),o||g.css("width",g.outerWidth(C)),this.reposition(c,arguments[2]),o||g.css("width",""),l.solo&&("string"==typeof l.solo?d(l.solo):d(U,l.solo)).not(g).not(l.target).qtip("hide",new d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,A&&!d(U+'[tracking="true"]:visible',l.solo).not(g).length&&(d(b).unbind("mousemove."+Q),A=C),this.blur(c)),j=d.proxy(function(){a?(ba.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof l.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),l.effect===C||q===C?(g[k](),j()):d.isFunction(l.effect)?(g.stop(1,1),l.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&l.target.trigger("qtip-"+this.id+"-inactive"),this))},x.show=function(a){return this.toggle(B,a)},x.hide=function(a){return this.toggle(C,a)},x.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(U),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=w.zindex+b.length;return c.hasClass(Y)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+Y).qtip("blur",a)),c.addClass(Y)[0].style.zIndex=f),this},x.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(Y),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},x.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass($):this.disabled):"boolean"!=typeof a&&(a=B),this.rendered&&this.tooltip.toggleClass($,a).attr("aria-disabled",a),this.disabled=!!a,this)},x.enable=function(){return this.disable(C)},x._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),e.jquery?b.button=e:b.button=d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":Q+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass($)||a.hide(b),C})},x._updateButton=function(a){if(!this.rendered)return C;var b=this.elements.button;a?this._createButton():b.remove()},x._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass($);c.removeClass($),$=a?"ui-state-disabled":"qtip-disabled",c.toggleClass($,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(X,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(Q+"-icon",!a)},x._storeMouse=function(a){return(this.mouse=d.event.fix(a)).type="mousemove",this},x._bind=function(a,b,c,e,f){if(a&&c&&b.length){var g="."+this._id+(e?"-"+e:"");return d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this)),this}},x._unbind=function(a,b){return a&&d(a).unbind("."+this._id+(b?"-"+b:"")),this},x._trigger=function(a,b,c){var e=new d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||D,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=C,!e.isDefaultPrevented()},x._bindEvents=function(a,b,c,e,f,g){var h=c.filter(e).add(e.filter(c)),i=[];h.length&&(d.each(b,function(b,c){var e=d.inArray(c,a);e>-1&&i.push(a.splice(e,1)[0])}),i.length&&(this._bind(h,i,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)}),c=c.not(h),e=e.not(h))),this._bind(c,a,f),this._bind(e,b,g)},x._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?C:(this.cache.event=a&&d.event.fix(a),this.cache.target=a&&d(a.target),clearTimeout(this.timers.show),void(this.timers.show=l.call(this,function(){this.render("object"==typeof a||c.show.ready)},c.prerender?0:c.show.delay)))}var c=this.options,e=c.show.target,f=c.hide.target,g=c.show.event?d.trim(""+c.show.event).split(" "):[],h=c.hide.event?d.trim(""+c.hide.event).split(" "):[];this._bind(this.elements.target,["remove","removeqtip"],function(){this.destroy(!0)},"destroy"),/mouse(over|enter)/i.test(c.show.event)&&!/mouse(out|leave)/i.test(c.hide.event)&&h.push("mouseleave"),this._bind(e,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=B}),this._bindEvents(g,h,e,f,b,function(){return this.timers?void clearTimeout(this.timers.show):C}),(c.show.ready||c.prerender)&&b.call(this,a)},x._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),q=d(a),r=e.show.event?d.trim(""+e.show.event).split(" "):[],s=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(W)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass($)&&this.tooltip[0].offsetWidth>0,e=b.parents(U).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",o,"inactive"),this._bind(i.add(g),w.inactiveEvents,o)),this._bindEvents(r,s,h,i,m,n),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){return this.cache?void(this.cache.onTarget="mouseenter"===a.type):C}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass($)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:q,"resize",p),f.adjust.scroll&&this._bind(q.add(f.container),"scroll",p)},x._unassignEvents=function(){var c=this.options,e=c.show.target,f=c.hide.target,g=d.grep([this.elements.target[0],this.rendered&&this.tooltip[0],c.position.container[0],c.position.viewport[0],c.position.container.closest("html")[0],a,b],function(a){return"object"==typeof a});e&&e.toArray&&(g=g.concat(e.toArray())),f&&f.toArray&&(g=g.concat(f.toArray())),this._unbind(g)._unbind(g,"destroy")._unbind(g,"inactive")},d(function(){q(U,["mouseenter","mouseleave"],function(a){var b="mouseenter"===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(W)&&!c.hasClass($)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.position.adjust.mouse&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass(Z,b)}),q("["+S+"]",V,o)}),w=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=D,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],Q):D;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,Q);if(!a)return B;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),C;a.set(b,e)}}),g!==D?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(B,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===C||c.length<1||w.api[c]?w.nextid++:c,b=r(d(this),c,k),b===C?B:(w.api[c]=b,d.each(P,function(){"initialize"===this.initialize&&this(b)}),void b._assignInitialEvents(j))}))},d.qtip=e,w.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&f.options&&"object"==typeof f&&"object"==typeof f.options&&f.options.suppress)return arguments.length<2?d.attr(c,aa):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(aa,b))}return d.fn["attr"+_].apply(this,arguments)},clone:function(a){var b=d.fn["clone"+_].apply(this,arguments);return a||b.filter("["+aa+"]").attr("title",function(){return d.attr(this,aa)}).removeAttr(aa),b}},function(a,b){if(!b||d.fn[a+_])return B;var c=d.fn[a+_]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+_]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(R))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+_].apply(this,arguments)}),w.version="3.0.3",w.nextid=0,w.inactiveEvents=V,w.zindex=15e3,w.defaults={prerender:C,id:C,overwrite:B,suppress:B,content:{text:B,attr:"title",title:C,button:C},position:{my:"top left",at:"bottom right",target:C,container:C,viewport:C,adjust:{x:0,y:0,mouse:B,scroll:B,resize:B,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:C})}},show:{target:C,event:"mouseenter",effect:B,delay:90,solo:C,ready:C,autofocus:C},hide:{target:C,event:"mouseleave",effect:B,delay:0,fixed:C,inactive:C,leave:"window",distance:C},style:{classes:"",widget:C,width:C,height:C,def:B},events:{render:D,move:D,show:D,hide:D,toggle:D,visible:D,hidden:D,focus:D,blur:D}};var fa,ga,ha,ia,ja,ka="margin",la="border",ma="color",na="background-color",oa="transparent",pa=" !important",qa=!!b.createElement("canvas").getContext,ra=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,sa={},ta=["Webkit","O","Moz","ms"];qa?(ia=a.devicePixelRatio||1,ja=function(){var a=b.createElement("canvas").getContext("2d");return a.backingStorePixelRatio||a.webkitBackingStorePixelRatio||a.mozBackingStorePixelRatio||a.msBackingStorePixelRatio||a.oBackingStorePixelRatio||1}(),ha=ia/ja):ga=function(a,b,c){return"<qtipvml:"+a+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(b||"")+' style="behavior: url(#default#VML); '+(c||"")+'" />'},d.extend(v.prototype,{init:function(a){var b,c;c=this.element=a.elements.tip=d("<div />",{"class":Q+"-tip"}).prependTo(a.tooltip),qa?(b=d("<canvas />").appendTo(this.element)[0].getContext("2d"),b.lineJoin="miter",b.miterLimit=1e5,b.save()):(b=ga("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(b+b),a._bind(d("*",c).add(c),["click","mousedown"],function(a){a.stopPropagation()},this._ns)),a._bind(a.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(a){var b=this.qtip.elements.titlebar;return b&&(a.y===I||a.y===M&&this.element.position().top+this.size[1]/2+this.options.offset<b.outerHeight(B))},_parseCorner:function(a){var b=this.qtip.options.position.my;return a===C||b===C?a=C:a===B?a=new y(b.string()):a.string||(a=new y(a),a.fixed=B),a},_parseWidth:function(a,b,c){var d=this.qtip.elements,e=la+s(b)+"Width";return(c?u(c,e):u(d.content,e)||u(this._useTitle(a)&&d.titlebar||d.content,e)||u(d.tooltip,e))||0},_parseRadius:function(a){var b=this.qtip.elements,c=la+s(a.y)+s(a.x)+"Radius";return ba.ie<9?0:u(this._useTitle(a)&&b.titlebar||b.content,c)||u(b.tooltip,c)||0},_invalidColour:function(a,b,c){var d=a.css(b);return!d||c&&d===a.css(c)||ra.test(d)?C:d},_parseColours:function(a){var b=this.qtip.elements,c=this.element.css("cssText",""),e=la+s(a[a.precedance])+s(ma),f=this._useTitle(a)&&b.titlebar||b.content,g=this._invalidColour,h=[];return h[0]=g(c,na)||g(f,na)||g(b.content,na)||g(b.tooltip,na)||c.css(na),h[1]=g(c,e,ma)||g(f,e,ma)||g(b.content,e,ma)||g(b.tooltip,e,ma)||b.tooltip.css(e),d("*",c).add(c).css("cssText",na+":"+oa+pa+";"+la+":0"+pa+";"),h},_calculateSize:function(a){var b,c,d,e=a.precedance===F,f=this.options.width,g=this.options.height,h="c"===a.abbrev(),i=(e?f:g)*(h?.5:1),j=Math.pow,k=Math.round,l=Math.sqrt(j(i,2)+j(g,2)),m=[this.border/i*l,this.border/g*l];return m[2]=Math.sqrt(j(m[0],2)-j(this.border,2)),m[3]=Math.sqrt(j(m[1],2)-j(this.border,2)),b=l+m[2]+m[3]+(h?0:m[0]),c=b/l,d=[k(c*f),k(c*g)],e?d:d.reverse()},_calculateTip:function(a,b,c){c=c||1,b=b||this.size;var d=b[0]*c,e=b[1]*c,f=Math.ceil(d/2),g=Math.ceil(e/2),h={br:[0,0,d,e,d,0],bl:[0,0,d,0,0,e],tr:[0,e,d,0,d,e],tl:[0,0,0,e,d,e],tc:[0,e,f,0,d,e],bc:[0,0,d,0,f,e],rc:[0,0,d,g,0,e],lc:[d,0,d,e,0,g]};return h.lt=h.br,h.rt=h.bl,h.lb=h.tr,h.rb=h.tl,h[a.abbrev()]},_drawCoords:function(a,b){a.beginPath(),a.moveTo(b[0],b[1]),a.lineTo(b[2],b[3]),a.lineTo(b[4],b[5]),a.closePath()},create:function(){var a=this.corner=(qa||ba.ie)&&this._parseCorner(this.options.corner);return this.enabled=!!this.corner&&"c"!==this.corner.abbrev(),this.enabled&&(this.qtip.cache.corner=a.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(b,c){if(!this.enabled)return this;var e,f,g,h,i,j,k,l,m=this.qtip.elements,n=this.element,o=n.children(),p=this.options,q=this.size,r=p.mimic,s=Math.round;b||(b=this.qtip.cache.corner||this.corner),r===C?r=b:(r=new y(r),r.precedance=b.precedance,"inherit"===r.x?r.x=b.x:"inherit"===r.y?r.y=b.y:r.x===r.y&&(r[b.precedance]=b[b.precedance])),f=r.precedance,b.precedance===E?this._swapDimensions():this._resetDimensions(),e=this.color=this._parseColours(b),e[1]!==oa?(l=this.border=this._parseWidth(b,b[b.precedance]),p.border&&1>l&&!ra.test(e[1])&&(e[0]=e[1]),this.border=l=p.border!==B?p.border:l):this.border=l=0,k=this.size=this._calculateSize(b),n.css({width:k[0],height:k[1],lineHeight:k[1]+"px"}),j=b.precedance===F?[s(r.x===J?l:r.x===L?k[0]-q[0]-l:(k[0]-q[0])/2),s(r.y===I?k[1]-q[1]:0)]:[s(r.x===J?k[0]-q[0]:0),s(r.y===I?l:r.y===K?k[1]-q[1]-l:(k[1]-q[1])/2)],qa?(g=o[0].getContext("2d"),g.restore(),g.save(),g.clearRect(0,0,6e3,6e3),h=this._calculateTip(r,q,ha),i=this._calculateTip(r,this.size,ha),o.attr(G,k[0]*ha).attr(H,k[1]*ha),o.css(G,k[0]).css(H,k[1]),this._drawCoords(g,i),g.fillStyle=e[1],g.fill(),g.translate(j[0]*ha,j[1]*ha),this._drawCoords(g,h),g.fillStyle=e[0],g.fill()):(h=this._calculateTip(r),h="m"+h[0]+","+h[1]+" l"+h[2]+","+h[3]+" "+h[4]+","+h[5]+" xe",j[2]=l&&/^(r|b)/i.test(b.string())?8===ba.ie?2:1:0,o.css({coordsize:k[0]+l+" "+k[1]+l,antialias:""+(r.string().indexOf(M)>-1),left:j[0]-j[2]*Number(f===E),top:j[1]-j[2]*Number(f===F),width:k[0]+l,height:k[1]+l}).each(function(a){var b=d(this);b[b.prop?"prop":"attr"]({coordsize:k[0]+l+" "+k[1]+l,path:h,fillcolor:e[0],filled:!!a,stroked:!a}).toggle(!(!l&&!a)),!a&&b.html(ga("stroke",'weight="'+2*l+'px" color="'+e[1]+'" miterlimit="1000" joinstyle="miter"'))})),a.opera&&setTimeout(function(){m.tip.css({display:"inline-block",visibility:"visible"})},1),c!==C&&this.calculate(b,k)},calculate:function(a,b){if(!this.enabled)return C;var c,e,f=this,g=this.qtip.elements,h=this.element,i=this.options.offset,j={};return a=a||this.corner,c=a.precedance,b=b||this._calculateSize(a),e=[a.x,a.y],c===E&&e.reverse(),d.each(e,function(d,e){var h,k,l;e===M?(h=c===F?J:I,j[h]="50%",j[ka+"-"+h]=-Math.round(b[c===F?0:1]/2)+i):(h=f._parseWidth(a,e,g.tooltip),k=f._parseWidth(a,e,g.content),l=f._parseRadius(a),j[e]=Math.max(-f.border,d?k:i+(l>h?l:-h)))}),j[a[c]]-=b[c===E?0:1],h.css({margin:"",top:"",bottom:"",left:"",right:""}).css(j),j},reposition:function(a,b,d){function e(a,b,c,d,e){a===O&&j.precedance===b&&k[d]&&j[c]!==M?j.precedance=j.precedance===E?F:E:a!==O&&k[d]&&(j[b]=j[b]===M?k[d]>0?d:e:j[b]===d?e:d)}function f(a,b,e){j[a]===M?p[ka+"-"+b]=o[a]=g[ka+"-"+b]-k[b]:(h=g[e]!==c?[k[b],-g[b]]:[-k[b],g[b]],(o[a]=Math.max(h[0],h[1]))>h[0]&&(d[b]-=k[b],o[b]=C),p[g[e]!==c?e:b]=o[a])}if(this.enabled){var g,h,i=b.cache,j=this.corner.clone(),k=d.adjusted,l=b.options.position.adjust.method.split(" "),m=l[0],n=l[1]||l[0],o={left:C,top:C,x:0,y:0},p={};this.corner.fixed!==B&&(e(m,E,F,J,L),e(n,F,E,I,K),j.string()===i.corner.string()&&i.cornerTop===k.top&&i.cornerLeft===k.left||this.update(j,C)),g=this.calculate(j),g.right!==c&&(g.left=-g.right),g.bottom!==c&&(g.top=-g.bottom),g.user=this.offset,o.left=m===O&&!!k.left,o.left&&f(E,J,L),o.top=n===O&&!!k.top,o.top&&f(F,I,K),this.element.css(p).toggle(!(o.x&&o.y||j.x===M&&o.y||j.y===M&&o.x)),d.left-=g.left.charAt?g.user:m!==O||o.top||!o.left&&!o.top?g.left+this.border:0,d.top-=g.top.charAt?g.user:n!==O||o.left||!o.left&&!o.top?g.top+this.border:0,i.cornerLeft=k.left,i.cornerTop=k.top,i.corner=j.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),fa=P.tip=function(a){return new v(a,a.options.style.tip)},fa.initialize="render",fa.sanitize=function(a){if(a.style&&"tip"in a.style){var b=a.style.tip;"object"!=typeof b&&(b=a.style.tip={corner:b}),/string|boolean/i.test(typeof b.corner)||(b.corner=B)}},z.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(a){this.size=[a.width,a.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},d.extend(B,w.defaults,{style:{tip:{corner:B,mimic:C,width:6,height:6,border:B,offset:0}}}),P.viewport=function(c,d,e,f,g,h,i){function j(a,b,c,e,f,g,h,i,j){var k=d[f],s=u[a],t=v[a],w=c===O,x=s===f?j:s===g?-j:-j/2,y=t===f?i:t===g?-i:-i/2,z=q[f]+r[f]-(n?0:m[f]),A=z-k,B=k+j-(h===G?o:p)-z,C=x-(u.precedance===a||s===u[b]?y:0)-(t===M?i/2:0);return w?(C=(s===f?1:-1)*x,d[f]+=A>0?A:B>0?-B:0,d[f]=Math.max(-m[f]+r[f],k-C,Math.min(Math.max(-m[f]+r[f]+(h===G?o:p),k+C),d[f],"center"===s?k-x:1e9))):(e*=c===N?2:0,A>0&&(s!==f||B>0)?(d[f]-=C+e,l.invert(a,f)):B>0&&(s!==g||A>0)&&(d[f]-=(s===M?-C:C)+e,l.invert(a,g)),d[f]<q[f]&&-d[f]>B&&(d[f]=k,l=u.clone())),d[f]-k}var k,l,m,n,o,p,q,r,s=e.target,t=c.elements.tooltip,u=e.my,v=e.at,w=e.adjust,x=w.method.split(" "),y=x[0],z=x[1]||x[0],A=e.viewport,B=e.container,D={left:0,top:0};return A.jquery&&s[0]!==a&&s[0]!==b.body&&"none"!==w.method?(m=B.offset()||D,n="static"===B.css("position"),k="fixed"===t.css("position"),o=A[0]===a?A.width():A.outerWidth(C),p=A[0]===a?A.height():A.outerHeight(C),q={left:k?0:A.scrollLeft(),top:k?0:A.scrollTop()},r=A.offset()||D,"shift"===y&&"shift"===z||(l=u.clone()),D={left:"none"!==y?j(E,F,y,w.x,J,L,G,f,h):0,top:"none"!==z?j(F,E,z,w.y,I,K,H,g,i):0,my:l}):D}})}(window,document);
487
 
488
- /* bootstrap-switch v3.3.2 | http://www.bootstrap-switch.org | Copyright (c) 2012-2013 Mattia Larentis. Released under the Apache 2.0 license. */
489
- (function(){var t=[].slice;!function(e,i){"use strict";var n;return n=function(){function t(t,i){null==i&&(i={}),this.$element=e(t),this.options=e.extend({},e.fn.bootstrapSwitch.defaults,{state:this.$element.is(":checked"),size:this.$element.data("size"),animate:this.$element.data("animate"),disabled:this.$element.is(":disabled"),readonly:this.$element.is("[readonly]"),indeterminate:this.$element.data("indeterminate"),inverse:this.$element.data("inverse"),radioAllOff:this.$element.data("radio-all-off"),onColor:this.$element.data("on-color"),offColor:this.$element.data("off-color"),onText:this.$element.data("on-text"),offText:this.$element.data("off-text"),labelText:this.$element.data("label-text"),handleWidth:this.$element.data("handle-width"),labelWidth:this.$element.data("label-width"),baseClass:this.$element.data("base-class"),wrapperClass:this.$element.data("wrapper-class")},i),this.prevOptions={},this.$wrapper=e("<div>",{"class":function(t){return function(){var e;return e=[""+t.options.baseClass].concat(t._getClasses(t.options.wrapperClass)),e.push(t.options.state?t.options.baseClass+"-on":t.options.baseClass+"-off"),null!=t.options.size&&e.push(t.options.baseClass+"-"+t.options.size),t.options.disabled&&e.push(t.options.baseClass+"-disabled"),t.options.readonly&&e.push(t.options.baseClass+"-readonly"),t.options.indeterminate&&e.push(t.options.baseClass+"-indeterminate"),t.options.inverse&&e.push(t.options.baseClass+"-inverse"),t.$element.attr("id")&&e.push(t.options.baseClass+"-id-"+t.$element.attr("id")),e.join(" ")}}(this)()}),this.$container=e("<div>",{"class":this.options.baseClass+"-container"}),this.$on=e("<span>",{html:this.options.onText,"class":this.options.baseClass+"-handle-on "+this.options.baseClass+"-"+this.options.onColor}),this.$off=e("<span>",{html:this.options.offText,"class":this.options.baseClass+"-handle-off "+this.options.baseClass+"-"+this.options.offColor}),this.$label=e("<span>",{html:this.options.labelText,"class":this.options.baseClass+"-label"}),this.$element.on("init.bootstrapSwitch",function(e){return function(){return e.options.onInit.apply(t,arguments)}}(this)),this.$element.on("switchChange.bootstrapSwitch",function(i){return function(n){return!1===i.options.onSwitchChange.apply(t,arguments)?i.$element.is(":radio")?e("[name='"+i.$element.attr("name")+"']").trigger("previousState.bootstrapSwitch",!0):i.$element.trigger("previousState.bootstrapSwitch",!0):void 0}}(this)),this.$container=this.$element.wrap(this.$container).parent(),this.$wrapper=this.$container.wrap(this.$wrapper).parent(),this.$element.before(this.options.inverse?this.$off:this.$on).before(this.$label).before(this.options.inverse?this.$on:this.$off),this.options.indeterminate&&this.$element.prop("indeterminate",!0),this._init(),this._elementHandlers(),this._handleHandlers(),this._labelHandlers(),this._formHandler(),this._externalLabelHandler(),this.$element.trigger("init.bootstrapSwitch",this.options.state)}return t.prototype._constructor=t,t.prototype.setPrevOptions=function(){return this.prevOptions=e.extend(!0,{},this.options)},t.prototype.state=function(t,i){return"undefined"==typeof t?this.options.state:this.options.disabled||this.options.readonly?this.$element:this.options.state&&!this.options.radioAllOff&&this.$element.is(":radio")?this.$element:(this.$element.is(":radio")?e("[name='"+this.$element.attr("name")+"']").trigger("setPreviousOptions.bootstrapSwitch"):this.$element.trigger("setPreviousOptions.bootstrapSwitch"),this.options.indeterminate&&this.indeterminate(!1),t=!!t,this.$element.prop("checked",t).trigger("change.bootstrapSwitch",i),this.$element)},t.prototype.toggleState=function(t){return this.options.disabled||this.options.readonly?this.$element:this.options.indeterminate?(this.indeterminate(!1),this.state(!0)):this.$element.prop("checked",!this.options.state).trigger("change.bootstrapSwitch",t)},t.prototype.size=function(t){return"undefined"==typeof t?this.options.size:(null!=this.options.size&&this.$wrapper.removeClass(this.options.baseClass+"-"+this.options.size),t&&this.$wrapper.addClass(this.options.baseClass+"-"+t),this._width(),this._containerPosition(),this.options.size=t,this.$element)},t.prototype.animate=function(t){return"undefined"==typeof t?this.options.animate:(t=!!t,t===this.options.animate?this.$element:this.toggleAnimate())},t.prototype.toggleAnimate=function(){return this.options.animate=!this.options.animate,this.$wrapper.toggleClass(this.options.baseClass+"-animate"),this.$element},t.prototype.disabled=function(t){return"undefined"==typeof t?this.options.disabled:(t=!!t,t===this.options.disabled?this.$element:this.toggleDisabled())},t.prototype.toggleDisabled=function(){return this.options.disabled=!this.options.disabled,this.$element.prop("disabled",this.options.disabled),this.$wrapper.toggleClass(this.options.baseClass+"-disabled"),this.$element},t.prototype.readonly=function(t){return"undefined"==typeof t?this.options.readonly:(t=!!t,t===this.options.readonly?this.$element:this.toggleReadonly())},t.prototype.toggleReadonly=function(){return this.options.readonly=!this.options.readonly,this.$element.prop("readonly",this.options.readonly),this.$wrapper.toggleClass(this.options.baseClass+"-readonly"),this.$element},t.prototype.indeterminate=function(t){return"undefined"==typeof t?this.options.indeterminate:(t=!!t,t===this.options.indeterminate?this.$element:this.toggleIndeterminate())},t.prototype.toggleIndeterminate=function(){return this.options.indeterminate=!this.options.indeterminate,this.$element.prop("indeterminate",this.options.indeterminate),this.$wrapper.toggleClass(this.options.baseClass+"-indeterminate"),this._containerPosition(),this.$element},t.prototype.inverse=function(t){return"undefined"==typeof t?this.options.inverse:(t=!!t,t===this.options.inverse?this.$element:this.toggleInverse())},t.prototype.toggleInverse=function(){var t,e;return this.$wrapper.toggleClass(this.options.baseClass+"-inverse"),e=this.$on.clone(!0),t=this.$off.clone(!0),this.$on.replaceWith(t),this.$off.replaceWith(e),this.$on=t,this.$off=e,this.options.inverse=!this.options.inverse,this.$element},t.prototype.onColor=function(t){var e;return e=this.options.onColor,"undefined"==typeof t?e:(null!=e&&this.$on.removeClass(this.options.baseClass+"-"+e),this.$on.addClass(this.options.baseClass+"-"+t),this.options.onColor=t,this.$element)},t.prototype.offColor=function(t){var e;return e=this.options.offColor,"undefined"==typeof t?e:(null!=e&&this.$off.removeClass(this.options.baseClass+"-"+e),this.$off.addClass(this.options.baseClass+"-"+t),this.options.offColor=t,this.$element)},t.prototype.onText=function(t){return"undefined"==typeof t?this.options.onText:(this.$on.html(t),this._width(),this._containerPosition(),this.options.onText=t,this.$element)},t.prototype.offText=function(t){return"undefined"==typeof t?this.options.offText:(this.$off.html(t),this._width(),this._containerPosition(),this.options.offText=t,this.$element)},t.prototype.labelText=function(t){return"undefined"==typeof t?this.options.labelText:(this.$label.html(t),this._width(),this.options.labelText=t,this.$element)},t.prototype.handleWidth=function(t){return"undefined"==typeof t?this.options.handleWidth:(this.options.handleWidth=t,this._width(),this._containerPosition(),this.$element)},t.prototype.labelWidth=function(t){return"undefined"==typeof t?this.options.labelWidth:(this.options.labelWidth=t,this._width(),this._containerPosition(),this.$element)},t.prototype.baseClass=function(t){return this.options.baseClass},t.prototype.wrapperClass=function(t){return"undefined"==typeof t?this.options.wrapperClass:(t||(t=e.fn.bootstrapSwitch.defaults.wrapperClass),this.$wrapper.removeClass(this._getClasses(this.options.wrapperClass).join(" ")),this.$wrapper.addClass(this._getClasses(t).join(" ")),this.options.wrapperClass=t,this.$element)},t.prototype.radioAllOff=function(t){return"undefined"==typeof t?this.options.radioAllOff:(t=!!t,t===this.options.radioAllOff?this.$element:(this.options.radioAllOff=t,this.$element))},t.prototype.onInit=function(t){return"undefined"==typeof t?this.options.onInit:(t||(t=e.fn.bootstrapSwitch.defaults.onInit),this.options.onInit=t,this.$element)},t.prototype.onSwitchChange=function(t){return"undefined"==typeof t?this.options.onSwitchChange:(t||(t=e.fn.bootstrapSwitch.defaults.onSwitchChange),this.options.onSwitchChange=t,this.$element)},t.prototype.destroy=function(){var t;return t=this.$element.closest("form"),t.length&&t.off("reset.bootstrapSwitch").removeData("bootstrap-switch"),this.$container.children().not(this.$element).remove(),this.$element.unwrap().unwrap().off(".bootstrapSwitch").removeData("bootstrap-switch"),this.$element},t.prototype._width=function(){var t,e;return t=this.$on.add(this.$off),t.add(this.$label).css("width",""),e="auto"===this.options.handleWidth?Math.max(this.$on.width(),this.$off.width()):this.options.handleWidth,t.width(e),this.$label.width(function(t){return function(i,n){return"auto"!==t.options.labelWidth?t.options.labelWidth:e>n?e:n}}(this)),this._handleWidth=this.$on.outerWidth(),this._labelWidth=this.$label.outerWidth(),this.$container.width(2*this._handleWidth+this._labelWidth),this.$wrapper.width(this._handleWidth+this._labelWidth)},t.prototype._containerPosition=function(t,e){return null==t&&(t=this.options.state),this.$container.css("margin-left",function(e){return function(){var i;return i=[0,"-"+e._handleWidth+"px"],e.options.indeterminate?"-"+e._handleWidth/2+"px":t?e.options.inverse?i[1]:i[0]:e.options.inverse?i[0]:i[1]}}(this)),e?setTimeout(function(){return e()},50):void 0},t.prototype._init=function(){var t,e;return t=function(t){return function(){return t.setPrevOptions(),t._width(),t._containerPosition(null,function(){return t.options.animate?t.$wrapper.addClass(t.options.baseClass+"-animate"):void 0})}}(this),this.$wrapper.is(":visible")?t():e=i.setInterval(function(n){return function(){return n.$wrapper.is(":visible")?(t(),i.clearInterval(e)):void 0}}(this),50)},t.prototype._elementHandlers=function(){return this.$element.on({"setPreviousOptions.bootstrapSwitch":function(t){return function(e){return t.setPrevOptions()}}(this),"previousState.bootstrapSwitch":function(t){return function(e){return t.options=t.prevOptions,t.options.indeterminate&&t.$wrapper.addClass(t.options.baseClass+"-indeterminate"),t.$element.prop("checked",t.options.state).trigger("change.bootstrapSwitch",!0)}}(this),"change.bootstrapSwitch":function(t){return function(i,n){var o;return i.preventDefault(),i.stopImmediatePropagation(),o=t.$element.is(":checked"),t._containerPosition(o),o!==t.options.state?(t.options.state=o,t.$wrapper.toggleClass(t.options.baseClass+"-off").toggleClass(t.options.baseClass+"-on"),n?void 0:(t.$element.is(":radio")&&e("[name='"+t.$element.attr("name")+"']").not(t.$element).prop("checked",!1).trigger("change.bootstrapSwitch",!0),t.$element.trigger("switchChange.bootstrapSwitch",[o]))):void 0}}(this),"focus.bootstrapSwitch":function(t){return function(e){return e.preventDefault(),t.$wrapper.addClass(t.options.baseClass+"-focused")}}(this),"blur.bootstrapSwitch":function(t){return function(e){return e.preventDefault(),t.$wrapper.removeClass(t.options.baseClass+"-focused")}}(this),"keydown.bootstrapSwitch":function(t){return function(e){if(e.which&&!t.options.disabled&&!t.options.readonly)switch(e.which){case 37:return e.preventDefault(),e.stopImmediatePropagation(),t.state(!1);case 39:return e.preventDefault(),e.stopImmediatePropagation(),t.state(!0)}}}(this)})},t.prototype._handleHandlers=function(){return this.$on.on("click.bootstrapSwitch",function(t){return function(e){return e.preventDefault(),e.stopPropagation(),t.state(!1),t.$element.trigger("focus.bootstrapSwitch")}}(this)),this.$off.on("click.bootstrapSwitch",function(t){return function(e){return e.preventDefault(),e.stopPropagation(),t.state(!0),t.$element.trigger("focus.bootstrapSwitch")}}(this))},t.prototype._labelHandlers=function(){return this.$label.on({click:function(t){return t.stopPropagation()},"mousedown.bootstrapSwitch touchstart.bootstrapSwitch":function(t){return function(e){return t._dragStart||t.options.disabled||t.options.readonly?void 0:(e.preventDefault(),e.stopPropagation(),t._dragStart=(e.pageX||e.originalEvent.touches[0].pageX)-parseInt(t.$container.css("margin-left"),10),t.options.animate&&t.$wrapper.removeClass(t.options.baseClass+"-animate"),t.$element.trigger("focus.bootstrapSwitch"))}}(this),"mousemove.bootstrapSwitch touchmove.bootstrapSwitch":function(t){return function(e){var i;if(null!=t._dragStart&&(e.preventDefault(),i=(e.pageX||e.originalEvent.touches[0].pageX)-t._dragStart,!(i<-t._handleWidth||i>0)))return t._dragEnd=i,t.$container.css("margin-left",t._dragEnd+"px")}}(this),"mouseup.bootstrapSwitch touchend.bootstrapSwitch":function(t){return function(e){var i;if(t._dragStart)return e.preventDefault(),t.options.animate&&t.$wrapper.addClass(t.options.baseClass+"-animate"),t._dragEnd?(i=t._dragEnd>-(t._handleWidth/2),t._dragEnd=!1,t.state(t.options.inverse?!i:i)):t.state(!t.options.state),t._dragStart=!1}}(this),"mouseleave.bootstrapSwitch":function(t){return function(e){return t.$label.trigger("mouseup.bootstrapSwitch")}}(this)})},t.prototype._externalLabelHandler=function(){var t;return t=this.$element.closest("label"),t.on("click",function(e){return function(i){return i.preventDefault(),i.stopImmediatePropagation(),i.target===t[0]?e.toggleState():void 0}}(this))},t.prototype._formHandler=function(){var t;return t=this.$element.closest("form"),t.data("bootstrap-switch")?void 0:t.on("reset.bootstrapSwitch",function(){return i.setTimeout(function(){return t.find("input").filter(function(){return e(this).data("bootstrap-switch")}).each(function(){return e(this).bootstrapSwitch("state",this.checked)})},1)}).data("bootstrap-switch",!0)},t.prototype._getClasses=function(t){var i,n,o,s;if(!e.isArray(t))return[this.options.baseClass+"-"+t];for(n=[],o=0,s=t.length;s>o;o++)i=t[o],n.push(this.options.baseClass+"-"+i);return n},t}(),e.fn.bootstrapSwitch=function(){var i,o,s;return o=arguments[0],i=2<=arguments.length?t.call(arguments,1):[],s=this,this.each(function(){var t,a;return t=e(this),a=t.data("bootstrap-switch"),a||t.data("bootstrap-switch",a=new n(this,o)),"string"==typeof o?s=a[o].apply(a,i):void 0}),s},e.fn.bootstrapSwitch.Constructor=n,e.fn.bootstrapSwitch.defaults={state:!0,size:null,animate:!0,disabled:!1,readonly:!1,indeterminate:!1,inverse:!1,radioAllOff:!1,onColor:"primary",offColor:"default",onText:"ON",offText:"OFF",labelText:"&nbsp;",handleWidth:"auto",labelWidth:"auto",baseClass:"bootstrap-switch",wrapperClass:"wrapper",onInit:function(){},onSwitchChange:function(){}}}(window.jQuery,window)}).call(this);
490
 
491
  /* caret v1.3.3 | https://github.com/accursoft/caret | Copyright (c) 2009 Gideon Sireling. Released under the BSD3 license. */
492
  !function(e){e.fn.caret=function(e){var t=this[0],n="true"===t.contentEditable;if(0==arguments.length){if(window.getSelection){if(n){t.focus();var o=window.getSelection().getRangeAt(0),r=o.cloneRange();return r.selectNodeContents(t),r.setEnd(o.endContainer,o.endOffset),r.toString().length}return t.selectionStart}if(document.selection){if(t.focus(),n){var o=document.selection.createRange(),r=document.body.createTextRange();return r.moveToElementText(t),r.setEndPoint("EndToEnd",o),r.text.length}var e=0,c=t.createTextRange(),r=document.selection.createRange().duplicate(),a=r.getBookmark();for(c.moveToBookmark(a);0!==c.moveStart("character",-1);)e++;return e}return t.selectionStart?t.selectionStart:0}if(-1==e&&(e=this[n?"text":"val"]().length),window.getSelection)n?(t.focus(),window.getSelection().collapse(t.firstChild,e)):t.setSelectionRange(e,e);else if(document.body.createTextRange)if(n){var c=document.body.createTextRange();c.moveToElementText(t),c.moveStart("character",e),c.collapse(!0),c.select()}else{var c=t.createTextRange();c.move("character",e),c.select()}return n||t.focus(),e}}(jQuery);
493
 
494
- /* jQuery tagEditor v1.0.20 | https://github.com/Pixabay/jQuery-tagEditor | Copyright (c) 2013 Pixabay. Licensed under the MIT license. */
495
- !function(t){t.fn.tagEditorInput=function(){var e=" ",i=t(this),a=parseInt(i.css("fontSize")),r=t("<span/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:i.css("fontSize"),fontFamily:i.css("fontFamily"),fontWeight:i.css("fontWeight"),letterSpacing:i.css("letterSpacing"),whiteSpace:"nowrap"}),l=function(){if(e!==(e=i.val())){r.text(e);var t=r.width()+a;20>t&&(t=20),t!=i.width()&&i.width(t)}};return r.insertAfter(i),i.bind("keyup keydown focus",l)},t.fn.tagEditor=function(e,a,r){function l(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var n,o=t.extend({},t.fn.tagEditor.defaults,e),c=this;if(o.dregex=new RegExp("["+o.delimiter.replace("-","-")+"]","g"),"string"==typeof e){var s=[];return c.each(function(){var i=t(this),l=i.data("options"),n=i.next(".tag-editor");if("getTags"==e)s.push({field:i[0],editor:n,tags:n.data("tags")});else if("addTag"==e){if(l.maxTags&&n.data("tags").length>=l.maxTags)return!1;t('<li><div class="tag-editor-spacer">&nbsp;'+l.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>').appendTo(n).find(".tag-editor-tag").html('<input type="text" maxlength="'+l.maxLength+'">').addClass("active").find("input").val(a).blur(),r?t(".placeholder",n).remove():n.click()}else"removeTag"==e?(t(".tag-editor-tag",n).filter(function(){return t(this).text()==a}).closest("li").find(".tag-editor-delete").click(),r||n.click()):"destroy"==e&&i.removeClass("tag-editor-hidden-src").removeData("options").off("focus.tag-editor").next(".tag-editor").remove()}),"getTags"==e?s:this}return window.getSelection&&t(document).off("keydown.tag-editor").on("keydown.tag-editor",function(e){if(8==e.which||46==e.which||e.ctrlKey&&88==e.which){try{var a=getSelection(),r="BODY"==document.activeElement.tagName?t(a.getRangeAt(0).startContainer.parentNode).closest(".tag-editor"):0}catch(e){r=0}if(a.rangeCount>0&&r&&r.length){var l=[],n=a.toString().split(r.prev().data("options").dregex);for(i=0;i<n.length;i++){var o=t.trim(n[i]);o&&l.push(o)}return t(".tag-editor-tag",r).each(function(){~t.inArray(t(this).text(),l)&&t(this).closest("li").find(".tag-editor-delete").click()}),!1}}}),c.each(function(){function e(){!o.placeholder||c.length||t(".deleted, .placeholder, input",s).length||s.append('<li class="placeholder"><div>'+o.placeholder+"</div></li>")}function i(i){var a=c.toString();c=t(".tag-editor-tag:not(.deleted)",s).map(function(e,i){var a=t.trim(t(this).hasClass("active")?t(this).find("input").val():t(i).text());return a?a:void 0}).get(),s.data("tags",c),r.val(c.join(o.delimiter[0])),i||a!=c.toString()&&o.onChange(r,s,c),e()}function a(e){for(var a,n=e.closest("li"),d=e.val().replace(/ +/," ").split(o.dregex),g=e.data("old_tag"),f=c.slice(0),h=!1,u=0;u<d.length;u++)if(v=t.trim(d[u]).slice(0,o.maxLength),o.forceLowercase&&(v=v.toLowerCase()),a=o.beforeTagSave(r,s,f,g,v),v=a||v,a!==!1&&v&&(o.removeDuplicates&&~t.inArray(v,f)&&t(".tag-editor-tag",s).each(function(){t(this).text()==v&&t(this).closest("li").remove()}),f.push(v),n.before('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+l(v)+'</div><div class="tag-editor-delete"><i></i></div></li>'),o.maxTags&&f.length>=o.maxTags)){h=!0;break}e.attr("maxlength",o.maxLength).removeData("old_tag").val(""),h?e.blur():e.focus(),i()}var r=t(this),c=[],s=t("<ul "+(o.clickDelete?'oncontextmenu="return false;" ':"")+'class="tag-editor"></ul>').insertAfter(r);r.addClass("tag-editor-hidden-src").data("options",o).on("focus.tag-editor",function(){s.click()}),s.append('<li style="width:1px">&nbsp;</li>');var d='<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>';s.click(function(e,i){var a,r,l=99999;if(!window.getSelection||""==getSelection())return o.maxTags&&s.data("tags").length>=o.maxTags?(s.find("input").blur(),!1):(n=!0,t("input:focus",s).blur(),n?(n=!0,t(".placeholder",s).remove(),i&&i.length?r="before":t(".tag-editor-tag",s).each(function(){var n=t(this),o=n.offset(),c=o.left,s=o.top;e.pageY>=s&&e.pageY<=s+n.height()&&(e.pageX<c?(r="before",a=c-e.pageX):(r="after",a=e.pageX-c-n.width()),l>a&&(l=a,i=n))}),"before"==r?t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click():"after"==r?t(d).insertAfter(i.closest("li")).find(".tag-editor-tag").click():t(d).appendTo(s).find(".tag-editor-tag").click(),!1):!1)}),s.on("click",".tag-editor-delete",function(){if(t(this).prev().hasClass("active"))return t(this).closest("li").find("input").caret(-1),!1;var a=t(this).closest("li"),l=a.find(".tag-editor-tag");return o.beforeTagDelete(r,s,c,l.text())===!1?!1:(l.addClass("deleted").animate({width:0},o.animateDelete,function(){a.remove(),e()}),i(),!1)}),o.clickDelete&&s.on("mousedown",".tag-editor-tag",function(a){if(a.ctrlKey||a.which>1){var l=t(this).closest("li"),n=l.find(".tag-editor-tag");return o.beforeTagDelete(r,s,c,n.text())===!1?!1:(n.addClass("deleted").animate({width:0},o.animateDelete,function(){l.remove(),e()}),i(),!1)}}),s.on("click",".tag-editor-tag",function(e){if(o.clickDelete&&(e.ctrlKey||e.which>1))return!1;if(!t(this).hasClass("active")){var i=t(this).text(),a=Math.abs((t(this).offset().left-e.pageX)/t(this).width()),r=parseInt(i.length*a),n=t(this).html('<input type="text" maxlength="'+o.maxLength+'" value="'+l(i)+'">').addClass("active").find("input");if(n.data("old_tag",i).tagEditorInput().focus().caret(r),o.autocomplete){var c=t.extend({},o.autocomplete),d="select"in c?o.autocomplete.select:"";c.select=function(e,i){d&&d(e,i),setTimeout(function(){s.trigger("click",[t(".active",s).find("input").closest("li").next("li").find(".tag-editor-tag")])},20)},n.autocomplete(c)}}return!1}),s.on("blur","input",function(d){d.stopPropagation();var g=t(this),f=g.data("old_tag"),h=t.trim(g.val().replace(/ +/," ").replace(o.dregex,o.delimiter[0]));if(h){if(h.indexOf(o.delimiter[0])>=0)return void a(g);if(h!=f)if(o.forceLowercase&&(h=h.toLowerCase()),cb_val=o.beforeTagSave(r,s,c,f,h),h=cb_val||h,cb_val===!1){if(f)return g.val(f).focus(),n=!1,void i();try{g.closest("li").remove()}catch(d){}f&&i()}else o.removeDuplicates&&t(".tag-editor-tag:not(.active)",s).each(function(){t(this).text()==h&&t(this).closest("li").remove()})}else{if(f&&o.beforeTagDelete(r,s,c,f)===!1)return g.val(f).focus(),n=!1,void i();try{g.closest("li").remove()}catch(d){}f&&i()}g.parent().html(l(h)).removeClass("active"),h!=f&&i(),e()});var g;s.on("paste","input",function(){t(this).removeAttr("maxlength"),g=t(this),setTimeout(function(){a(g)},30)});var f;s.on("keypress","input",function(e){o.delimiter.indexOf(String.fromCharCode(e.which))>=0&&(f=t(this),setTimeout(function(){a(f)},20))}),s.on("keydown","input",function(e){var i=t(this);if((37==e.which||!o.autocomplete&&38==e.which)&&!i.caret()||8==e.which&&!i.val()){var a=i.closest("li").prev("li").find(".tag-editor-tag");return a.length?a.click().find("input").caret(-1):!i.val()||o.maxTags&&s.data("tags").length>=o.maxTags||t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click(),!1}if((39==e.which||!o.autocomplete&&40==e.which)&&i.caret()==i.val().length){var l=i.closest("li").next("li").find(".tag-editor-tag");return l.length?l.click().find("input").caret(0):i.val()&&s.click(),!1}if(9==e.which){if(e.shiftKey){var a=i.closest("li").prev("li").find(".tag-editor-tag");if(a.length)a.click().find("input").caret(0);else{if(!i.val()||o.maxTags&&s.data("tags").length>=o.maxTags)return r.attr("disabled","disabled"),void setTimeout(function(){r.removeAttr("disabled")},30);t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click()}return!1}var l=i.closest("li").next("li").find(".tag-editor-tag");if(l.length)l.click().find("input").caret(0);else{if(!i.val())return;s.click()}return!1}if(!(46!=e.which||t.trim(i.val())&&i.caret()!=i.val().length)){var l=i.closest("li").next("li").find(".tag-editor-tag");return l.length?l.click().find("input").caret(0):i.val()&&s.click(),!1}if(13==e.which)return s.trigger("click",[i.closest("li").next("li").find(".tag-editor-tag")]),o.maxTags&&s.data("tags").length>=o.maxTags&&s.find("input").blur(),!1;if(36!=e.which||i.caret()){if(35==e.which&&i.caret()==i.val().length)s.find(".tag-editor-tag").last().click();else if(27==e.which)return i.val(i.data("old_tag")?i.data("old_tag"):"").blur(),!1}else s.find(".tag-editor-tag").first().click()});for(var h=o.initialTags.length?o.initialTags:r.val().split(o.dregex),u=0;u<h.length&&!(o.maxTags&&u>=o.maxTags);u++){var v=t.trim(h[u].replace(/ +/," "));v&&(o.forceLowercase&&(v=v.toLowerCase()),c.push(v),s.append('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+l(v)+'</div><div class="tag-editor-delete"><i></i></div></li>'))}i(!0),o.sortable&&t.fn.sortable&&s.sortable({distance:5,cancel:".tag-editor-spacer, input",helper:"clone",update:function(){i()}})})},t.fn.tagEditor.defaults={initialTags:[],maxTags:0,maxLength:50,delimiter:",;",placeholder:"",forceLowercase:!0,removeDuplicates:!0,clickDelete:!1,animateDelete:175,sortable:!0,autocomplete:null,onChange:function(){},beforeTagSave:function(){},beforeTagDelete:function(){}}}(jQuery);
50
  }
51
  },
52
 
53
+ refresh_countdown: function() {
54
+ SlimStatAdmin._refresh_timer[ 1 ]--;
55
+ if (SlimStatAdmin._refresh_timer[ 1 ] == -1){
56
+ SlimStatAdmin._refresh_timer[ 1 ] = 59;
57
+ SlimStatAdmin._refresh_timer[ 0 ] = SlimStatAdmin._refresh_timer[ 0 ] - 1;
58
  }
59
+ jQuery( '.refresh-timer' ).html( SlimStatAdmin._refresh_timer[ 0 ] + ':' + ( ( SlimStatAdmin._refresh_timer[ 1 ] < 10 ) ? '0' : '' ) + SlimStatAdmin._refresh_timer[ 1 ] );
60
+ if ( SlimStatAdmin._refresh_timer[ 0 ] > 0 || SlimStatAdmin._refresh_timer[ 1 ] > 0 ) {
61
+ refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
62
  }
63
+ else {
64
  report_id = 'slim_p7_02';
65
  data = {action: 'slimstat_load_report', report_id: report_id, security: jQuery('#meta-box-order-nonce').val(), page: SlimStatAdmin.get_query_string_value( 'page' ) };
66
  jQuery('#'+report_id+' .inside').html('<p class="loading"><i class="slimstat-font-spin4 animate-spin"></i></p>');
67
  SlimStatAdmin.refresh_report(report_id, data);
68
 
69
  window.clearTimeout(refresh_handle);
70
+ SlimStatAdmin._refresh_timer[ 0 ] = parseInt( SlimStatAdminParams.refresh_interval / 60 );
71
+ SlimStatAdmin._refresh_timer[ 1 ] = SlimStatAdminParams.refresh_interval % 60;
72
+ refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
73
  }
74
  },
75
 
76
+ refresh_report: function( report_id, data ) {
77
  // Get the data from the hidden form
78
+ filters_input = jQuery( '#slimstat-filters-form .slimstat-post-filter' ).toArray();
79
+ for ( i in filters_input ) {
80
+ data[ filters_input[ i ][ 'name' ] ] = filters_input[ i ][ 'value' ];
81
  }
82
 
83
  jQuery('#'+report_id+' .inside').html('<p class="loading"><i class="slimstat-font-spin4 animate-spin"></i></p>');
84
 
85
  jQuery.post(ajaxurl, data, function(response){
86
  if (report_id.indexOf('_01') > 0){
87
+ jQuery('#'+report_id + ' .inside').html( response );
 
88
  }
89
  else{
90
+ jQuery( '#' + report_id + ' .inside' ).fadeOut( 700, function() {
91
+ jQuery( this ).html( response ).fadeIn( 700, function() {
92
+ if ( jQuery( '.refresh-timer' ).length > 0 ) {
93
+ if ( typeof refresh_handle !== 'undefined' ) {
94
+ window.clearTimeout( refresh_handle );
95
+ }
96
+ SlimStatAdmin._refresh_timer[ 0 ] = parseInt( SlimStatAdminParams.refresh_interval / 60 );
97
+ SlimStatAdmin._refresh_timer[ 1 ] = SlimStatAdminParams.refresh_interval % 60;
98
+ refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
99
+ }
100
+ });
101
  });
102
  }
103
  });
104
 
105
  // Remove filters set by other Ajax buttons
106
  jQuery('.slimstat-temp-filter').remove();
107
+
108
+ // if ( jQuery( '.refresh-timer' ).length > 0 ) {
109
+ // SlimStatAdmin.refresh_countdown();
110
+ // }
111
  },
112
 
113
  get_query_string_value: function( key ) {
130
 
131
  jQuery(function(){
132
  // Refresh page every X seconds
133
+ if ( SlimStatAdminParams.refresh_interval > 0 && jQuery( '.refresh-timer' ).length > 0 ) {
134
  SlimStatAdmin._refresh_timer[ 0 ] = parseInt( SlimStatAdminParams.refresh_interval / 60 );
135
  SlimStatAdmin._refresh_timer[ 1 ] = SlimStatAdminParams.refresh_interval % 60;
136
  refresh_handle = window.setTimeout( "SlimStatAdmin.refresh_countdown();", 1000 );
250
 
251
  jQuery('#'+report_id+' .inside').slimScroll({scrollTo : '0px'});
252
 
253
+ if ( typeof refresh_handle !== 'undefined' ) {
254
+ window.clearTimeout( refresh_handle );
 
 
 
255
  }
256
  });
257
 
494
  /* qTip2 v3.0.3 | http://qtip2.com | Released under the MIT and GPL licenses. */
495
  !function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=D,this.elements={target:a},this._id=Q+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:C,attr:e,onTooltip:C,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=C}function f(a){return a===D||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?C:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?(c=g(b)?C:b,b=a.content={text:c}):c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==C,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,D,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(d.isPlainObject(b.title)&&(b.button=b.title.button,b.title=b.title.text),g(b.title||C)&&(b.title=C))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===B?{ready:B}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(P,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)if(this.checks.hasOwnProperty(c))for(d in this.checks[c])this.checks[c].hasOwnProperty(d)&&(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return T.concat("").join(a?"-"+a+" ":" ")}function l(a,b){return b>0?setTimeout(d.proxy(a,this),b):void a.call(this)}function m(a){this.tooltip.hasClass($)||(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=l.call(this,function(){this.toggle(B,a)},this.options.show.delay))}function n(a){if(!this.tooltip.hasClass($)&&!this.destroyed){var b=d(a.relatedTarget),c=b.closest(U)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=l.call(this,function(){this.toggle(C,a)},this.options.hide.delay,this)}}function o(a){!this.tooltip.hasClass($)&&this.options.hide.inactive&&(clearTimeout(this.timers.inactive),this.timers.inactive=l.call(this,function(){this.hide(a)},this.options.hide.inactive))}function p(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function q(a,c,e){d(b.body).delegate(a,(c.split?c:c.join("."+Q+" "))+"."+Q,function(){var a=w.api[d.attr(this,S)];a&&!a.disabled&&e.apply(a,arguments)})}function r(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):D,p="html5"===f.metadata.type&&o?o[f.metadata.name]:D,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(B,{},w.defaults,f,"object"==typeof q?h(q):D,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===C||!j)return C;k.content.text=j}if(i.container.length||(i.container=m),i.target===C&&(i.target=n),k.show.target===C&&(k.show.target=n),k.show.solo===B&&(k.show.solo=i.container.closest("body")),k.hide.target===C&&(k.hide.target=n),k.position.viewport===B&&(k.position.viewport=i.container),i.container=i.container.eq(0),i.at=new y(i.at,B),i.my=new y(i.my),a.data(Q))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===C)return C;return a.attr(R,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(aa,l).attr("title",""),g=new e(a,k,c,!!j),a.data(Q,g),g}function s(a){return a.charAt(0).toUpperCase()+a.slice(1)}function t(a,b){var d,e,f=b.charAt(0).toUpperCase()+b.slice(1),g=(b+" "+ta.join(f+" ")+f).split(" "),h=0;if(sa[b])return a.css(sa[b]);for(;d=g[h++];)if((e=a.css(d))!==c)return sa[b]=d,e}function u(a,b){return Math.ceil(parseFloat(t(a,b)))}function v(a,b){this._ns="tip",this.options=b,this.offset=b.offset,this.size=[b.width,b.height],this.qtip=a,this.init(a)}var w,x,y,z,A,B=!0,C=!1,D=null,E="x",F="y",G="width",H="height",I="top",J="left",K="bottom",L="right",M="center",N="flipinvert",O="shift",P={},Q="qtip",R="data-hasqtip",S="data-qtip-id",T=["ui-widget","ui-tooltip"],U="."+Q,V="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),W=Q+"-fixed",X=Q+"-default",Y=Q+"-focus",Z=Q+"-hover",$=Q+"-disabled",_="_replacedByqTip",aa="oldtitle",ba={ie:function(){var a,c;for(a=4,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];a+=1);return a>4?a:NaN}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||C};x=e.prototype,x._when=function(a){return d.when.apply(d,a)},x.render=function(a){if(this.rendered||this.destroyed)return this;var b=this,c=this.options,e=this.cache,f=this.elements,g=c.content.text,h=c.content.title,i=c.content.button,j=c.position,k=[];return d.attr(this.target[0],"aria-describedby",this._id),e.posClass=this._createPosClass((this.position={my:j.my,at:j.at}).my),this.tooltip=f.tooltip=d("<div/>",{id:this._id,"class":[Q,X,c.style.classes,e.posClass].join(" "),width:c.style.width||"",height:c.style.height||"",tracking:"mouse"===j.target&&j.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":C,"aria-describedby":this._id+"-content","aria-hidden":B}).toggleClass($,this.disabled).attr(S,this.id).data(Q,this).appendTo(j.container).append(f.content=d("<div />",{"class":Q+"-content",id:this._id+"-content","aria-atomic":B})),this.rendered=-1,this.positioning=B,h&&(this._createTitle(),d.isFunction(h)||k.push(this._updateTitle(h,C))),i&&this._createButton(),d.isFunction(g)||k.push(this._updateContent(g,C)),this.rendered=B,this._setWidget(),d.each(P,function(a){var c;"render"===this.initialize&&(c=this(b))&&(b.plugins[a]=c)}),this._unassignEvents(),this._assignEvents(),this._when(k).then(function(){b._trigger("render"),b.positioning=C,b.hiddenDuringWait||!c.show.ready&&!a||b.toggle(B,e.event,C),b.hiddenDuringWait=C}),w.api[this.id]=this,this},x.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=B;var a,b=this.target,c=b.attr(aa);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()});for(a in this.timers)this.timers.hasOwnProperty(a)&&clearTimeout(this.timers[a]);b.removeData(Q).removeAttr(S).removeAttr(R).removeAttr("aria-describedby"),this.options.suppress&&c&&b.attr("title",c).removeAttr(aa),this._unassignEvents(),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=D,delete w.api[this.id]}}return this.destroyed?this.target:(a===B&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},z=x.checks={builtin:{"^id$":function(a,b,c,e){var f=c===B?w.nextid:c,g=Q+"-"+f;f!==C&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),void this._updateTitle(c)):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)},"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(this.position[b]=a[b]=new y(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(B)||this.toggle(B))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(X,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},x.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var ca=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,da=/^prerender|show\.ready/i;x.set=function(a,b){if(this.destroyed)return this;var c,e=this.rendered,f=C,g=this.options;return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&da.test(b))return void delete a[b];var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=ca.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=B,d.each(a,d.proxy(j,this)),this.positioning=C,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?D:this.cache.event),this},x._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=B,a.then(function(a){return e.waiting=C,c._update(a,b)},D,function(a){return c._update(a,b)})):a===C||!a&&""!==a?C:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):C},x._waitForContent=function(a){var b=this.cache;return b.waiting=B,(d.fn.imagesLoaded?a.imagesLoaded():(new d.Deferred).resolve([])).done(function(){b.waiting=C}).promise()},x._updateContent=function(a,b){this._update(a,this.elements.content,b)},x._updateTitle=function(a,b){this._update(a,this.elements.title,b)===C&&this._removeTitle(C)},x._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":Q+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":Q+"-title","aria-atomic":B})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},x._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=D,a!==C&&this.reposition())},x._createPosClass=function(a){return Q+"-pos-"+(a||this.options.position.my).abbrev()},x.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=B;var f,g,h,i,j=this.cache,k=this.tooltip,l=this.options.position,m=l.target,n=l.my,o=l.at,p=l.viewport,q=l.container,r=l.adjust,s=r.method.split(" "),t=k.outerWidth(C),u=k.outerHeight(C),v=0,w=0,x=k.css("position"),y={left:0,top:0},z=k[0].offsetWidth>0,A=c&&"scroll"===c.type,D=d(a),E=q[0].ownerDocument,F=this.mouse;if(d.isArray(m)&&2===m.length)o={x:J,y:I},y={left:m[0],top:m[1]};else if("mouse"===m)o={x:J,y:I},(!r.mouse||this.options.hide.distance)&&j.origin&&j.origin.pageX?c=j.origin:!c||c&&("resize"===c.type||"scroll"===c.type)?c=j.event:F&&F.pageX&&(c=F),"static"!==x&&(y=q.offset()),E.body.offsetWidth!==(a.innerWidth||E.documentElement.clientWidth)&&(g=d(b.body).offset()),y={left:c.pageX-y.left+(g&&g.left||0),top:c.pageY-y.top+(g&&g.top||0)},r.mouse&&A&&F&&(y.left-=(F.scrollX||0)-D.scrollLeft(),y.top-=(F.scrollY||0)-D.scrollTop());else{if("event"===m?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?j.target=d(c.target):c.target||(j.target=this.elements.target):"event"!==m&&(j.target=d(m.jquery?m:this.elements.target)),m=j.target,m=d(m).eq(0),0===m.length)return this;m[0]===b||m[0]===a?(v=ba.iOS?a.innerWidth:m.width(),w=ba.iOS?a.innerHeight:m.height(),m[0]===a&&(y={top:(p||m).scrollTop(),left:(p||m).scrollLeft()})):P.imagemap&&m.is("area")?f=P.imagemap(this,m,o,P.viewport?s:C):P.svg&&m&&m[0].ownerSVGElement?f=P.svg(this,m,o,P.viewport?s:C):(v=m.outerWidth(C),w=m.outerHeight(C),y=m.offset()),f&&(v=f.width,w=f.height,g=f.offset,y=f.position),y=this.reposition.offset(m,y,q),(ba.iOS>3.1&&ba.iOS<4.1||ba.iOS>=4.3&&ba.iOS<4.33||!ba.iOS&&"fixed"===x)&&(y.left-=D.scrollLeft(),y.top-=D.scrollTop()),(!f||f&&f.adjustable!==C)&&(y.left+=o.x===L?v:o.x===M?v/2:0,y.top+=o.y===K?w:o.y===M?w/2:0)}return y.left+=r.x+(n.x===L?-t:n.x===M?-t/2:0),y.top+=r.y+(n.y===K?-u:n.y===M?-u/2:0),P.viewport?(h=y.adjusted=P.viewport(this,y,l,v,w,t,u),g&&h.left&&(y.left+=g.left),g&&h.top&&(y.top+=g.top),h.my&&(this.position.my=h.my)):y.adjusted={left:0,top:0},j.posClass!==(i=this._createPosClass(this.position.my))&&(j.posClass=i,k.removeClass(j.posClass).addClass(i)),this._trigger("move",[y,p.elem||p],c)?(delete y.adjusted,e===C||!z||isNaN(y.left)||isNaN(y.top)||"mouse"===m||!d.isFunction(l.effect)?k.css(y):d.isFunction(l.effect)&&(l.effect.call(k,this,d.extend({},y)),k.queue(function(a){d(this).css({opacity:"",height:""}),ba.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=C,this):this},x.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!ba.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var ea=(y=x.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,M).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?F:E}).prototype;ea.invert=function(a,b){this[a]=this[a]===J?L:this[a]===L?J:b||this[a]},ea.string=function(a){var b=this.x,c=this.y,d=b!==c?"center"===b||"center"!==c&&(this.precedance===F||this.forceY)?[c,b]:[b,c]:[b];return a!==!1?d.join(" "):d},ea.abbrev=function(){var a=this.string(!1);return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},ea.clone=function(){return new y(this.string(),this.forceY)},x.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&e.event&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=d.event.fix(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=B),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",l=this.options[k],m=this.options.position,n=this.options.content,o=this.tooltip.css("width"),p=this.tooltip.is(":visible"),q=a||1===l.target.length,r=!c||l.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!p),h=!g.is(":animated")&&p===a&&r,i=h?D:!!this._trigger(k,[90]),this.destroyed?this:(i!==C&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(this.mouse&&(e.origin=d.event.fix(this.mouse)),d.isFunction(n.text)&&this._updateContent(n.text,C),d.isFunction(n.title)&&this._updateTitle(n.title,C),!A&&"mouse"===m.target&&m.adjust.mouse&&(d(b).bind("mousemove."+Q,this._storeMouse),A=B),o||g.css("width",g.outerWidth(C)),this.reposition(c,arguments[2]),o||g.css("width",""),l.solo&&("string"==typeof l.solo?d(l.solo):d(U,l.solo)).not(g).not(l.target).qtip("hide",new d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,A&&!d(U+'[tracking="true"]:visible',l.solo).not(g).length&&(d(b).unbind("mousemove."+Q),A=C),this.blur(c)),j=d.proxy(function(){a?(ba.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof l.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),l.effect===C||q===C?(g[k](),j()):d.isFunction(l.effect)?(g.stop(1,1),l.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&l.target.trigger("qtip-"+this.id+"-inactive"),this))},x.show=function(a){return this.toggle(B,a)},x.hide=function(a){return this.toggle(C,a)},x.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(U),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=w.zindex+b.length;return c.hasClass(Y)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+Y).qtip("blur",a)),c.addClass(Y)[0].style.zIndex=f),this},x.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(Y),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},x.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass($):this.disabled):"boolean"!=typeof a&&(a=B),this.rendered&&this.tooltip.toggleClass($,a).attr("aria-disabled",a),this.disabled=!!a,this)},x.enable=function(){return this.disable(C)},x._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),e.jquery?b.button=e:b.button=d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":Q+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass($)||a.hide(b),C})},x._updateButton=function(a){if(!this.rendered)return C;var b=this.elements.button;a?this._createButton():b.remove()},x._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass($);c.removeClass($),$=a?"ui-state-disabled":"qtip-disabled",c.toggleClass($,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(X,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(Q+"-icon",!a)},x._storeMouse=function(a){return(this.mouse=d.event.fix(a)).type="mousemove",this},x._bind=function(a,b,c,e,f){if(a&&c&&b.length){var g="."+this._id+(e?"-"+e:"");return d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this)),this}},x._unbind=function(a,b){return a&&d(a).unbind("."+this._id+(b?"-"+b:"")),this},x._trigger=function(a,b,c){var e=new d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||D,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=C,!e.isDefaultPrevented()},x._bindEvents=function(a,b,c,e,f,g){var h=c.filter(e).add(e.filter(c)),i=[];h.length&&(d.each(b,function(b,c){var e=d.inArray(c,a);e>-1&&i.push(a.splice(e,1)[0])}),i.length&&(this._bind(h,i,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)}),c=c.not(h),e=e.not(h))),this._bind(c,a,f),this._bind(e,b,g)},x._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?C:(this.cache.event=a&&d.event.fix(a),this.cache.target=a&&d(a.target),clearTimeout(this.timers.show),void(this.timers.show=l.call(this,function(){this.render("object"==typeof a||c.show.ready)},c.prerender?0:c.show.delay)))}var c=this.options,e=c.show.target,f=c.hide.target,g=c.show.event?d.trim(""+c.show.event).split(" "):[],h=c.hide.event?d.trim(""+c.hide.event).split(" "):[];this._bind(this.elements.target,["remove","removeqtip"],function(){this.destroy(!0)},"destroy"),/mouse(over|enter)/i.test(c.show.event)&&!/mouse(out|leave)/i.test(c.hide.event)&&h.push("mouseleave"),this._bind(e,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=B}),this._bindEvents(g,h,e,f,b,function(){return this.timers?void clearTimeout(this.timers.show):C}),(c.show.ready||c.prerender)&&b.call(this,a)},x._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),q=d(a),r=e.show.event?d.trim(""+e.show.event).split(" "):[],s=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(W)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass($)&&this.tooltip[0].offsetWidth>0,e=b.parents(U).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",o,"inactive"),this._bind(i.add(g),w.inactiveEvents,o)),this._bindEvents(r,s,h,i,m,n),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){return this.cache?void(this.cache.onTarget="mouseenter"===a.type):C}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass($)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:q,"resize",p),f.adjust.scroll&&this._bind(q.add(f.container),"scroll",p)},x._unassignEvents=function(){var c=this.options,e=c.show.target,f=c.hide.target,g=d.grep([this.elements.target[0],this.rendered&&this.tooltip[0],c.position.container[0],c.position.viewport[0],c.position.container.closest("html")[0],a,b],function(a){return"object"==typeof a});e&&e.toArray&&(g=g.concat(e.toArray())),f&&f.toArray&&(g=g.concat(f.toArray())),this._unbind(g)._unbind(g,"destroy")._unbind(g,"inactive")},d(function(){q(U,["mouseenter","mouseleave"],function(a){var b="mouseenter"===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(W)&&!c.hasClass($)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.position.adjust.mouse&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass(Z,b)}),q("["+S+"]",V,o)}),w=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=D,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],Q):D;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,Q);if(!a)return B;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),C;a.set(b,e)}}),g!==D?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(B,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===C||c.length<1||w.api[c]?w.nextid++:c,b=r(d(this),c,k),b===C?B:(w.api[c]=b,d.each(P,function(){"initialize"===this.initialize&&this(b)}),void b._assignInitialEvents(j))}))},d.qtip=e,w.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&f.options&&"object"==typeof f&&"object"==typeof f.options&&f.options.suppress)return arguments.length<2?d.attr(c,aa):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(aa,b))}return d.fn["attr"+_].apply(this,arguments)},clone:function(a){var b=d.fn["clone"+_].apply(this,arguments);return a||b.filter("["+aa+"]").attr("title",function(){return d.attr(this,aa)}).removeAttr(aa),b}},function(a,b){if(!b||d.fn[a+_])return B;var c=d.fn[a+_]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+_]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(R))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+_].apply(this,arguments)}),w.version="3.0.3",w.nextid=0,w.inactiveEvents=V,w.zindex=15e3,w.defaults={prerender:C,id:C,overwrite:B,suppress:B,content:{text:B,attr:"title",title:C,button:C},position:{my:"top left",at:"bottom right",target:C,container:C,viewport:C,adjust:{x:0,y:0,mouse:B,scroll:B,resize:B,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:C})}},show:{target:C,event:"mouseenter",effect:B,delay:90,solo:C,ready:C,autofocus:C},hide:{target:C,event:"mouseleave",effect:B,delay:0,fixed:C,inactive:C,leave:"window",distance:C},style:{classes:"",widget:C,width:C,height:C,def:B},events:{render:D,move:D,show:D,hide:D,toggle:D,visible:D,hidden:D,focus:D,blur:D}};var fa,ga,ha,ia,ja,ka="margin",la="border",ma="color",na="background-color",oa="transparent",pa=" !important",qa=!!b.createElement("canvas").getContext,ra=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,sa={},ta=["Webkit","O","Moz","ms"];qa?(ia=a.devicePixelRatio||1,ja=function(){var a=b.createElement("canvas").getContext("2d");return a.backingStorePixelRatio||a.webkitBackingStorePixelRatio||a.mozBackingStorePixelRatio||a.msBackingStorePixelRatio||a.oBackingStorePixelRatio||1}(),ha=ia/ja):ga=function(a,b,c){return"<qtipvml:"+a+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(b||"")+' style="behavior: url(#default#VML); '+(c||"")+'" />'},d.extend(v.prototype,{init:function(a){var b,c;c=this.element=a.elements.tip=d("<div />",{"class":Q+"-tip"}).prependTo(a.tooltip),qa?(b=d("<canvas />").appendTo(this.element)[0].getContext("2d"),b.lineJoin="miter",b.miterLimit=1e5,b.save()):(b=ga("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(b+b),a._bind(d("*",c).add(c),["click","mousedown"],function(a){a.stopPropagation()},this._ns)),a._bind(a.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(a){var b=this.qtip.elements.titlebar;return b&&(a.y===I||a.y===M&&this.element.position().top+this.size[1]/2+this.options.offset<b.outerHeight(B))},_parseCorner:function(a){var b=this.qtip.options.position.my;return a===C||b===C?a=C:a===B?a=new y(b.string()):a.string||(a=new y(a),a.fixed=B),a},_parseWidth:function(a,b,c){var d=this.qtip.elements,e=la+s(b)+"Width";return(c?u(c,e):u(d.content,e)||u(this._useTitle(a)&&d.titlebar||d.content,e)||u(d.tooltip,e))||0},_parseRadius:function(a){var b=this.qtip.elements,c=la+s(a.y)+s(a.x)+"Radius";return ba.ie<9?0:u(this._useTitle(a)&&b.titlebar||b.content,c)||u(b.tooltip,c)||0},_invalidColour:function(a,b,c){var d=a.css(b);return!d||c&&d===a.css(c)||ra.test(d)?C:d},_parseColours:function(a){var b=this.qtip.elements,c=this.element.css("cssText",""),e=la+s(a[a.precedance])+s(ma),f=this._useTitle(a)&&b.titlebar||b.content,g=this._invalidColour,h=[];return h[0]=g(c,na)||g(f,na)||g(b.content,na)||g(b.tooltip,na)||c.css(na),h[1]=g(c,e,ma)||g(f,e,ma)||g(b.content,e,ma)||g(b.tooltip,e,ma)||b.tooltip.css(e),d("*",c).add(c).css("cssText",na+":"+oa+pa+";"+la+":0"+pa+";"),h},_calculateSize:function(a){var b,c,d,e=a.precedance===F,f=this.options.width,g=this.options.height,h="c"===a.abbrev(),i=(e?f:g)*(h?.5:1),j=Math.pow,k=Math.round,l=Math.sqrt(j(i,2)+j(g,2)),m=[this.border/i*l,this.border/g*l];return m[2]=Math.sqrt(j(m[0],2)-j(this.border,2)),m[3]=Math.sqrt(j(m[1],2)-j(this.border,2)),b=l+m[2]+m[3]+(h?0:m[0]),c=b/l,d=[k(c*f),k(c*g)],e?d:d.reverse()},_calculateTip:function(a,b,c){c=c||1,b=b||this.size;var d=b[0]*c,e=b[1]*c,f=Math.ceil(d/2),g=Math.ceil(e/2),h={br:[0,0,d,e,d,0],bl:[0,0,d,0,0,e],tr:[0,e,d,0,d,e],tl:[0,0,0,e,d,e],tc:[0,e,f,0,d,e],bc:[0,0,d,0,f,e],rc:[0,0,d,g,0,e],lc:[d,0,d,e,0,g]};return h.lt=h.br,h.rt=h.bl,h.lb=h.tr,h.rb=h.tl,h[a.abbrev()]},_drawCoords:function(a,b){a.beginPath(),a.moveTo(b[0],b[1]),a.lineTo(b[2],b[3]),a.lineTo(b[4],b[5]),a.closePath()},create:function(){var a=this.corner=(qa||ba.ie)&&this._parseCorner(this.options.corner);return this.enabled=!!this.corner&&"c"!==this.corner.abbrev(),this.enabled&&(this.qtip.cache.corner=a.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(b,c){if(!this.enabled)return this;var e,f,g,h,i,j,k,l,m=this.qtip.elements,n=this.element,o=n.children(),p=this.options,q=this.size,r=p.mimic,s=Math.round;b||(b=this.qtip.cache.corner||this.corner),r===C?r=b:(r=new y(r),r.precedance=b.precedance,"inherit"===r.x?r.x=b.x:"inherit"===r.y?r.y=b.y:r.x===r.y&&(r[b.precedance]=b[b.precedance])),f=r.precedance,b.precedance===E?this._swapDimensions():this._resetDimensions(),e=this.color=this._parseColours(b),e[1]!==oa?(l=this.border=this._parseWidth(b,b[b.precedance]),p.border&&1>l&&!ra.test(e[1])&&(e[0]=e[1]),this.border=l=p.border!==B?p.border:l):this.border=l=0,k=this.size=this._calculateSize(b),n.css({width:k[0],height:k[1],lineHeight:k[1]+"px"}),j=b.precedance===F?[s(r.x===J?l:r.x===L?k[0]-q[0]-l:(k[0]-q[0])/2),s(r.y===I?k[1]-q[1]:0)]:[s(r.x===J?k[0]-q[0]:0),s(r.y===I?l:r.y===K?k[1]-q[1]-l:(k[1]-q[1])/2)],qa?(g=o[0].getContext("2d"),g.restore(),g.save(),g.clearRect(0,0,6e3,6e3),h=this._calculateTip(r,q,ha),i=this._calculateTip(r,this.size,ha),o.attr(G,k[0]*ha).attr(H,k[1]*ha),o.css(G,k[0]).css(H,k[1]),this._drawCoords(g,i),g.fillStyle=e[1],g.fill(),g.translate(j[0]*ha,j[1]*ha),this._drawCoords(g,h),g.fillStyle=e[0],g.fill()):(h=this._calculateTip(r),h="m"+h[0]+","+h[1]+" l"+h[2]+","+h[3]+" "+h[4]+","+h[5]+" xe",j[2]=l&&/^(r|b)/i.test(b.string())?8===ba.ie?2:1:0,o.css({coordsize:k[0]+l+" "+k[1]+l,antialias:""+(r.string().indexOf(M)>-1),left:j[0]-j[2]*Number(f===E),top:j[1]-j[2]*Number(f===F),width:k[0]+l,height:k[1]+l}).each(function(a){var b=d(this);b[b.prop?"prop":"attr"]({coordsize:k[0]+l+" "+k[1]+l,path:h,fillcolor:e[0],filled:!!a,stroked:!a}).toggle(!(!l&&!a)),!a&&b.html(ga("stroke",'weight="'+2*l+'px" color="'+e[1]+'" miterlimit="1000" joinstyle="miter"'))})),a.opera&&setTimeout(function(){m.tip.css({display:"inline-block",visibility:"visible"})},1),c!==C&&this.calculate(b,k)},calculate:function(a,b){if(!this.enabled)return C;var c,e,f=this,g=this.qtip.elements,h=this.element,i=this.options.offset,j={};return a=a||this.corner,c=a.precedance,b=b||this._calculateSize(a),e=[a.x,a.y],c===E&&e.reverse(),d.each(e,function(d,e){var h,k,l;e===M?(h=c===F?J:I,j[h]="50%",j[ka+"-"+h]=-Math.round(b[c===F?0:1]/2)+i):(h=f._parseWidth(a,e,g.tooltip),k=f._parseWidth(a,e,g.content),l=f._parseRadius(a),j[e]=Math.max(-f.border,d?k:i+(l>h?l:-h)))}),j[a[c]]-=b[c===E?0:1],h.css({margin:"",top:"",bottom:"",left:"",right:""}).css(j),j},reposition:function(a,b,d){function e(a,b,c,d,e){a===O&&j.precedance===b&&k[d]&&j[c]!==M?j.precedance=j.precedance===E?F:E:a!==O&&k[d]&&(j[b]=j[b]===M?k[d]>0?d:e:j[b]===d?e:d)}function f(a,b,e){j[a]===M?p[ka+"-"+b]=o[a]=g[ka+"-"+b]-k[b]:(h=g[e]!==c?[k[b],-g[b]]:[-k[b],g[b]],(o[a]=Math.max(h[0],h[1]))>h[0]&&(d[b]-=k[b],o[b]=C),p[g[e]!==c?e:b]=o[a])}if(this.enabled){var g,h,i=b.cache,j=this.corner.clone(),k=d.adjusted,l=b.options.position.adjust.method.split(" "),m=l[0],n=l[1]||l[0],o={left:C,top:C,x:0,y:0},p={};this.corner.fixed!==B&&(e(m,E,F,J,L),e(n,F,E,I,K),j.string()===i.corner.string()&&i.cornerTop===k.top&&i.cornerLeft===k.left||this.update(j,C)),g=this.calculate(j),g.right!==c&&(g.left=-g.right),g.bottom!==c&&(g.top=-g.bottom),g.user=this.offset,o.left=m===O&&!!k.left,o.left&&f(E,J,L),o.top=n===O&&!!k.top,o.top&&f(F,I,K),this.element.css(p).toggle(!(o.x&&o.y||j.x===M&&o.y||j.y===M&&o.x)),d.left-=g.left.charAt?g.user:m!==O||o.top||!o.left&&!o.top?g.left+this.border:0,d.top-=g.top.charAt?g.user:n!==O||o.left||!o.left&&!o.top?g.top+this.border:0,i.cornerLeft=k.left,i.cornerTop=k.top,i.corner=j.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),fa=P.tip=function(a){return new v(a,a.options.style.tip)},fa.initialize="render",fa.sanitize=function(a){if(a.style&&"tip"in a.style){var b=a.style.tip;"object"!=typeof b&&(b=a.style.tip={corner:b}),/string|boolean/i.test(typeof b.corner)||(b.corner=B)}},z.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(a){this.size=[a.width,a.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},d.extend(B,w.defaults,{style:{tip:{corner:B,mimic:C,width:6,height:6,border:B,offset:0}}}),P.viewport=function(c,d,e,f,g,h,i){function j(a,b,c,e,f,g,h,i,j){var k=d[f],s=u[a],t=v[a],w=c===O,x=s===f?j:s===g?-j:-j/2,y=t===f?i:t===g?-i:-i/2,z=q[f]+r[f]-(n?0:m[f]),A=z-k,B=k+j-(h===G?o:p)-z,C=x-(u.precedance===a||s===u[b]?y:0)-(t===M?i/2:0);return w?(C=(s===f?1:-1)*x,d[f]+=A>0?A:B>0?-B:0,d[f]=Math.max(-m[f]+r[f],k-C,Math.min(Math.max(-m[f]+r[f]+(h===G?o:p),k+C),d[f],"center"===s?k-x:1e9))):(e*=c===N?2:0,A>0&&(s!==f||B>0)?(d[f]-=C+e,l.invert(a,f)):B>0&&(s!==g||A>0)&&(d[f]-=(s===M?-C:C)+e,l.invert(a,g)),d[f]<q[f]&&-d[f]>B&&(d[f]=k,l=u.clone())),d[f]-k}var k,l,m,n,o,p,q,r,s=e.target,t=c.elements.tooltip,u=e.my,v=e.at,w=e.adjust,x=w.method.split(" "),y=x[0],z=x[1]||x[0],A=e.viewport,B=e.container,D={left:0,top:0};return A.jquery&&s[0]!==a&&s[0]!==b.body&&"none"!==w.method?(m=B.offset()||D,n="static"===B.css("position"),k="fixed"===t.css("position"),o=A[0]===a?A.width():A.outerWidth(C),p=A[0]===a?A.height():A.outerHeight(C),q={left:k?0:A.scrollLeft(),top:k?0:A.scrollTop()},r=A.offset()||D,"shift"===y&&"shift"===z||(l=u.clone()),D={left:"none"!==y?j(E,F,y,w.x,J,L,G,f,h):0,top:"none"!==z?j(F,E,z,w.y,I,K,H,g,i):0,my:l}):D}})}(window,document);
496
 
497
+ /* bootstrap-switch v3.3.4 | http://bootstrapswitch.com/ | Copyright (c) 2012-2017 Mattia Larentis & Emanuele Marchi. Released under the Apache 2.0 license. */
498
+ (function(a,b){if('function'==typeof define&&define.amd)define(['jquery'],b);else if('undefined'!=typeof exports)b(require('jquery'));else{b(a.jquery),a.bootstrapSwitch={exports:{}}.exports}})(this,function(a){'use strict';function c(j,k){if(!(j instanceof k))throw new TypeError('Cannot call a class as a function')}var d=function(j){return j&&j.__esModule?j:{default:j}}(a),e=Object.assign||function(j){for(var l,k=1;k<arguments.length;k++)for(var m in l=arguments[k],l)Object.prototype.hasOwnProperty.call(l,m)&&(j[m]=l[m]);return j},f=function(){function j(k,l){for(var n,m=0;m<l.length;m++)n=l[m],n.enumerable=n.enumerable||!1,n.configurable=!0,'value'in n&&(n.writable=!0),Object.defineProperty(k,n.key,n)}return function(k,l,m){return l&&j(k.prototype,l),m&&j(k,m),k}}(),g=d.default||window.jQuery||window.$,h=function(){function j(k){var l=this,m=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};c(this,j),this.$element=g(k),this.options=g.extend({},g.fn.bootstrapSwitch.defaults,this._getElementOptions(),m),this.prevOptions={},this.$wrapper=g('<div>',{class:function(){var o=[];return o.push(l.options.state?'on':'off'),l.options.size&&o.push(l.options.size),l.options.disabled&&o.push('disabled'),l.options.readonly&&o.push('readonly'),l.options.indeterminate&&o.push('indeterminate'),l.options.inverse&&o.push('inverse'),l.$element.attr('id')&&o.push('id-'+l.$element.attr('id')),o.map(l._getClass.bind(l)).concat([l.options.baseClass],l._getClasses(l.options.wrapperClass)).join(' ')}}),this.$container=g('<div>',{class:this._getClass('container')}),this.$on=g('<span>',{html:this.options.onText,class:this._getClass('handle-on')+' '+this._getClass(this.options.onColor)}),this.$off=g('<span>',{html:this.options.offText,class:this._getClass('handle-off')+' '+this._getClass(this.options.offColor)}),this.$label=g('<span>',{html:this.options.labelText,class:this._getClass('label')}),this.$element.on('init.bootstrapSwitch',this.options.onInit.bind(this,k)),this.$element.on('switchChange.bootstrapSwitch',function(){for(var n=arguments.length,o=Array(n),p=0;p<n;p++)o[p]=arguments[p];!1===l.options.onSwitchChange.apply(k,o)&&(l.$element.is(':radio')?g('[name="'+l.$element.attr('name')+'"]').trigger('previousState.bootstrapSwitch',!0):l.$element.trigger('previousState.bootstrapSwitch',!0))}),this.$container=this.$element.wrap(this.$container).parent(),this.$wrapper=this.$container.wrap(this.$wrapper).parent(),this.$element.before(this.options.inverse?this.$off:this.$on).before(this.$label).before(this.options.inverse?this.$on:this.$off),this.options.indeterminate&&this.$element.prop('indeterminate',!0),this._init(),this._elementHandlers(),this._handleHandlers(),this._labelHandlers(),this._formHandler(),this._externalLabelHandler(),this.$element.trigger('init.bootstrapSwitch',this.options.state)}return f(j,[{key:'setPrevOptions',value:function(){this.prevOptions=e({},this.options)}},{key:'state',value:function(l,m){return'undefined'==typeof l?this.options.state:this.options.disabled||this.options.readonly||this.options.state&&!this.options.radioAllOff&&this.$element.is(':radio')?this.$element:(this.$element.is(':radio')?g('[name="'+this.$element.attr('name')+'"]').trigger('setPreviousOptions.bootstrapSwitch'):this.$element.trigger('setPreviousOptions.bootstrapSwitch'),this.options.indeterminate&&this.indeterminate(!1),this.$element.prop('checked',!!l).trigger('change.bootstrapSwitch',m),this.$element)}},{key:'toggleState',value:function(l){return this.options.disabled||this.options.readonly?this.$element:this.options.indeterminate?(this.indeterminate(!1),this.state(!0)):this.$element.prop('checked',!this.options.state).trigger('change.bootstrapSwitch',l)}},{key:'size',value:function(l){return'undefined'==typeof l?this.options.size:(null!=this.options.size&&this.$wrapper.removeClass(this._getClass(this.options.size)),l&&this.$wrapper.addClass(this._getClass(l)),this._width(),this._containerPosition(),this.options.size=l,this.$element)}},{key:'animate',value:function(l){return'undefined'==typeof l?this.options.animate:this.options.animate===!!l?this.$element:this.toggleAnimate()}},{key:'toggleAnimate',value:function(){return this.options.animate=!this.options.animate,this.$wrapper.toggleClass(this._getClass('animate')),this.$element}},{key:'disabled',value:function(l){return'undefined'==typeof l?this.options.disabled:this.options.disabled===!!l?this.$element:this.toggleDisabled()}},{key:'toggleDisabled',value:function(){return this.options.disabled=!this.options.disabled,this.$element.prop('disabled',this.options.disabled),this.$wrapper.toggleClass(this._getClass('disabled')),this.$element}},{key:'readonly',value:function(l){return'undefined'==typeof l?this.options.readonly:this.options.readonly===!!l?this.$element:this.toggleReadonly()}},{key:'toggleReadonly',value:function(){return this.options.readonly=!this.options.readonly,this.$element.prop('readonly',this.options.readonly),this.$wrapper.toggleClass(this._getClass('readonly')),this.$element}},{key:'indeterminate',value:function(l){return'undefined'==typeof l?this.options.indeterminate:this.options.indeterminate===!!l?this.$element:this.toggleIndeterminate()}},{key:'toggleIndeterminate',value:function(){return this.options.indeterminate=!this.options.indeterminate,this.$element.prop('indeterminate',this.options.indeterminate),this.$wrapper.toggleClass(this._getClass('indeterminate')),this._containerPosition(),this.$element}},{key:'inverse',value:function(l){return'undefined'==typeof l?this.options.inverse:this.options.inverse===!!l?this.$element:this.toggleInverse()}},{key:'toggleInverse',value:function(){this.$wrapper.toggleClass(this._getClass('inverse'));var l=this.$on.clone(!0),m=this.$off.clone(!0);return this.$on.replaceWith(m),this.$off.replaceWith(l),this.$on=m,this.$off=l,this.options.inverse=!this.options.inverse,this.$element}},{key:'onColor',value:function(l){return'undefined'==typeof l?this.options.onColor:(this.options.onColor&&this.$on.removeClass(this._getClass(this.options.onColor)),this.$on.addClass(this._getClass(l)),this.options.onColor=l,this.$element)}},{key:'offColor',value:function(l){return'undefined'==typeof l?this.options.offColor:(this.options.offColor&&this.$off.removeClass(this._getClass(this.options.offColor)),this.$off.addClass(this._getClass(l)),this.options.offColor=l,this.$element)}},{key:'onText',value:function(l){return'undefined'==typeof l?this.options.onText:(this.$on.html(l),this._width(),this._containerPosition(),this.options.onText=l,this.$element)}},{key:'offText',value:function(l){return'undefined'==typeof l?this.options.offText:(this.$off.html(l),this._width(),this._containerPosition(),this.options.offText=l,this.$element)}},{key:'labelText',value:function(l){return'undefined'==typeof l?this.options.labelText:(this.$label.html(l),this._width(),this.options.labelText=l,this.$element)}},{key:'handleWidth',value:function(l){return'undefined'==typeof l?this.options.handleWidth:(this.options.handleWidth=l,this._width(),this._containerPosition(),this.$element)}},{key:'labelWidth',value:function(l){return'undefined'==typeof l?this.options.labelWidth:(this.options.labelWidth=l,this._width(),this._containerPosition(),this.$element)}},{key:'baseClass',value:function(){return this.options.baseClass}},{key:'wrapperClass',value:function(l){return'undefined'==typeof l?this.options.wrapperClass:(l||(l=g.fn.bootstrapSwitch.defaults.wrapperClass),this.$wrapper.removeClass(this._getClasses(this.options.wrapperClass).join(' ')),this.$wrapper.addClass(this._getClasses(l).join(' ')),this.options.wrapperClass=l,this.$element)}},{key:'radioAllOff',value:function(l){if('undefined'==typeof l)return this.options.radioAllOff;var m=!!l;return this.options.radioAllOff===m?this.$element:(this.options.radioAllOff=m,this.$element)}},{key:'onInit',value:function(l){return'undefined'==typeof l?this.options.onInit:(l||(l=g.fn.bootstrapSwitch.defaults.onInit),this.options.onInit=l,this.$element)}},{key:'onSwitchChange',value:function(l){return'undefined'==typeof l?this.options.onSwitchChange:(l||(l=g.fn.bootstrapSwitch.defaults.onSwitchChange),this.options.onSwitchChange=l,this.$element)}},{key:'destroy',value:function(){var l=this.$element.closest('form');return l.length&&l.off('reset.bootstrapSwitch').removeData('bootstrap-switch'),this.$container.children().not(this.$element).remove(),this.$element.unwrap().unwrap().off('.bootstrapSwitch').removeData('bootstrap-switch'),this.$element}},{key:'_getElementOptions',value:function(){return{state:this.$element.is(':checked'),size:this.$element.data('size'),animate:this.$element.data('animate'),disabled:this.$element.is(':disabled'),readonly:this.$element.is('[readonly]'),indeterminate:this.$element.data('indeterminate'),inverse:this.$element.data('inverse'),radioAllOff:this.$element.data('radio-all-off'),onColor:this.$element.data('on-color'),offColor:this.$element.data('off-color'),onText:this.$element.data('on-text'),offText:this.$element.data('off-text'),labelText:this.$element.data('label-text'),handleWidth:this.$element.data('handle-width'),labelWidth:this.$element.data('label-width'),baseClass:this.$element.data('base-class'),wrapperClass:this.$element.data('wrapper-class')}}},{key:'_width',value:function(){var l=this,m=this.$on.add(this.$off).add(this.$label).css('width',''),n='auto'===this.options.handleWidth?Math.round(Math.max(this.$on.width(),this.$off.width())):this.options.handleWidth;return m.width(n),this.$label.width(function(o,p){return'auto'===l.options.labelWidth?p<n?n:p:l.options.labelWidth}),this._handleWidth=this.$on.outerWidth(),this._labelWidth=this.$label.outerWidth(),this.$container.width(2*this._handleWidth+this._labelWidth),this.$wrapper.width(this._handleWidth+this._labelWidth)}},{key:'_containerPosition',value:function(){var l=this,m=0<arguments.length&&void 0!==arguments[0]?arguments[0]:this.options.state,n=arguments[1];this.$container.css('margin-left',function(){var o=[0,'-'+l._handleWidth+'px'];return l.options.indeterminate?'-'+l._handleWidth/2+'px':m?l.options.inverse?o[1]:o[0]:l.options.inverse?o[0]:o[1]})}},{key:'_init',value:function(){var l=this,m=function(){l.setPrevOptions(),l._width(),l._containerPosition(),setTimeout(function(){if(l.options.animate)return l.$wrapper.addClass(l._getClass('animate'))},50)};if(this.$wrapper.is(':visible'))return void m();var n=window.setInterval(function(){if(l.$wrapper.is(':visible'))return m(),window.clearInterval(n)},50)}},{key:'_elementHandlers',value:function(){var l=this;return this.$element.on({'setPreviousOptions.bootstrapSwitch':this.setPrevOptions.bind(this),'previousState.bootstrapSwitch':function(){l.options=l.prevOptions,l.options.indeterminate&&l.$wrapper.addClass(l._getClass('indeterminate')),l.$element.prop('checked',l.options.state).trigger('change.bootstrapSwitch',!0)},'change.bootstrapSwitch':function(n,o){n.preventDefault(),n.stopImmediatePropagation();var p=l.$element.is(':checked');l._containerPosition(p),p===l.options.state||(l.options.state=p,l.$wrapper.toggleClass(l._getClass('off')).toggleClass(l._getClass('on')),!o&&(l.$element.is(':radio')&&g('[name="'+l.$element.attr('name')+'"]').not(l.$element).prop('checked',!1).trigger('change.bootstrapSwitch',!0),l.$element.trigger('switchChange.bootstrapSwitch',[p])))},'focus.bootstrapSwitch':function(n){n.preventDefault(),l.$wrapper.addClass(l._getClass('focused'))},'blur.bootstrapSwitch':function(n){n.preventDefault(),l.$wrapper.removeClass(l._getClass('focused'))},'keydown.bootstrapSwitch':function(n){!n.which||l.options.disabled||l.options.readonly||(37===n.which||39===n.which)&&(n.preventDefault(),n.stopImmediatePropagation(),l.state(39===n.which))}})}},{key:'_handleHandlers',value:function(){var l=this;return this.$on.on('click.bootstrapSwitch',function(m){return m.preventDefault(),m.stopPropagation(),l.state(!1),l.$element.trigger('focus.bootstrapSwitch')}),this.$off.on('click.bootstrapSwitch',function(m){return m.preventDefault(),m.stopPropagation(),l.state(!0),l.$element.trigger('focus.bootstrapSwitch')})}},{key:'_labelHandlers',value:function(){var l=this;this.$label.on({click:function(o){o.stopPropagation()},'mousedown.bootstrapSwitch touchstart.bootstrapSwitch':function(o){l._dragStart||l.options.disabled||l.options.readonly||(o.preventDefault(),o.stopPropagation(),l._dragStart=(o.pageX||o.originalEvent.touches[0].pageX)-parseInt(l.$container.css('margin-left'),10),l.options.animate&&l.$wrapper.removeClass(l._getClass('animate')),l.$element.trigger('focus.bootstrapSwitch'))},'mousemove.bootstrapSwitch touchmove.bootstrapSwitch':function(o){if(null!=l._dragStart){var p=(o.pageX||o.originalEvent.touches[0].pageX)-l._dragStart;o.preventDefault(),p<-l._handleWidth||0<p||(l._dragEnd=p,l.$container.css('margin-left',l._dragEnd+'px'))}},'mouseup.bootstrapSwitch touchend.bootstrapSwitch':function(o){if(l._dragStart){if(o.preventDefault(),l.options.animate&&l.$wrapper.addClass(l._getClass('animate')),l._dragEnd){var p=l._dragEnd>-(l._handleWidth/2);l._dragEnd=!1,l.state(l.options.inverse?!p:p)}else l.state(!l.options.state);l._dragStart=!1}},'mouseleave.bootstrapSwitch':function(){l.$label.trigger('mouseup.bootstrapSwitch')}})}},{key:'_externalLabelHandler',value:function(){var l=this,m=this.$element.closest('label');m.on('click',function(n){n.preventDefault(),n.stopImmediatePropagation(),n.target===m[0]&&l.toggleState()})}},{key:'_formHandler',value:function(){var l=this.$element.closest('form');l.data('bootstrap-switch')||l.on('reset.bootstrapSwitch',function(){window.setTimeout(function(){l.find('input').filter(function(){return g(this).data('bootstrap-switch')}).each(function(){return g(this).bootstrapSwitch('state',this.checked)})},1)}).data('bootstrap-switch',!0)}},{key:'_getClass',value:function(l){return this.options.baseClass+'-'+l}},{key:'_getClasses',value:function(l){return g.isArray(l)?l.map(this._getClass.bind(this)):[this._getClass(l)]}}]),j}();g.fn.bootstrapSwitch=function(j){for(var l=arguments.length,m=Array(1<l?l-1:0),n=1;n<l;n++)m[n-1]=arguments[n];return Array.prototype.reduce.call(this,function(o,p){var q=g(p),r=q.data('bootstrap-switch'),s=r||new h(p,j);return r||q.data('bootstrap-switch',s),'string'==typeof j?s[j].apply(s,m):o},this)},g.fn.bootstrapSwitch.Constructor=h,g.fn.bootstrapSwitch.defaults={state:!0,size:null,animate:!0,disabled:!1,readonly:!1,indeterminate:!1,inverse:!1,radioAllOff:!1,onColor:'primary',offColor:'default',onText:'ON',offText:'OFF',labelText:'&nbsp',handleWidth:'auto',labelWidth:'auto',baseClass:'bootstrap-switch',wrapperClass:'wrapper',onInit:function(){},onSwitchChange:function(){}}});
499
 
500
  /* caret v1.3.3 | https://github.com/accursoft/caret | Copyright (c) 2009 Gideon Sireling. Released under the BSD3 license. */
501
  !function(e){e.fn.caret=function(e){var t=this[0],n="true"===t.contentEditable;if(0==arguments.length){if(window.getSelection){if(n){t.focus();var o=window.getSelection().getRangeAt(0),r=o.cloneRange();return r.selectNodeContents(t),r.setEnd(o.endContainer,o.endOffset),r.toString().length}return t.selectionStart}if(document.selection){if(t.focus(),n){var o=document.selection.createRange(),r=document.body.createTextRange();return r.moveToElementText(t),r.setEndPoint("EndToEnd",o),r.text.length}var e=0,c=t.createTextRange(),r=document.selection.createRange().duplicate(),a=r.getBookmark();for(c.moveToBookmark(a);0!==c.moveStart("character",-1);)e++;return e}return t.selectionStart?t.selectionStart:0}if(-1==e&&(e=this[n?"text":"val"]().length),window.getSelection)n?(t.focus(),window.getSelection().collapse(t.firstChild,e)):t.setSelectionRange(e,e);else if(document.body.createTextRange)if(n){var c=document.body.createTextRange();c.moveToElementText(t),c.moveStart("character",e),c.collapse(!0),c.select()}else{var c=t.createTextRange();c.move("character",e),c.select()}return n||t.focus(),e}}(jQuery);
502
 
503
+ /* jQuery tagEditor v1.0.21 | https://github.com/Pixabay/jQuery-tagEditor | Copyright (c) 2013 Pixabay. Licensed under the MIT license. */
504
+ !function(t){t.fn.tagEditorInput=function(){var e=" ",i=t(this),a=parseInt(i.css("fontSize")),r=t("<span/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:i.css("fontSize"),fontFamily:i.css("fontFamily"),fontWeight:i.css("fontWeight"),letterSpacing:i.css("letterSpacing"),whiteSpace:"nowrap"}),l=function(){if(e!==(e=i.val())){r.text(e);var t=r.width()+a;20>t&&(t=20),t!=i.width()&&i.width(t)}};return r.insertAfter(i),i.bind("keyup keydown focus",l)},t.fn.tagEditor=function(e,a,r){function l(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var n,o=t.extend({},t.fn.tagEditor.defaults,e),c=this;if(o.dregex=new RegExp("["+o.delimiter.replace("-","-")+"]","g"),"string"==typeof e){var s=[];return c.each(function(){var i=t(this),l=i.data("options"),n=i.next(".tag-editor");if("getTags"==e)s.push({field:i[0],editor:n,tags:n.data("tags")});else if("addTag"==e){if(l.maxTags&&n.data("tags").length>=l.maxTags)return!1;t('<li><div class="tag-editor-spacer">&nbsp;'+l.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>').appendTo(n).find(".tag-editor-tag").html('<input type="text" maxlength="'+l.maxLength+'">').addClass("active").find("input").val(a).blur(),r?t(".placeholder",n).remove():n.click()}else"removeTag"==e?(t(".tag-editor-tag",n).filter(function(){return t(this).text()==a}).closest("li").find(".tag-editor-delete").click(),r||n.click()):"destroy"==e&&i.removeClass("tag-editor-hidden-src").removeData("options").off("focus.tag-editor").next(".tag-editor").remove()}),"getTags"==e?s:this}return window.getSelection&&t(document).off("keydown.tag-editor").on("keydown.tag-editor",function(e){if(8==e.which||46==e.which||e.ctrlKey&&88==e.which){try{var a=getSelection(),r="INPUT"!=document.activeElement.tagName?t(a.getRangeAt(0).startContainer.parentNode).closest(".tag-editor"):0}catch(e){r=0}if(a.rangeCount>0&&r&&r.length){var l=[],n=a.toString().split(r.prev().data("options").dregex);for(i=0;i<n.length;i++){var o=t.trim(n[i]);o&&l.push(o)}return t(".tag-editor-tag",r).each(function(){~t.inArray(t(this).text(),l)&&t(this).closest("li").find(".tag-editor-delete").click()}),!1}}}),c.each(function(){function e(){!o.placeholder||c.length||t(".deleted, .placeholder, input",s).length||s.append('<li class="placeholder"><div>'+o.placeholder+"</div></li>")}function i(i){var a=c.toString();c=t(".tag-editor-tag:not(.deleted)",s).map(function(e,i){var a=t.trim(t(this).hasClass("active")?t(this).find("input").val():t(i).text());return a?a:void 0}).get(),s.data("tags",c),r.val(c.join(o.delimiter[0])),i||a!=c.toString()&&o.onChange(r,s,c),e()}function a(e){for(var a,n=e.closest("li"),d=e.val().replace(/ +/," ").split(o.dregex),g=e.data("old_tag"),f=c.slice(0),h=!1,u=0;u<d.length;u++)if(v=t.trim(d[u]).slice(0,o.maxLength),o.forceLowercase&&(v=v.toLowerCase()),a=o.beforeTagSave(r,s,f,g,v),v=a||v,a!==!1&&v&&(o.removeDuplicates&&~t.inArray(v,f)&&t(".tag-editor-tag",s).each(function(){t(this).text()==v&&t(this).closest("li").remove()}),f.push(v),n.before('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+l(v)+'</div><div class="tag-editor-delete"><i></i></div></li>'),o.maxTags&&f.length>=o.maxTags)){h=!0;break}e.attr("maxlength",o.maxLength).removeData("old_tag").val(""),h?e.blur():e.focus(),i()}var r=t(this),c=[],s=t("<ul "+(o.clickDelete?'oncontextmenu="return false;" ':"")+'class="tag-editor"></ul>').insertAfter(r);r.addClass("tag-editor-hidden-src").data("options",o).on("focus.tag-editor",function(){s.click()}),s.append('<li style="width:1px">&nbsp;</li>');var d='<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag"></div><div class="tag-editor-delete"><i></i></div></li>';s.click(function(e,i){var a,r,l=99999;if(!window.getSelection||""==getSelection())return o.maxTags&&s.data("tags").length>=o.maxTags?(s.find("input").blur(),!1):(n=!0,t("input:focus",s).blur(),n?(n=!0,t(".placeholder",s).remove(),i&&i.length?r="before":t(".tag-editor-tag",s).each(function(){var n=t(this),o=n.offset(),c=o.left,s=o.top;e.pageY>=s&&e.pageY<=s+n.height()&&(e.pageX<c?(r="before",a=c-e.pageX):(r="after",a=e.pageX-c-n.width()),l>a&&(l=a,i=n))}),"before"==r?t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click():"after"==r?t(d).insertAfter(i.closest("li")).find(".tag-editor-tag").click():t(d).appendTo(s).find(".tag-editor-tag").click(),!1):!1)}),s.on("click",".tag-editor-delete",function(){if(t(this).prev().hasClass("active"))return t(this).closest("li").find("input").caret(-1),!1;var a=t(this).closest("li"),l=a.find(".tag-editor-tag");return o.beforeTagDelete(r,s,c,l.text())===!1?!1:(l.addClass("deleted").animate({width:0},o.animateDelete,function(){a.remove(),e()}),i(),!1)}),o.clickDelete&&s.on("mousedown",".tag-editor-tag",function(a){if(a.ctrlKey||a.which>1){var l=t(this).closest("li"),n=l.find(".tag-editor-tag");return o.beforeTagDelete(r,s,c,n.text())===!1?!1:(n.addClass("deleted").animate({width:0},o.animateDelete,function(){l.remove(),e()}),i(),!1)}}),s.on("click",".tag-editor-tag",function(e){if(o.clickDelete&&(e.ctrlKey||e.which>1))return!1;if(!t(this).hasClass("active")){var i=t(this).text(),a=Math.abs((t(this).offset().left-e.pageX)/t(this).width()),r=parseInt(i.length*a),n=t(this).html('<input type="text" maxlength="'+o.maxLength+'" value="'+l(i)+'">').addClass("active").find("input");if(n.data("old_tag",i).tagEditorInput().focus().caret(r),o.autocomplete){var c=t.extend({},o.autocomplete),d="select"in c?o.autocomplete.select:"";c.select=function(e,i){d&&d(e,i),setTimeout(function(){s.trigger("click",[t(".active",s).find("input").closest("li").next("li").find(".tag-editor-tag")])},20)},n.autocomplete(c)}}return!1}),s.on("blur","input",function(d){d.stopPropagation();var g=t(this),f=g.data("old_tag"),h=t.trim(g.val().replace(/ +/," ").replace(o.dregex,o.delimiter[0]));if(h){if(h.indexOf(o.delimiter[0])>=0)return void a(g);if(h!=f)if(o.forceLowercase&&(h=h.toLowerCase()),cb_val=o.beforeTagSave(r,s,c,f,h),h=cb_val||h,cb_val===!1){if(f)return g.val(f).focus(),n=!1,void i();try{g.closest("li").remove()}catch(d){}f&&i()}else o.removeDuplicates&&t(".tag-editor-tag:not(.active)",s).each(function(){t(this).text()==h&&t(this).closest("li").remove()})}else{if(f&&o.beforeTagDelete(r,s,c,f)===!1)return g.val(f).focus(),n=!1,void i();try{g.closest("li").remove()}catch(d){}f&&i()}g.parent().html(l(h)).removeClass("active"),h!=f&&i(),e()});var g;s.on("paste","input",function(){t(this).removeAttr("maxlength"),g=t(this),setTimeout(function(){a(g)},30)});var f;s.on("keypress","input",function(e){o.delimiter.indexOf(String.fromCharCode(e.which))>=0&&(f=t(this),setTimeout(function(){a(f)},20))}),s.on("keydown","input",function(e){var i=t(this);if((37==e.which||!o.autocomplete&&38==e.which)&&!i.caret()||8==e.which&&!i.val()){var a=i.closest("li").prev("li").find(".tag-editor-tag");return a.length?a.click().find("input").caret(-1):!i.val()||o.maxTags&&s.data("tags").length>=o.maxTags||t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click(),!1}if((39==e.which||!o.autocomplete&&40==e.which)&&i.caret()==i.val().length){var l=i.closest("li").next("li").find(".tag-editor-tag");return l.length?l.click().find("input").caret(0):i.val()&&s.click(),!1}if(9==e.which){if(e.shiftKey){var a=i.closest("li").prev("li").find(".tag-editor-tag");if(a.length)a.click().find("input").caret(0);else{if(!i.val()||o.maxTags&&s.data("tags").length>=o.maxTags)return r.attr("disabled","disabled"),void setTimeout(function(){r.removeAttr("disabled")},30);t(d).insertBefore(i.closest("li")).find(".tag-editor-tag").click()}return!1}var l=i.closest("li").next("li").find(".tag-editor-tag");if(l.length)l.click().find("input").caret(0);else{if(!i.val())return;s.click()}return!1}if(!(46!=e.which||t.trim(i.val())&&i.caret()!=i.val().length)){var l=i.closest("li").next("li").find(".tag-editor-tag");return l.length?l.click().find("input").caret(0):i.val()&&s.click(),!1}if(13==e.which)return s.trigger("click",[i.closest("li").next("li").find(".tag-editor-tag")]),o.maxTags&&s.data("tags").length>=o.maxTags&&s.find("input").blur(),!1;if(36!=e.which||i.caret()){if(35==e.which&&i.caret()==i.val().length)s.find(".tag-editor-tag").last().click();else if(27==e.which)return i.val(i.data("old_tag")?i.data("old_tag"):"").blur(),!1}else s.find(".tag-editor-tag").first().click()});for(var h=o.initialTags.length?o.initialTags:r.val().split(o.dregex),u=0;u<h.length&&!(o.maxTags&&u>=o.maxTags);u++){var v=t.trim(h[u].replace(/ +/," "));v&&(o.forceLowercase&&(v=v.toLowerCase()),c.push(v),s.append('<li><div class="tag-editor-spacer">&nbsp;'+o.delimiter[0]+'</div><div class="tag-editor-tag">'+l(v)+'</div><div class="tag-editor-delete"><i></i></div></li>'))}i(!0),o.sortable&&t.fn.sortable&&s.sortable({distance:5,cancel:".tag-editor-spacer, input",helper:"clone",update:function(){i()}})})},t.fn.tagEditor.defaults={initialTags:[],maxTags:0,maxLength:50,delimiter:",;",placeholder:"",forceLowercase:!0,removeDuplicates:!0,clickDelete:!1,animateDelete:175,sortable:!0,autocomplete:null,onChange:function(){},beforeTagSave:function(){},beforeTagDelete:function(){}}}(jQuery);
admin/update-checker/Puc/v4/Factory.php ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4_Factory', false) ):
3
+
4
+ /**
5
+ * A factory that builds update checker instances.
6
+ *
7
+ * When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
8
+ * and 4.1), this factory will always use the latest available minor version. Register class
9
+ * versions by calling {@link PucFactory::addVersion()}.
10
+ *
11
+ * At the moment it can only build instances of the UpdateChecker class. Other classes are
12
+ * intended mainly for internal use and refer directly to specific implementations.
13
+ */
14
+ class Puc_v4_Factory {
15
+ protected static $classVersions = array();
16
+ protected static $sorted = false;
17
+
18
+ protected static $myMajorVersion = '';
19
+ protected static $latestCompatibleVersion = '';
20
+
21
+ /**
22
+ * Create a new instance of the update checker.
23
+ *
24
+ * This method automatically detects if you're using it for a plugin or a theme and chooses
25
+ * the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc).
26
+ *
27
+ * @see Puc_v4p2_UpdateChecker::__construct
28
+ *
29
+ * @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source.
30
+ * @param string $fullPath Full path to the main plugin file or to the theme directory.
31
+ * @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory.
32
+ * @param int $checkPeriod How often to check for updates (in hours).
33
+ * @param string $optionName Where to store book-keeping info about update checks.
34
+ * @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
35
+ * @return Puc_v4p2_Plugin_UpdateChecker|Puc_v4p2_Theme_UpdateChecker|Puc_v4p2_Vcs_BaseChecker
36
+ */
37
+ public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
38
+ $fullPath = wp_normalize_path($fullPath);
39
+ $id = null;
40
+
41
+ //Plugin or theme?
42
+ $themeDirectory = self::getThemeDirectoryName($fullPath);
43
+ if ( self::isPluginFile($fullPath) ) {
44
+ $type = 'Plugin';
45
+ $id = $fullPath;
46
+ } else if ( $themeDirectory !== null ) {
47
+ $type = 'Theme';
48
+ $id = $themeDirectory;
49
+ } else {
50
+ throw new RuntimeException(sprintf(
51
+ 'The update checker cannot determine if "%s" is a plugin or a theme. ' .
52
+ 'This is a bug. Please contact the PUC developer.',
53
+ htmlentities($fullPath)
54
+ ));
55
+ }
56
+
57
+ //Which hosting service does the URL point to?
58
+ $service = self::getVcsService($metadataUrl);
59
+
60
+ $apiClass = null;
61
+ if ( empty($service) ) {
62
+ //The default is to get update information from a remote JSON file.
63
+ $checkerClass = $type . '_UpdateChecker';
64
+ } else {
65
+ //You can also use a VCS repository like GitHub.
66
+ $checkerClass = 'Vcs_' . $type . 'UpdateChecker';
67
+ $apiClass = $service . 'Api';
68
+ }
69
+
70
+ $checkerClass = self::getCompatibleClassVersion($checkerClass);
71
+ if ( $checkerClass === null ) {
72
+ trigger_error(
73
+ sprintf(
74
+ 'PUC %s does not support updates for %ss %s',
75
+ htmlentities(self::$latestCompatibleVersion),
76
+ strtolower($type),
77
+ $service ? ('hosted on ' . htmlentities($service)) : 'using JSON metadata'
78
+ ),
79
+ E_USER_ERROR
80
+ );
81
+ return null;
82
+ }
83
+
84
+ if ( !isset($apiClass) ) {
85
+ //Plain old update checker.
86
+ return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
87
+ } else {
88
+ //VCS checker + an API client.
89
+ $apiClass = self::getCompatibleClassVersion($apiClass);
90
+ if ( $apiClass === null ) {
91
+ trigger_error(sprintf(
92
+ 'PUC %s does not support %s',
93
+ htmlentities(self::$latestCompatibleVersion),
94
+ htmlentities($service)
95
+ ), E_USER_ERROR);
96
+ return null;
97
+ }
98
+
99
+ return new $checkerClass(
100
+ new $apiClass($metadataUrl),
101
+ $id,
102
+ $slug,
103
+ $checkPeriod,
104
+ $optionName,
105
+ $muPluginFile
106
+ );
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Check if the path points to a plugin file.
112
+ *
113
+ * @param string $absolutePath Normalized path.
114
+ * @return bool
115
+ */
116
+ protected static function isPluginFile($absolutePath) {
117
+ //Is the file inside the "plugins" or "mu-plugins" directory?
118
+ $pluginDir = wp_normalize_path(WP_PLUGIN_DIR);
119
+ $muPluginDir = wp_normalize_path(WPMU_PLUGIN_DIR);
120
+ if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
121
+ return true;
122
+ }
123
+
124
+ //Is it a file at all? Caution: is_file() can fail if the parent dir. doesn't have the +x permission set.
125
+ if ( !is_file($absolutePath) ) {
126
+ return false;
127
+ }
128
+
129
+ //Does it have a valid plugin header?
130
+ //This is a last-ditch check for plugins symlinked from outside the WP root.
131
+ if ( function_exists('get_file_data') ) {
132
+ $headers = get_file_data($absolutePath, array('Name' => 'Plugin Name'), 'plugin');
133
+ return !empty($headers['Name']);
134
+ }
135
+
136
+ return false;
137
+ }
138
+
139
+ /**
140
+ * Get the name of the theme's directory from a full path to a file inside that directory.
141
+ * E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo".
142
+ *
143
+ * Note that subdirectories are currently not supported. For example,
144
+ * "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL.
145
+ *
146
+ * @param string $absolutePath Normalized path.
147
+ * @return string|null Directory name, or NULL if the path doesn't point to a theme.
148
+ */
149
+ protected static function getThemeDirectoryName($absolutePath) {
150
+ if ( is_file($absolutePath) ) {
151
+ $absolutePath = dirname($absolutePath);
152
+ }
153
+
154
+ if ( file_exists($absolutePath . '/style.css') ) {
155
+ return basename($absolutePath);
156
+ }
157
+ return null;
158
+ }
159
+
160
+ /**
161
+ * Get the name of the hosting service that the URL points to.
162
+ *
163
+ * @param string $metadataUrl
164
+ * @return string|null
165
+ */
166
+ private static function getVcsService($metadataUrl) {
167
+ $service = null;
168
+
169
+ //Which hosting service does the URL point to?
170
+ $host = @parse_url($metadataUrl, PHP_URL_HOST);
171
+ $path = @parse_url($metadataUrl, PHP_URL_PATH);
172
+ //Check if the path looks like "/user-name/repository".
173
+ $usernameRepoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
174
+ if ( preg_match($usernameRepoRegex, $path) ) {
175
+ $knownServices = array(
176
+ 'github.com' => 'GitHub',
177
+ 'bitbucket.org' => 'BitBucket',
178
+ 'gitlab.com' => 'GitLab',
179
+ );
180
+ if ( isset($knownServices[$host]) ) {
181
+ $service = $knownServices[$host];
182
+ }
183
+ }
184
+
185
+ return $service;
186
+ }
187
+
188
+ /**
189
+ * Get the latest version of the specified class that has the same major version number
190
+ * as this factory class.
191
+ *
192
+ * @param string $class Partial class name.
193
+ * @return string|null Full class name.
194
+ */
195
+ protected static function getCompatibleClassVersion($class) {
196
+ if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
197
+ return self::$classVersions[$class][self::$latestCompatibleVersion];
198
+ }
199
+ return null;
200
+ }
201
+
202
+ /**
203
+ * Get the specific class name for the latest available version of a class.
204
+ *
205
+ * @param string $class
206
+ * @return null|string
207
+ */
208
+ public static function getLatestClassVersion($class) {
209
+ if ( !self::$sorted ) {
210
+ self::sortVersions();
211
+ }
212
+
213
+ if ( isset(self::$classVersions[$class]) ) {
214
+ return reset(self::$classVersions[$class]);
215
+ } else {
216
+ return null;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Sort available class versions in descending order (i.e. newest first).
222
+ */
223
+ protected static function sortVersions() {
224
+ foreach ( self::$classVersions as $class => $versions ) {
225
+ uksort($versions, array(__CLASS__, 'compareVersions'));
226
+ self::$classVersions[$class] = $versions;
227
+ }
228
+ self::$sorted = true;
229
+ }
230
+
231
+ protected static function compareVersions($a, $b) {
232
+ return -version_compare($a, $b);
233
+ }
234
+
235
+ /**
236
+ * Register a version of a class.
237
+ *
238
+ * @access private This method is only for internal use by the library.
239
+ *
240
+ * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
241
+ * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
242
+ * @param string $version Version number, e.g. '1.2'.
243
+ */
244
+ public static function addVersion($generalClass, $versionedClass, $version) {
245
+ if ( empty(self::$myMajorVersion) ) {
246
+ $nameParts = explode('_', __CLASS__, 3);
247
+ self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1);
248
+ }
249
+
250
+ //Store the greatest version number that matches our major version.
251
+ $components = explode('.', $version);
252
+ if ( $components[0] === self::$myMajorVersion ) {
253
+
254
+ if (
255
+ empty(self::$latestCompatibleVersion)
256
+ || version_compare($version, self::$latestCompatibleVersion, '>')
257
+ ) {
258
+ self::$latestCompatibleVersion = $version;
259
+ }
260
+
261
+ }
262
+
263
+ if ( !isset(self::$classVersions[$generalClass]) ) {
264
+ self::$classVersions[$generalClass] = array();
265
+ }
266
+ self::$classVersions[$generalClass][$version] = $versionedClass;
267
+ self::$sorted = false;
268
+ }
269
+ }
270
+
271
+ endif;
admin/update-checker/Puc/v4p2/Autoloader.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Autoloader', false) ):
4
+
5
+ class Puc_v4p2_Autoloader {
6
+ private $prefix = '';
7
+ private $rootDir = '';
8
+ private $libraryDir = '';
9
+
10
+ private $staticMap;
11
+
12
+ public function __construct() {
13
+ $this->rootDir = dirname(__FILE__) . '/';
14
+ $nameParts = explode('_', __CLASS__, 3);
15
+ $this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
16
+
17
+ $this->libraryDir = realpath($this->rootDir . '../..') . '/';
18
+ $this->staticMap = array(
19
+ 'PucReadmeParser' => 'vendor/readme-parser.php',
20
+ 'Parsedown' => 'vendor/ParsedownLegacy.php',
21
+ );
22
+ if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
23
+ $this->staticMap['Parsedown'] = 'vendor/Parsedown.php';
24
+ }
25
+
26
+ spl_autoload_register(array($this, 'autoload'));
27
+ }
28
+
29
+ public function autoload($className) {
30
+ if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
31
+ /** @noinspection PhpIncludeInspection */
32
+ include ($this->libraryDir . $this->staticMap[$className]);
33
+ return;
34
+ }
35
+
36
+ if (strpos($className, $this->prefix) === 0) {
37
+ $path = substr($className, strlen($this->prefix));
38
+ $path = str_replace('_', '/', $path);
39
+ $path = $this->rootDir . $path . '.php';
40
+
41
+ if (file_exists($path)) {
42
+ /** @noinspection PhpIncludeInspection */
43
+ include $path;
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ endif;
admin/update-checker/Puc/v4p2/Metadata.php ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Metadata', false) ):
3
+
4
+ /**
5
+ * A base container for holding information about updates and plugin metadata.
6
+ *
7
+ * @author Janis Elsts
8
+ * @copyright 2016
9
+ * @access public
10
+ */
11
+ abstract class Puc_v4p2_Metadata {
12
+
13
+ /**
14
+ * Create an instance of this class from a JSON document.
15
+ *
16
+ * @abstract
17
+ * @param string $json
18
+ * @return self
19
+ */
20
+ public static function fromJson(/** @noinspection PhpUnusedParameterInspection */ $json) {
21
+ throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
22
+ }
23
+
24
+ /**
25
+ * @param string $json
26
+ * @param self $target
27
+ * @return bool
28
+ */
29
+ protected static function createFromJson($json, $target) {
30
+ /** @var StdClass $apiResponse */
31
+ $apiResponse = json_decode($json);
32
+ if ( empty($apiResponse) || !is_object($apiResponse) ){
33
+ trigger_error(
34
+ "Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/",
35
+ E_USER_NOTICE
36
+ );
37
+ return false;
38
+ }
39
+
40
+ $valid = $target->validateMetadata($apiResponse);
41
+ if ( is_wp_error($valid) ){
42
+ trigger_error($valid->get_error_message(), E_USER_NOTICE);
43
+ return false;
44
+ }
45
+
46
+ foreach(get_object_vars($apiResponse) as $key => $value){
47
+ $target->$key = $value;
48
+ }
49
+
50
+ return true;
51
+ }
52
+
53
+ /**
54
+ * No validation by default! Subclasses should check that the required fields are present.
55
+ *
56
+ * @param StdClass $apiResponse
57
+ * @return bool|WP_Error
58
+ */
59
+ protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) {
60
+ return true;
61
+ }
62
+
63
+ /**
64
+ * Create a new instance by copying the necessary fields from another object.
65
+ *
66
+ * @abstract
67
+ * @param StdClass|self $object The source object.
68
+ * @return self The new copy.
69
+ */
70
+ public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) {
71
+ throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
72
+ }
73
+
74
+ /**
75
+ * Create an instance of StdClass that can later be converted back to an
76
+ * update or info container. Useful for serialization and caching, as it
77
+ * avoids the "incomplete object" problem if the cached value is loaded
78
+ * before this class.
79
+ *
80
+ * @return StdClass
81
+ */
82
+ public function toStdClass() {
83
+ $object = new stdClass();
84
+ $this->copyFields($this, $object);
85
+ return $object;
86
+ }
87
+
88
+ /**
89
+ * Transform the metadata into the format used by WordPress core.
90
+ *
91
+ * @return object
92
+ */
93
+ abstract public function toWpFormat();
94
+
95
+ /**
96
+ * Copy known fields from one object to another.
97
+ *
98
+ * @param StdClass|self $from
99
+ * @param StdClass|self $to
100
+ */
101
+ protected function copyFields($from, $to) {
102
+ $fields = $this->getFieldNames();
103
+
104
+ if ( property_exists($from, 'slug') && !empty($from->slug) ) {
105
+ //Let plugins add extra fields without having to create subclasses.
106
+ $fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields);
107
+ }
108
+
109
+ foreach ($fields as $field) {
110
+ if ( property_exists($from, $field) ) {
111
+ $to->$field = $from->$field;
112
+ }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * @return string[]
118
+ */
119
+ protected function getFieldNames() {
120
+ return array();
121
+ }
122
+
123
+ /**
124
+ * @param string $tag
125
+ * @return string
126
+ */
127
+ protected function getPrefixedFilter($tag) {
128
+ return 'puc_' . $tag;
129
+ }
130
+ }
131
+
132
+ endif;
admin/update-checker/Puc/v4p2/Plugin/Info.php ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Plugin_Info', false) ):
3
+
4
+ /**
5
+ * A container class for holding and transforming various plugin metadata.
6
+ *
7
+ * @author Janis Elsts
8
+ * @copyright 2016
9
+ * @access public
10
+ */
11
+ class Puc_v4p2_Plugin_Info extends Puc_v4p2_Metadata {
12
+ //Most fields map directly to the contents of the plugin's info.json file.
13
+ //See the relevant docs for a description of their meaning.
14
+ public $name;
15
+ public $slug;
16
+ public $version;
17
+ public $homepage;
18
+ public $sections = array();
19
+ public $banners;
20
+ public $translations = array();
21
+ public $download_url;
22
+
23
+ public $author;
24
+ public $author_homepage;
25
+
26
+ public $requires;
27
+ public $tested;
28
+ public $upgrade_notice;
29
+
30
+ public $rating;
31
+ public $num_ratings;
32
+ public $downloaded;
33
+ public $active_installs;
34
+ public $last_updated;
35
+
36
+ public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
37
+
38
+ public $filename; //Plugin filename relative to the plugins directory.
39
+
40
+ /**
41
+ * Create a new instance of Plugin Info from JSON-encoded plugin info
42
+ * returned by an external update API.
43
+ *
44
+ * @param string $json Valid JSON string representing plugin info.
45
+ * @return self|null New instance of Plugin Info, or NULL on error.
46
+ */
47
+ public static function fromJson($json){
48
+ $instance = new self();
49
+
50
+ if ( !parent::createFromJson($json, $instance) ) {
51
+ return null;
52
+ }
53
+
54
+ //json_decode decodes assoc. arrays as objects. We want it as an array.
55
+ $instance->sections = (array)$instance->sections;
56
+
57
+ return $instance;
58
+ }
59
+
60
+ /**
61
+ * Very, very basic validation.
62
+ *
63
+ * @param StdClass $apiResponse
64
+ * @return bool|WP_Error
65
+ */
66
+ protected function validateMetadata($apiResponse) {
67
+ if (
68
+ !isset($apiResponse->name, $apiResponse->version)
69
+ || empty($apiResponse->name)
70
+ || empty($apiResponse->version)
71
+ ) {
72
+ return new WP_Error(
73
+ 'puc-invalid-metadata',
74
+ "The plugin metadata file does not contain the required 'name' and/or 'version' keys."
75
+ );
76
+ }
77
+ return true;
78
+ }
79
+
80
+
81
+ /**
82
+ * Transform plugin info into the format used by the native WordPress.org API
83
+ *
84
+ * @return object
85
+ */
86
+ public function toWpFormat(){
87
+ $info = new stdClass;
88
+
89
+ //The custom update API is built so that many fields have the same name and format
90
+ //as those returned by the native WordPress.org API. These can be assigned directly.
91
+ $sameFormat = array(
92
+ 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
93
+ 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
94
+ );
95
+ foreach($sameFormat as $field){
96
+ if ( isset($this->$field) ) {
97
+ $info->$field = $this->$field;
98
+ } else {
99
+ $info->$field = null;
100
+ }
101
+ }
102
+
103
+ //Other fields need to be renamed and/or transformed.
104
+ $info->download_link = $this->download_url;
105
+ $info->author = $this->getFormattedAuthor();
106
+ $info->sections = array_merge(array('description' => ''), $this->sections);
107
+
108
+ if ( !empty($this->banners) ) {
109
+ //WP expects an array with two keys: "high" and "low". Both are optional.
110
+ //Docs: https://wordpress.org/plugins/about/faq/#banners
111
+ $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
112
+ $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
113
+ }
114
+
115
+ return $info;
116
+ }
117
+
118
+ protected function getFormattedAuthor() {
119
+ if ( !empty($this->author_homepage) ){
120
+ /** @noinspection HtmlUnknownTarget */
121
+ return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
122
+ }
123
+ return $this->author;
124
+ }
125
+ }
126
+
127
+ endif;
admin/update-checker/Puc/v4p2/Plugin/Update.php ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Plugin_Update', false) ):
3
+
4
+ /**
5
+ * A simple container class for holding information about an available update.
6
+ *
7
+ * @author Janis Elsts
8
+ * @copyright 2016
9
+ * @access public
10
+ */
11
+ class Puc_v4p2_Plugin_Update extends Puc_v4p2_Update {
12
+ public $id = 0;
13
+ public $homepage;
14
+ public $upgrade_notice;
15
+ public $tested;
16
+ public $filename; //Plugin filename relative to the plugins directory.
17
+
18
+ protected static $extraFields = array(
19
+ 'id', 'homepage', 'tested', 'upgrade_notice', 'filename',
20
+ );
21
+
22
+ /**
23
+ * Create a new instance of PluginUpdate from its JSON-encoded representation.
24
+ *
25
+ * @param string $json
26
+ * @return Puc_v4p2_Plugin_Update|null
27
+ */
28
+ public static function fromJson($json){
29
+ //Since update-related information is simply a subset of the full plugin info,
30
+ //we can parse the update JSON as if it was a plugin info string, then copy over
31
+ //the parts that we care about.
32
+ $pluginInfo = Puc_v4p2_Plugin_Info::fromJson($json);
33
+ if ( $pluginInfo !== null ) {
34
+ return self::fromPluginInfo($pluginInfo);
35
+ } else {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Create a new instance of PluginUpdate based on an instance of PluginInfo.
42
+ * Basically, this just copies a subset of fields from one object to another.
43
+ *
44
+ * @param Puc_v4p2_Plugin_Info $info
45
+ * @return Puc_v4p2_Plugin_Update
46
+ */
47
+ public static function fromPluginInfo($info){
48
+ return self::fromObject($info);
49
+ }
50
+
51
+ /**
52
+ * Create a new instance by copying the necessary fields from another object.
53
+ *
54
+ * @param StdClass|Puc_v4p2_Plugin_Info|Puc_v4p2_Plugin_Update $object The source object.
55
+ * @return Puc_v4p2_Plugin_Update The new copy.
56
+ */
57
+ public static function fromObject($object) {
58
+ $update = new self();
59
+ $update->copyFields($object, $update);
60
+ return $update;
61
+ }
62
+
63
+ /**
64
+ * @return string[]
65
+ */
66
+ protected function getFieldNames() {
67
+ return array_merge(parent::getFieldNames(), self::$extraFields);
68
+ }
69
+
70
+ /**
71
+ * Transform the update into the format used by WordPress native plugin API.
72
+ *
73
+ * @return object
74
+ */
75
+ public function toWpFormat(){
76
+ $update = parent::toWpFormat();
77
+
78
+ $update->id = $this->id;
79
+ $update->url = $this->homepage;
80
+ $update->tested = $this->tested;
81
+ $update->plugin = $this->filename;
82
+
83
+ if ( !empty($this->upgrade_notice) ){
84
+ $update->upgrade_notice = $this->upgrade_notice;
85
+ }
86
+
87
+ return $update;
88
+ }
89
+ }
90
+
91
+ endif;
admin/update-checker/Puc/v4p2/Plugin/UpdateChecker.php ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Plugin_UpdateChecker', false) ):
3
+
4
+ /**
5
+ * A custom plugin update checker.
6
+ *
7
+ * @author Janis Elsts
8
+ * @copyright 2016
9
+ * @access public
10
+ */
11
+ class Puc_v4p2_Plugin_UpdateChecker extends Puc_v4p2_UpdateChecker {
12
+ protected $updateTransient = 'update_plugins';
13
+ protected $translationType = 'plugin';
14
+
15
+ public $pluginAbsolutePath = ''; //Full path of the main plugin file.
16
+ public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
17
+ public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
18
+
19
+ private $cachedInstalledVersion = null;
20
+
21
+ /**
22
+ * Class constructor.
23
+ *
24
+ * @param string $metadataUrl The URL of the plugin's metadata file.
25
+ * @param string $pluginFile Fully qualified path to the main plugin file.
26
+ * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
27
+ * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
28
+ * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
29
+ * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
30
+ */
31
+ public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
32
+ $this->pluginAbsolutePath = $pluginFile;
33
+ $this->pluginFile = plugin_basename($this->pluginAbsolutePath);
34
+ $this->muPluginFile = $muPluginFile;
35
+
36
+ //If no slug is specified, use the name of the main plugin file as the slug.
37
+ //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
38
+ if ( empty($slug) ){
39
+ $slug = basename($this->pluginFile, '.php');
40
+ }
41
+
42
+ //Plugin slugs must be unique.
43
+ $slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug;
44
+ $slugUsedBy = apply_filters($slugCheckFilter, false);
45
+ if ( $slugUsedBy ) {
46
+ $this->triggerError(sprintf(
47
+ 'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
48
+ htmlentities($this->slug),
49
+ htmlentities($slugUsedBy)
50
+ ), E_USER_ERROR);
51
+ }
52
+ add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
53
+
54
+ //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
55
+ //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
56
+ if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
57
+ $this->muPluginFile = $this->pluginFile;
58
+ }
59
+
60
+ parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
61
+ }
62
+
63
+ /**
64
+ * Create an instance of the scheduler.
65
+ *
66
+ * @param int $checkPeriod
67
+ * @return Puc_v4p2_Scheduler
68
+ */
69
+ protected function createScheduler($checkPeriod) {
70
+ $scheduler = new Puc_v4p2_Scheduler($this, $checkPeriod, array('load-plugins.php'));
71
+ register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron'));
72
+ return $scheduler;
73
+ }
74
+
75
+ /**
76
+ * Install the hooks required to run periodic update checks and inject update info
77
+ * into WP data structures.
78
+ *
79
+ * @return void
80
+ */
81
+ protected function installHooks(){
82
+ //Override requests for plugin information
83
+ add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
84
+
85
+ add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
86
+ add_action('admin_init', array($this, 'handleManualCheck'));
87
+ add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
88
+
89
+ //Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
90
+ add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
91
+ add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
92
+
93
+ parent::installHooks();
94
+ }
95
+
96
+ /**
97
+ * Retrieve plugin info from the configured API endpoint.
98
+ *
99
+ * @uses wp_remote_get()
100
+ *
101
+ * @param array $queryArgs Additional query arguments to append to the request. Optional.
102
+ * @return Puc_v4p2_Plugin_Info
103
+ */
104
+ public function requestInfo($queryArgs = array()) {
105
+ list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p2_Plugin_Info', 'request_info', $queryArgs);
106
+
107
+ if ( $pluginInfo !== null ) {
108
+ /** @var Puc_v4p2_Plugin_Info $pluginInfo */
109
+ $pluginInfo->filename = $this->pluginFile;
110
+ $pluginInfo->slug = $this->slug;
111
+ }
112
+
113
+ $pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result);
114
+ return $pluginInfo;
115
+ }
116
+
117
+ /**
118
+ * Retrieve the latest update (if any) from the configured API endpoint.
119
+ *
120
+ * @uses PluginUpdateChecker::requestInfo()
121
+ *
122
+ * @return Puc_v4p2_Update|null An instance of Plugin_Update, or NULL when no updates are available.
123
+ */
124
+ public function requestUpdate() {
125
+ //For the sake of simplicity, this function just calls requestInfo()
126
+ //and transforms the result accordingly.
127
+ $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
128
+ if ( $pluginInfo === null ){
129
+ return null;
130
+ }
131
+ $update = Puc_v4p2_Plugin_Update::fromPluginInfo($pluginInfo);
132
+
133
+ $update = $this->filterUpdateResult($update);
134
+
135
+ return $update;
136
+ }
137
+
138
+ /**
139
+ * Get the currently installed version of the plugin.
140
+ *
141
+ * @return string Version number.
142
+ */
143
+ public function getInstalledVersion(){
144
+ if ( isset($this->cachedInstalledVersion) ) {
145
+ return $this->cachedInstalledVersion;
146
+ }
147
+
148
+ $pluginHeader = $this->getPluginHeader();
149
+ if ( isset($pluginHeader['Version']) ) {
150
+ $this->cachedInstalledVersion = $pluginHeader['Version'];
151
+ return $pluginHeader['Version'];
152
+ } else {
153
+ //This can happen if the filename points to something that is not a plugin.
154
+ $this->triggerError(
155
+ sprintf(
156
+ "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
157
+ $this->pluginFile
158
+ ),
159
+ E_USER_WARNING
160
+ );
161
+ return null;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Get plugin's metadata from its file header.
167
+ *
168
+ * @return array
169
+ */
170
+ protected function getPluginHeader() {
171
+ if ( !is_file($this->pluginAbsolutePath) ) {
172
+ //This can happen if the plugin filename is wrong.
173
+ $this->triggerError(
174
+ sprintf(
175
+ "Can't to read the plugin header for '%s'. The file does not exist.",
176
+ $this->pluginFile
177
+ ),
178
+ E_USER_WARNING
179
+ );
180
+ return array();
181
+ }
182
+
183
+ if ( !function_exists('get_plugin_data') ){
184
+ /** @noinspection PhpIncludeInspection */
185
+ require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
186
+ }
187
+ return get_plugin_data($this->pluginAbsolutePath, false, false);
188
+ }
189
+
190
+ /**
191
+ * @return array
192
+ */
193
+ protected function getHeaderNames() {
194
+ return array(
195
+ 'Name' => 'Plugin Name',
196
+ 'PluginURI' => 'Plugin URI',
197
+ 'Version' => 'Version',
198
+ 'Description' => 'Description',
199
+ 'Author' => 'Author',
200
+ 'AuthorURI' => 'Author URI',
201
+ 'TextDomain' => 'Text Domain',
202
+ 'DomainPath' => 'Domain Path',
203
+ 'Network' => 'Network',
204
+
205
+ //The newest WordPress version that this plugin requires or has been tested with.
206
+ //We support several different formats for compatibility with other libraries.
207
+ 'Tested WP' => 'Tested WP',
208
+ 'Requires WP' => 'Requires WP',
209
+ 'Tested up to' => 'Tested up to',
210
+ 'Requires at least' => 'Requires at least',
211
+ );
212
+ }
213
+
214
+
215
+ /**
216
+ * Intercept plugins_api() calls that request information about our plugin and
217
+ * use the configured API endpoint to satisfy them.
218
+ *
219
+ * @see plugins_api()
220
+ *
221
+ * @param mixed $result
222
+ * @param string $action
223
+ * @param array|object $args
224
+ * @return mixed
225
+ */
226
+ public function injectInfo($result, $action = null, $args = null){
227
+ $relevant = ($action == 'plugin_information') && isset($args->slug) && (
228
+ ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
229
+ );
230
+ if ( !$relevant ) {
231
+ return $result;
232
+ }
233
+
234
+ $pluginInfo = $this->requestInfo();
235
+ $pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo);
236
+ if ( $pluginInfo ) {
237
+ return $pluginInfo->toWpFormat();
238
+ }
239
+
240
+ return $result;
241
+ }
242
+
243
+ protected function shouldShowUpdates() {
244
+ //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
245
+ //is usually different from the main plugin file so the update wouldn't show up properly anyway.
246
+ return !$this->isUnknownMuPlugin();
247
+ }
248
+
249
+ /**
250
+ * @param stdClass|null $updates
251
+ * @param stdClass $updateToAdd
252
+ * @return stdClass
253
+ */
254
+ protected function addUpdateToList($updates, $updateToAdd) {
255
+ if ( $this->isMuPlugin() ) {
256
+ //WP does not support automatic update installation for mu-plugins, but we can
257
+ //still display a notice.
258
+ $updateToAdd->package = null;
259
+ }
260
+ return parent::addUpdateToList($updates, $updateToAdd);
261
+ }
262
+
263
+ /**
264
+ * @param stdClass|null $updates
265
+ * @return stdClass|null
266
+ */
267
+ protected function removeUpdateFromList($updates) {
268
+ $updates = parent::removeUpdateFromList($updates);
269
+ if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) {
270
+ unset($updates->response[$this->muPluginFile]);
271
+ }
272
+ return $updates;
273
+ }
274
+
275
+ /**
276
+ * For plugins, the update array is indexed by the plugin filename relative to the "plugins"
277
+ * directory. Example: "plugin-name/plugin.php".
278
+ *
279
+ * @return string
280
+ */
281
+ protected function getUpdateListKey() {
282
+ if ( $this->isMuPlugin() ) {
283
+ return $this->muPluginFile;
284
+ }
285
+ return $this->pluginFile;
286
+ }
287
+
288
+ /**
289
+ * Alias for isBeingUpgraded().
290
+ *
291
+ * @deprecated
292
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
293
+ * @return bool
294
+ */
295
+ public function isPluginBeingUpgraded($upgrader = null) {
296
+ return $this->isBeingUpgraded($upgrader);
297
+ }
298
+
299
+ /**
300
+ * Is there an update being installed for this plugin, right now?
301
+ *
302
+ * @param WP_Upgrader|null $upgrader
303
+ * @return bool
304
+ */
305
+ public function isBeingUpgraded($upgrader = null) {
306
+ return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
307
+ }
308
+
309
+ /**
310
+ * Get the details of the currently available update, if any.
311
+ *
312
+ * If no updates are available, or if the last known update version is below or equal
313
+ * to the currently installed version, this method will return NULL.
314
+ *
315
+ * Uses cached update data. To retrieve update information straight from
316
+ * the metadata URL, call requestUpdate() instead.
317
+ *
318
+ * @return Puc_v4p2_Plugin_Update|null
319
+ */
320
+ public function getUpdate() {
321
+ $update = parent::getUpdate();
322
+ if ( isset($update) ) {
323
+ /** @var Puc_v4p2_Plugin_Update $update */
324
+ $update->filename = $this->pluginFile;
325
+ }
326
+ return $update;
327
+ }
328
+
329
+ /**
330
+ * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
331
+ * the new link will appear after the "Visit plugin site" link.
332
+ *
333
+ * You can change the link text by using the "puc_manual_check_link-$slug" filter.
334
+ * Returning an empty string from the filter will disable the link.
335
+ *
336
+ * @param array $pluginMeta Array of meta links.
337
+ * @param string $pluginFile
338
+ * @return array
339
+ */
340
+ public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
341
+ $isRelevant = ($pluginFile == $this->pluginFile)
342
+ || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
343
+
344
+ if ( $isRelevant && $this->userCanInstallUpdates() ) {
345
+ $linkUrl = wp_nonce_url(
346
+ add_query_arg(
347
+ array(
348
+ 'puc_check_for_updates' => 1,
349
+ 'puc_slug' => $this->slug,
350
+ ),
351
+ self_admin_url('plugins.php')
352
+ ),
353
+ 'puc_check_for_updates'
354
+ );
355
+
356
+ $linkText = apply_filters(
357
+ $this->getUniqueName('manual_check_link'),
358
+ __('Check for updates', 'plugin-update-checker')
359
+ );
360
+ if ( !empty($linkText) ) {
361
+ /** @noinspection HtmlUnknownTarget */
362
+ $pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
363
+ }
364
+ }
365
+ return $pluginMeta;
366
+ }
367
+
368
+ /**
369
+ * Check for updates when the user clicks the "Check for updates" link.
370
+ * @see self::addCheckForUpdatesLink()
371
+ *
372
+ * @return void
373
+ */
374
+ public function handleManualCheck() {
375
+ $shouldCheck =
376
+ isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
377
+ && $_GET['puc_slug'] == $this->slug
378
+ && $this->userCanInstallUpdates()
379
+ && check_admin_referer('puc_check_for_updates');
380
+
381
+ if ( $shouldCheck ) {
382
+ $update = $this->checkForUpdates();
383
+ $status = ($update === null) ? 'no_update' : 'update_available';
384
+ wp_redirect(add_query_arg(
385
+ array(
386
+ 'puc_update_check_result' => $status,
387
+ 'puc_slug' => $this->slug,
388
+ ),
389
+ self_admin_url('plugins.php')
390
+ ));
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Display the results of a manual update check.
396
+ * @see self::handleManualCheck()
397
+ *
398
+ * You can change the result message by using the "puc_manual_check_message-$slug" filter.
399
+ */
400
+ public function displayManualCheckResult() {
401
+ if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
402
+ $status = strval($_GET['puc_update_check_result']);
403
+ $title = $this->getPluginTitle();
404
+ if ( $status == 'no_update' ) {
405
+ $message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title);
406
+ } else if ( $status == 'update_available' ) {
407
+ $message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title);
408
+ } else {
409
+ $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
410
+ }
411
+ printf(
412
+ '<div class="updated notice is-dismissible"><p>%s</p></div>',
413
+ apply_filters($this->getUniqueName('manual_check_message'), $message, $status)
414
+ );
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Get the translated plugin title.
420
+ *
421
+ * @return string
422
+ */
423
+ protected function getPluginTitle() {
424
+ $title = '';
425
+ $header = $this->getPluginHeader();
426
+ if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) {
427
+ $title = translate($header['Name'], $header['TextDomain']);
428
+ }
429
+ return $title;
430
+ }
431
+
432
+ /**
433
+ * Check if the current user has the required permissions to install updates.
434
+ *
435
+ * @return bool
436
+ */
437
+ public function userCanInstallUpdates() {
438
+ return current_user_can('update_plugins');
439
+ }
440
+
441
+ /**
442
+ * Check if the plugin file is inside the mu-plugins directory.
443
+ *
444
+ * @return bool
445
+ */
446
+ protected function isMuPlugin() {
447
+ static $cachedResult = null;
448
+
449
+ if ( $cachedResult === null ) {
450
+ //Convert both paths to the canonical form before comparison.
451
+ $muPluginDir = realpath(WPMU_PLUGIN_DIR);
452
+ $pluginPath = realpath($this->pluginAbsolutePath);
453
+
454
+ $cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
455
+ }
456
+
457
+ return $cachedResult;
458
+ }
459
+
460
+ /**
461
+ * MU plugins are partially supported, but only when we know which file in mu-plugins
462
+ * corresponds to this plugin.
463
+ *
464
+ * @return bool
465
+ */
466
+ protected function isUnknownMuPlugin() {
467
+ return empty($this->muPluginFile) && $this->isMuPlugin();
468
+ }
469
+
470
+ /**
471
+ * Clear the cached plugin version. This method can be set up as a filter (hook) and will
472
+ * return the filter argument unmodified.
473
+ *
474
+ * @param mixed $filterArgument
475
+ * @return mixed
476
+ */
477
+ public function clearCachedVersion($filterArgument = null) {
478
+ $this->cachedInstalledVersion = null;
479
+ return $filterArgument;
480
+ }
481
+
482
+ /**
483
+ * Get absolute path to the main plugin file.
484
+ *
485
+ * @return string
486
+ */
487
+ public function getAbsolutePath() {
488
+ return $this->pluginAbsolutePath;
489
+ }
490
+
491
+ /**
492
+ * Register a callback for filtering query arguments.
493
+ *
494
+ * The callback function should take one argument - an associative array of query arguments.
495
+ * It should return a modified array of query arguments.
496
+ *
497
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
498
+ *
499
+ * @param callable $callback
500
+ * @return void
501
+ */
502
+ public function addQueryArgFilter($callback){
503
+ $this->addFilter('request_info_query_args', $callback);
504
+ }
505
+
506
+ /**
507
+ * Register a callback for filtering arguments passed to wp_remote_get().
508
+ *
509
+ * The callback function should take one argument - an associative array of arguments -
510
+ * and return a modified array or arguments. See the WP documentation on wp_remote_get()
511
+ * for details on what arguments are available and how they work.
512
+ *
513
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
514
+ *
515
+ * @param callable $callback
516
+ * @return void
517
+ */
518
+ public function addHttpRequestArgFilter($callback) {
519
+ $this->addFilter('request_info_options', $callback);
520
+ }
521
+
522
+ /**
523
+ * Register a callback for filtering the plugin info retrieved from the external API.
524
+ *
525
+ * The callback function should take two arguments. If the plugin info was retrieved
526
+ * successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
527
+ * it will be NULL. The second argument will be the corresponding return value of
528
+ * wp_remote_get (see WP docs for details).
529
+ *
530
+ * The callback function should return a new or modified instance of PluginInfo or NULL.
531
+ *
532
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
533
+ *
534
+ * @param callable $callback
535
+ * @return void
536
+ */
537
+ public function addResultFilter($callback) {
538
+ $this->addFilter('request_info_result', $callback, 10, 2);
539
+ }
540
+
541
+ protected function createDebugBarExtension() {
542
+ return new Puc_v4p2_DebugBar_PluginExtension($this);
543
+ }
544
+ }
545
+
546
+ endif;
admin/update-checker/Puc/v4p2/Scheduler.php ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Scheduler', false) ):
3
+
4
+ /**
5
+ * The scheduler decides when and how often to check for updates.
6
+ * It calls @see Puc_v4p2_UpdateChecker::checkForUpdates() to perform the actual checks.
7
+ */
8
+ class Puc_v4p2_Scheduler {
9
+ public $checkPeriod = 12; //How often to check for updates (in hours).
10
+ public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
11
+ public $throttledCheckPeriod = 72;
12
+
13
+ protected $hourlyCheckHooks = array('load-update.php');
14
+
15
+ /**
16
+ * @var Puc_v4p2_UpdateChecker
17
+ */
18
+ protected $updateChecker;
19
+
20
+ private $cronHook = null;
21
+
22
+ /**
23
+ * Scheduler constructor.
24
+ *
25
+ * @param Puc_v4p2_UpdateChecker $updateChecker
26
+ * @param int $checkPeriod How often to check for updates (in hours).
27
+ * @param array $hourlyHooks
28
+ */
29
+ public function __construct($updateChecker, $checkPeriod, $hourlyHooks = array('load-plugins.php')) {
30
+ $this->updateChecker = $updateChecker;
31
+ $this->checkPeriod = $checkPeriod;
32
+
33
+ //Set up the periodic update checks
34
+ $this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates');
35
+ if ( $this->checkPeriod > 0 ){
36
+
37
+ //Trigger the check via Cron.
38
+ //Try to use one of the default schedules if possible as it's less likely to conflict
39
+ //with other plugins and their custom schedules.
40
+ $defaultSchedules = array(
41
+ 1 => 'hourly',
42
+ 12 => 'twicedaily',
43
+ 24 => 'daily',
44
+ );
45
+ if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
46
+ $scheduleName = $defaultSchedules[$this->checkPeriod];
47
+ } else {
48
+ //Use a custom cron schedule.
49
+ $scheduleName = 'every' . $this->checkPeriod . 'hours';
50
+ add_filter('cron_schedules', array($this, '_addCustomSchedule'));
51
+ }
52
+
53
+ if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
54
+ wp_schedule_event(time(), $scheduleName, $this->cronHook);
55
+ }
56
+ add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
57
+
58
+ //In case Cron is disabled or unreliable, we also manually trigger
59
+ //the periodic checks while the user is browsing the Dashboard.
60
+ add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
61
+
62
+ //Like WordPress itself, we check more often on certain pages.
63
+ /** @see wp_update_plugins */
64
+ add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
65
+ //"load-update.php" and "load-plugins.php" or "load-themes.php".
66
+ $this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
67
+ foreach($this->hourlyCheckHooks as $hook) {
68
+ add_action($hook, array($this, 'maybeCheckForUpdates'));
69
+ }
70
+ //This hook fires after a bulk update is complete.
71
+ add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);
72
+
73
+ } else {
74
+ //Periodic checks are disabled.
75
+ wp_clear_scheduled_hook($this->cronHook);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Check for updates if the configured check interval has already elapsed.
81
+ * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
82
+ *
83
+ * You can override the default behaviour by using the "puc_check_now-$slug" filter.
84
+ * The filter callback will be passed three parameters:
85
+ * - Current decision. TRUE = check updates now, FALSE = don't check now.
86
+ * - Last check time as a Unix timestamp.
87
+ * - Configured check period in hours.
88
+ * Return TRUE to check for updates immediately, or FALSE to cancel.
89
+ *
90
+ * This method is declared public because it's a hook callback. Calling it directly is not recommended.
91
+ */
92
+ public function maybeCheckForUpdates(){
93
+ if ( empty($this->checkPeriod) ){
94
+ return;
95
+ }
96
+
97
+ $state = $this->updateChecker->getUpdateState();
98
+ $shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
99
+
100
+ //Let plugin authors substitute their own algorithm.
101
+ $shouldCheck = apply_filters(
102
+ $this->updateChecker->getUniqueName('check_now'),
103
+ $shouldCheck,
104
+ $state->getLastCheck(),
105
+ $this->checkPeriod
106
+ );
107
+
108
+ if ( $shouldCheck ) {
109
+ $this->updateChecker->checkForUpdates();
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Calculate the actual check period based on the current status and environment.
115
+ *
116
+ * @return int Check period in seconds.
117
+ */
118
+ protected function getEffectiveCheckPeriod() {
119
+ $currentFilter = current_filter();
120
+ if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
121
+ //Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
122
+ $period = 60;
123
+ } else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
124
+ //Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
125
+ $period = 3600;
126
+ } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
127
+ //Check less frequently if it's already known that an update is available.
128
+ $period = $this->throttledCheckPeriod * 3600;
129
+ } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
130
+ //WordPress cron schedules are not exact, so lets do an update check even
131
+ //if slightly less than $checkPeriod hours have elapsed since the last check.
132
+ $cronFuzziness = 20 * 60;
133
+ $period = $this->checkPeriod * 3600 - $cronFuzziness;
134
+ } else {
135
+ $period = $this->checkPeriod * 3600;
136
+ }
137
+
138
+ return $period;
139
+ }
140
+
141
+ /**
142
+ * Add our custom schedule to the array of Cron schedules used by WP.
143
+ *
144
+ * @param array $schedules
145
+ * @return array
146
+ */
147
+ public function _addCustomSchedule($schedules){
148
+ if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
149
+ $scheduleName = 'every' . $this->checkPeriod . 'hours';
150
+ $schedules[$scheduleName] = array(
151
+ 'interval' => $this->checkPeriod * 3600,
152
+ 'display' => sprintf('Every %d hours', $this->checkPeriod),
153
+ );
154
+ }
155
+ return $schedules;
156
+ }
157
+
158
+ /**
159
+ * Remove the scheduled cron event that the library uses to check for updates.
160
+ *
161
+ * @return void
162
+ */
163
+ public function removeUpdaterCron(){
164
+ wp_clear_scheduled_hook($this->cronHook);
165
+ }
166
+
167
+ /**
168
+ * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
169
+ *
170
+ * @return string
171
+ */
172
+ public function getCronHookName() {
173
+ return $this->cronHook;
174
+ }
175
+ }
176
+
177
+ endif;
admin/update-checker/Puc/v4p2/StateStore.php ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_StateStore', false) ):
4
+
5
+ class Puc_v4p2_StateStore {
6
+ /**
7
+ * @var int Last update check timestamp.
8
+ */
9
+ protected $lastCheck = 0;
10
+
11
+ /**
12
+ * @var string Version number.
13
+ */
14
+ protected $checkedVersion = '';
15
+
16
+ /**
17
+ * @var Puc_v4p2_Update|null Cached update.
18
+ */
19
+ protected $update = null;
20
+
21
+ /**
22
+ * @var string Site option name.
23
+ */
24
+ private $optionName = '';
25
+
26
+ /**
27
+ * @var bool Whether we've already tried to load the state from the database.
28
+ */
29
+ private $isLoaded = false;
30
+
31
+ public function __construct($optionName) {
32
+ $this->optionName = $optionName;
33
+ }
34
+
35
+ /**
36
+ * Get time elapsed since the last update check.
37
+ *
38
+ * If there are no recorded update checks, this method returns a large arbitrary number
39
+ * (i.e. time since the Unix epoch).
40
+ *
41
+ * @return int Elapsed time in seconds.
42
+ */
43
+ public function timeSinceLastCheck() {
44
+ $this->lazyLoad();
45
+ return time() - $this->lastCheck;
46
+ }
47
+
48
+ /**
49
+ * @return int
50
+ */
51
+ public function getLastCheck() {
52
+ $this->lazyLoad();
53
+ return $this->lastCheck;
54
+ }
55
+
56
+ /**
57
+ * Set the time of the last update check to the current timestamp.
58
+ *
59
+ * @return $this
60
+ */
61
+ public function setLastCheckToNow() {
62
+ $this->lazyLoad();
63
+ $this->lastCheck = time();
64
+ return $this;
65
+ }
66
+
67
+ /**
68
+ * @return null|Puc_v4p2_Update
69
+ */
70
+ public function getUpdate() {
71
+ $this->lazyLoad();
72
+ return $this->update;
73
+ }
74
+
75
+ /**
76
+ * @param Puc_v4p2_Update|null $update
77
+ * @return $this
78
+ */
79
+ public function setUpdate(Puc_v4p2_Update $update = null) {
80
+ $this->lazyLoad();
81
+ $this->update = $update;
82
+ return $this;
83
+ }
84
+
85
+ /**
86
+ * @return string
87
+ */
88
+ public function getCheckedVersion() {
89
+ $this->lazyLoad();
90
+ return $this->checkedVersion;
91
+ }
92
+
93
+ /**
94
+ * @param string $version
95
+ * @return $this
96
+ */
97
+ public function setCheckedVersion($version) {
98
+ $this->lazyLoad();
99
+ $this->checkedVersion = strval($version);
100
+ return $this;
101
+ }
102
+
103
+ /**
104
+ * Get translation updates.
105
+ *
106
+ * @return array
107
+ */
108
+ public function getTranslations() {
109
+ $this->lazyLoad();
110
+ if ( isset($this->update, $this->update->translations) ) {
111
+ return $this->update->translations;
112
+ }
113
+ return array();
114
+ }
115
+
116
+ /**
117
+ * Set translation updates.
118
+ *
119
+ * @param array $translationUpdates
120
+ */
121
+ public function setTranslations($translationUpdates) {
122
+ $this->lazyLoad();
123
+ if ( isset($this->update) ) {
124
+ $this->update->translations = $translationUpdates;
125
+ $this->save();
126
+ }
127
+ }
128
+
129
+ public function save() {
130
+ $state = new stdClass();
131
+
132
+ $state->lastCheck = $this->lastCheck;
133
+ $state->checkedVersion = $this->checkedVersion;
134
+
135
+ if ( isset($this->update)) {
136
+ $state->update = $this->update->toStdClass();
137
+
138
+ $updateClass = get_class($this->update);
139
+ $state->updateClass = $updateClass;
140
+ $prefix = $this->getLibPrefix();
141
+ if ( Puc_v4p2_Utils::startsWith($updateClass, $prefix) ) {
142
+ $state->updateBaseClass = substr($updateClass, strlen($prefix));
143
+ }
144
+ }
145
+
146
+ update_site_option($this->optionName, $state);
147
+ $this->isLoaded = true;
148
+ }
149
+
150
+ /**
151
+ * @return $this
152
+ */
153
+ public function lazyLoad() {
154
+ if ( !$this->isLoaded ) {
155
+ $this->load();
156
+ }
157
+ return $this;
158
+ }
159
+
160
+ protected function load() {
161
+ $this->isLoaded = true;
162
+
163
+ $state = get_site_option($this->optionName, null);
164
+
165
+ if ( !is_object($state) ) {
166
+ $this->lastCheck = 0;
167
+ $this->checkedVersion = '';
168
+ $this->update = null;
169
+ return;
170
+ }
171
+
172
+ $this->lastCheck = intval(Puc_v4p2_Utils::get($state, 'lastCheck', 0));
173
+ $this->checkedVersion = Puc_v4p2_Utils::get($state, 'checkedVersion', '');
174
+ $this->update = null;
175
+
176
+ if ( isset($state->update) ) {
177
+ //This mess is due to the fact that the want the update class from this version
178
+ //of the library, not the version that saved the update.
179
+
180
+ $updateClass = null;
181
+ if ( isset($state->updateBaseClass) ) {
182
+ $updateClass = $this->getLibPrefix() . $state->updateBaseClass;
183
+ } else if ( isset($state->updateClass) && class_exists($state->updateClass) ) {
184
+ $updateClass = $state->updateClass;
185
+ }
186
+
187
+ if ( $updateClass !== null ) {
188
+ $this->update = call_user_func(array($updateClass, 'fromObject'), $state->update);
189
+ }
190
+ }
191
+ }
192
+
193
+ public function delete() {
194
+ delete_site_option($this->optionName);
195
+
196
+ $this->lastCheck = 0;
197
+ $this->checkedVersion = '';
198
+ $this->update = null;
199
+ }
200
+
201
+ private function getLibPrefix() {
202
+ $parts = explode('_', __CLASS__, 3);
203
+ return $parts[0] . '_' . $parts[1] . '_';
204
+ }
205
+ }
206
+
207
+ endif;
admin/update-checker/Puc/v4p2/Theme/Update.php ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Theme_Update', false) ):
4
+
5
+ class Puc_v4p2_Theme_Update extends Puc_v4p2_Update {
6
+ public $details_url = '';
7
+
8
+ protected static $extraFields = array('details_url');
9
+
10
+ /**
11
+ * Transform the metadata into the format used by WordPress core.
12
+ * Note the inconsistency: WP stores plugin updates as objects and theme updates as arrays.
13
+ *
14
+ * @return array
15
+ */
16
+ public function toWpFormat() {
17
+ $update = array(
18
+ 'theme' => $this->slug,
19
+ 'new_version' => $this->version,
20
+ 'url' => $this->details_url,
21
+ );
22
+
23
+ if ( !empty($this->download_url) ) {
24
+ $update['package'] = $this->download_url;
25
+ }
26
+
27
+ return $update;
28
+ }
29
+
30
+ /**
31
+ * Create a new instance of Theme_Update from its JSON-encoded representation.
32
+ *
33
+ * @param string $json Valid JSON string representing a theme information object.
34
+ * @return self New instance of ThemeUpdate, or NULL on error.
35
+ */
36
+ public static function fromJson($json) {
37
+ $instance = new self();
38
+ if ( !parent::createFromJson($json, $instance) ) {
39
+ return null;
40
+ }
41
+ return $instance;
42
+ }
43
+
44
+ /**
45
+ * Create a new instance by copying the necessary fields from another object.
46
+ *
47
+ * @param StdClass|Puc_v4p2_Theme_Update $object The source object.
48
+ * @return Puc_v4p2_Theme_Update The new copy.
49
+ */
50
+ public static function fromObject($object) {
51
+ $update = new self();
52
+ $update->copyFields($object, $update);
53
+ return $update;
54
+ }
55
+
56
+ /**
57
+ * Basic validation.
58
+ *
59
+ * @param StdClass $apiResponse
60
+ * @return bool|WP_Error
61
+ */
62
+ protected function validateMetadata($apiResponse) {
63
+ $required = array('version', 'details_url');
64
+ foreach($required as $key) {
65
+ if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) {
66
+ return new WP_Error(
67
+ 'tuc-invalid-metadata',
68
+ sprintf('The theme metadata is missing the required "%s" key.', $key)
69
+ );
70
+ }
71
+ }
72
+ return true;
73
+ }
74
+
75
+ protected function getFieldNames() {
76
+ return array_merge(parent::getFieldNames(), self::$extraFields);
77
+ }
78
+
79
+ protected function getPrefixedFilter($tag) {
80
+ return parent::getPrefixedFilter($tag) . '_theme';
81
+ }
82
+ }
83
+
84
+ endif;
admin/update-checker/Puc/v4p2/Theme/UpdateChecker.php ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Theme_UpdateChecker', false) ):
4
+
5
+ class Puc_v4p2_Theme_UpdateChecker extends Puc_v4p2_UpdateChecker {
6
+ protected $filterSuffix = 'theme';
7
+ protected $updateTransient = 'update_themes';
8
+ protected $translationType = 'theme';
9
+
10
+ /**
11
+ * @var string Theme directory name.
12
+ */
13
+ protected $stylesheet;
14
+
15
+ /**
16
+ * @var WP_Theme Theme object.
17
+ */
18
+ protected $theme;
19
+
20
+ public function __construct($metadataUrl, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
21
+ if ( $stylesheet === null ) {
22
+ $stylesheet = get_stylesheet();
23
+ }
24
+ $this->stylesheet = $stylesheet;
25
+ $this->theme = wp_get_theme($this->stylesheet);
26
+
27
+ parent::__construct(
28
+ $metadataUrl,
29
+ $stylesheet,
30
+ $customSlug ? $customSlug : $stylesheet,
31
+ $checkPeriod,
32
+ $optionName
33
+ );
34
+ }
35
+
36
+ /**
37
+ * For themes, the update array is indexed by theme directory name.
38
+ *
39
+ * @return string
40
+ */
41
+ protected function getUpdateListKey() {
42
+ return $this->directoryName;
43
+ }
44
+
45
+ /**
46
+ * Retrieve the latest update (if any) from the configured API endpoint.
47
+ *
48
+ * @return Puc_v4p2_Update|null An instance of Update, or NULL when no updates are available.
49
+ */
50
+ public function requestUpdate() {
51
+ list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p2_Theme_Update', 'request_update');
52
+
53
+ if ( $themeUpdate !== null ) {
54
+ /** @var Puc_v4p2_Theme_Update $themeUpdate */
55
+ $themeUpdate->slug = $this->slug;
56
+ }
57
+
58
+ $themeUpdate = $this->filterUpdateResult($themeUpdate, $result);
59
+ return $themeUpdate;
60
+ }
61
+
62
+ public function userCanInstallUpdates() {
63
+ return current_user_can('update_themes');
64
+ }
65
+
66
+ /**
67
+ * Get the currently installed version of the plugin or theme.
68
+ *
69
+ * @return string Version number.
70
+ */
71
+ public function getInstalledVersion() {
72
+ return $this->theme->get('Version');
73
+ }
74
+
75
+ /**
76
+ * Create an instance of the scheduler.
77
+ *
78
+ * @param int $checkPeriod
79
+ * @return Puc_v4p2_Scheduler
80
+ */
81
+ protected function createScheduler($checkPeriod) {
82
+ return new Puc_v4p2_Scheduler($this, $checkPeriod, array('load-themes.php'));
83
+ }
84
+
85
+ /**
86
+ * Is there an update being installed right now for this theme?
87
+ *
88
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
89
+ * @return bool
90
+ */
91
+ public function isBeingUpgraded($upgrader = null) {
92
+ return $this->upgraderStatus->isThemeBeingUpgraded($this->stylesheet, $upgrader);
93
+ }
94
+
95
+ protected function createDebugBarExtension() {
96
+ return new Puc_v4p2_DebugBar_Extension($this, 'Puc_v4p2_DebugBar_ThemePanel');
97
+ }
98
+
99
+ /**
100
+ * Register a callback for filtering query arguments.
101
+ *
102
+ * The callback function should take one argument - an associative array of query arguments.
103
+ * It should return a modified array of query arguments.
104
+ *
105
+ * @param callable $callback
106
+ * @return void
107
+ */
108
+ public function addQueryArgFilter($callback){
109
+ $this->addFilter('request_update_query_args', $callback);
110
+ }
111
+
112
+ /**
113
+ * Register a callback for filtering arguments passed to wp_remote_get().
114
+ *
115
+ * The callback function should take one argument - an associative array of arguments -
116
+ * and return a modified array or arguments. See the WP documentation on wp_remote_get()
117
+ * for details on what arguments are available and how they work.
118
+ *
119
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
120
+ *
121
+ * @param callable $callback
122
+ * @return void
123
+ */
124
+ public function addHttpRequestArgFilter($callback) {
125
+ $this->addFilter('request_update_options', $callback);
126
+ }
127
+
128
+ /**
129
+ * Register a callback for filtering theme updates retrieved from the external API.
130
+ *
131
+ * The callback function should take two arguments. If the theme update was retrieved
132
+ * successfully, the first argument passed will be an instance of Theme_Update. Otherwise,
133
+ * it will be NULL. The second argument will be the corresponding return value of
134
+ * wp_remote_get (see WP docs for details).
135
+ *
136
+ * The callback function should return a new or modified instance of Theme_Update or NULL.
137
+ *
138
+ * @uses add_filter() This method is a convenience wrapper for add_filter().
139
+ *
140
+ * @param callable $callback
141
+ * @return void
142
+ */
143
+ public function addResultFilter($callback) {
144
+ $this->addFilter('request_update_result', $callback, 10, 2);
145
+ }
146
+
147
+ /**
148
+ * @return array
149
+ */
150
+ protected function getHeaderNames() {
151
+ return array(
152
+ 'Name' => 'Theme Name',
153
+ 'ThemeURI' => 'Theme URI',
154
+ 'Description' => 'Description',
155
+ 'Author' => 'Author',
156
+ 'AuthorURI' => 'Author URI',
157
+ 'Version' => 'Version',
158
+ 'Template' => 'Template',
159
+ 'Status' => 'Status',
160
+ 'Tags' => 'Tags',
161
+ 'TextDomain' => 'Text Domain',
162
+ 'DomainPath' => 'Domain Path',
163
+ );
164
+ }
165
+ }
166
+
167
+ endif;
admin/update-checker/Puc/v4p2/Update.php ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Update', false) ):
3
+
4
+ /**
5
+ * A simple container class for holding information about an available update.
6
+ *
7
+ * @author Janis Elsts
8
+ * @access public
9
+ */
10
+ abstract class Puc_v4p2_Update extends Puc_v4p2_Metadata {
11
+ public $slug;
12
+ public $version;
13
+ public $download_url;
14
+ public $translations = array();
15
+
16
+ /**
17
+ * @return string[]
18
+ */
19
+ protected function getFieldNames() {
20
+ return array('slug', 'version', 'download_url', 'translations');
21
+ }
22
+
23
+ public function toWpFormat() {
24
+ $update = new stdClass();
25
+
26
+ $update->slug = $this->slug;
27
+ $update->new_version = $this->version;
28
+ $update->package = $this->download_url;
29
+
30
+ return $update;
31
+ }
32
+ }
33
+
34
+ endif;
admin/update-checker/Puc/v4p2/UpdateChecker.php ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_UpdateChecker', false) ):
4
+
5
+ abstract class Puc_v4p2_UpdateChecker {
6
+ protected $filterSuffix = '';
7
+ protected $updateTransient = '';
8
+ protected $translationType = ''; //"plugin" or "theme".
9
+
10
+ /**
11
+ * Set to TRUE to enable error reporting. Errors are raised using trigger_error()
12
+ * and should be logged to the standard PHP error log.
13
+ * @var bool
14
+ */
15
+ public $debugMode = false;
16
+
17
+ /**
18
+ * @var string Where to store the update info.
19
+ */
20
+ public $optionName = '';
21
+
22
+ /**
23
+ * @var string The URL of the metadata file.
24
+ */
25
+ public $metadataUrl = '';
26
+
27
+ /**
28
+ * @var string Plugin or theme directory name.
29
+ */
30
+ public $directoryName = '';
31
+
32
+ /**
33
+ * @var string The slug that will be used in update checker hooks and remote API requests.
34
+ * Usually matches the directory name unless the plugin/theme directory has been renamed.
35
+ */
36
+ public $slug = '';
37
+
38
+ /**
39
+ * @var Puc_v4p2_Scheduler
40
+ */
41
+ public $scheduler;
42
+
43
+ /**
44
+ * @var Puc_v4p2_UpgraderStatus
45
+ */
46
+ protected $upgraderStatus;
47
+
48
+ /**
49
+ * @var Puc_v4p2_StateStore
50
+ */
51
+ protected $updateState;
52
+
53
+ public function __construct($metadataUrl, $directoryName, $slug = null, $checkPeriod = 12, $optionName = '') {
54
+ $this->debugMode = (bool)(constant('WP_DEBUG'));
55
+ $this->metadataUrl = $metadataUrl;
56
+ $this->directoryName = $directoryName;
57
+ $this->slug = !empty($slug) ? $slug : $this->directoryName;
58
+
59
+ $this->optionName = $optionName;
60
+ if ( empty($this->optionName) ) {
61
+ //BC: Initially the library only supported plugin updates and didn't use type prefixes
62
+ //in the option name. Lets use the same prefix-less name when possible.
63
+ if ( $this->filterSuffix === '' ) {
64
+ $this->optionName = 'external_updates-' . $this->slug;
65
+ } else {
66
+ $this->optionName = $this->getUniqueName('external_updates');
67
+ }
68
+ }
69
+
70
+ $this->scheduler = $this->createScheduler($checkPeriod);
71
+ $this->upgraderStatus = new Puc_v4p2_UpgraderStatus();
72
+ $this->updateState = new Puc_v4p2_StateStore($this->optionName);
73
+
74
+ if ( did_action('init') ) {
75
+ $this->loadTextDomain();
76
+ } else {
77
+ add_action('init', array($this, 'loadTextDomain'));
78
+ }
79
+
80
+ $this->installHooks();
81
+ }
82
+
83
+ /**
84
+ * @internal
85
+ */
86
+ public function loadTextDomain() {
87
+ //We're not using load_plugin_textdomain() or its siblings because figuring out where
88
+ //the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy.
89
+ $domain = 'plugin-update-checker';
90
+ $locale = apply_filters(
91
+ 'plugin_locale',
92
+ (is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(),
93
+ $domain
94
+ );
95
+
96
+ $moFile = $domain . '-' . $locale . '.mo';
97
+ $path = realpath(dirname(__FILE__) . '/../../languages');
98
+
99
+ if ($path && file_exists($path)) {
100
+ load_textdomain($domain, $path . '/' . $moFile);
101
+ }
102
+ }
103
+
104
+ protected function installHooks() {
105
+ //Insert our update info into the update array maintained by WP.
106
+ add_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
107
+
108
+ //Insert translation updates into the update list.
109
+ add_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
110
+
111
+ //Clear translation updates when WP clears the update cache.
112
+ //This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
113
+ //it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
114
+ add_action(
115
+ 'delete_site_transient_' . $this->updateTransient,
116
+ array($this, 'clearCachedTranslationUpdates')
117
+ );
118
+
119
+ //Rename the update directory to be the same as the existing directory.
120
+ if ( $this->directoryName !== '.' ) {
121
+ add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
122
+ }
123
+
124
+ //Allow HTTP requests to the metadata URL even if it's on a local host.
125
+ add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
126
+
127
+ //DebugBar integration.
128
+ if ( did_action('plugins_loaded') ) {
129
+ $this->maybeInitDebugBar();
130
+ } else {
131
+ add_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Check if the current user has the required permissions to install updates.
137
+ *
138
+ * @return bool
139
+ */
140
+ abstract public function userCanInstallUpdates();
141
+
142
+ /**
143
+ * Explicitly allow HTTP requests to the metadata URL.
144
+ *
145
+ * WordPress has a security feature where the HTTP API will reject all requests that are sent to
146
+ * another site hosted on the same server as the current site (IP match), a local host, or a local
147
+ * IP, unless the host exactly matches the current site.
148
+ *
149
+ * This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
150
+ *
151
+ * That can be a problem when you're developing your plugin and you decide to host the update information
152
+ * on the same server as your test site. Update requests will mysteriously fail.
153
+ *
154
+ * We fix that by adding an exception for the metadata host.
155
+ *
156
+ * @param bool $allow
157
+ * @param string $host
158
+ * @return bool
159
+ */
160
+ public function allowMetadataHost($allow, $host) {
161
+ static $metadataHost = 0; //Using 0 instead of NULL because parse_url can return NULL.
162
+ if ( $metadataHost === 0 ) {
163
+ $metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
164
+ }
165
+
166
+ if ( is_string($metadataHost) && (strtolower($host) === strtolower($metadataHost)) ) {
167
+ return true;
168
+ }
169
+ return $allow;
170
+ }
171
+
172
+ /**
173
+ * Create an instance of the scheduler.
174
+ *
175
+ * This is implemented as a method to make it possible for plugins to subclass the update checker
176
+ * and substitute their own scheduler.
177
+ *
178
+ * @param int $checkPeriod
179
+ * @return Puc_v4p2_Scheduler
180
+ */
181
+ abstract protected function createScheduler($checkPeriod);
182
+
183
+ /**
184
+ * Check for updates. The results are stored in the DB option specified in $optionName.
185
+ *
186
+ * @return Puc_v4p2_Update|null
187
+ */
188
+ public function checkForUpdates() {
189
+ $installedVersion = $this->getInstalledVersion();
190
+ //Fail silently if we can't find the plugin/theme or read its header.
191
+ if ( $installedVersion === null ) {
192
+ $this->triggerError(
193
+ sprintf('Skipping update check for %s - installed version unknown.', $this->slug),
194
+ E_USER_WARNING
195
+ );
196
+ return null;
197
+ }
198
+
199
+ $state = $this->updateState;
200
+ $state->setLastCheckToNow()
201
+ ->setCheckedVersion($installedVersion)
202
+ ->save(); //Save before checking in case something goes wrong
203
+
204
+ $state->setUpdate($this->requestUpdate());
205
+ $state->save();
206
+
207
+ return $this->getUpdate();
208
+ }
209
+
210
+ /**
211
+ * Load the update checker state from the DB.
212
+ *
213
+ * @return Puc_v4p2_StateStore
214
+ */
215
+ public function getUpdateState() {
216
+ return $this->updateState->lazyLoad();
217
+ }
218
+
219
+ /**
220
+ * Reset update checker state - i.e. last check time, cached update data and so on.
221
+ *
222
+ * Call this when your plugin is being uninstalled, or if you want to
223
+ * clear the update cache.
224
+ */
225
+ public function resetUpdateState() {
226
+ $this->updateState->delete();
227
+ }
228
+
229
+ /**
230
+ * Get the details of the currently available update, if any.
231
+ *
232
+ * If no updates are available, or if the last known update version is below or equal
233
+ * to the currently installed version, this method will return NULL.
234
+ *
235
+ * Uses cached update data. To retrieve update information straight from
236
+ * the metadata URL, call requestUpdate() instead.
237
+ *
238
+ * @return Puc_v4p2_Update|null
239
+ */
240
+ public function getUpdate() {
241
+ $update = $this->updateState->getUpdate();
242
+
243
+ //Is there an update available?
244
+ if ( isset($update) ) {
245
+ //Check if the update is actually newer than the currently installed version.
246
+ $installedVersion = $this->getInstalledVersion();
247
+ if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
248
+ return $update;
249
+ }
250
+ }
251
+ return null;
252
+ }
253
+
254
+ /**
255
+ * Retrieve the latest update (if any) from the configured API endpoint.
256
+ *
257
+ * Subclasses should run the update through filterUpdateResult before returning it.
258
+ *
259
+ * @return Puc_v4p2_Update An instance of Update, or NULL when no updates are available.
260
+ */
261
+ abstract public function requestUpdate();
262
+
263
+ /**
264
+ * Filter the result of a requestUpdate() call.
265
+ *
266
+ * @param Puc_v4p2_Update|null $update
267
+ * @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
268
+ * @return Puc_v4p2_Update
269
+ */
270
+ protected function filterUpdateResult($update, $httpResult = null) {
271
+ //Let plugins/themes modify the update.
272
+ $update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult);
273
+
274
+ if ( isset($update, $update->translations) ) {
275
+ //Keep only those translation updates that apply to this site.
276
+ $update->translations = $this->filterApplicableTranslations($update->translations);
277
+ }
278
+
279
+ return $update;
280
+ }
281
+
282
+ /**
283
+ * Get the currently installed version of the plugin or theme.
284
+ *
285
+ * @return string|null Version number.
286
+ */
287
+ abstract public function getInstalledVersion();
288
+
289
+ /**
290
+ * Trigger a PHP error, but only when $debugMode is enabled.
291
+ *
292
+ * @param string $message
293
+ * @param int $errorType
294
+ */
295
+ protected function triggerError($message, $errorType) {
296
+ if ($this->debugMode) {
297
+ trigger_error($message, $errorType);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Get the full name of an update checker filter, action or DB entry.
303
+ *
304
+ * This method adds the "puc_" prefix and the "-$slug" suffix to the filter name.
305
+ * For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug".
306
+ *
307
+ * @param string $baseTag
308
+ * @return string
309
+ */
310
+ public function getUniqueName($baseTag) {
311
+ $name = 'puc_' . $baseTag;
312
+ if ($this->filterSuffix !== '') {
313
+ $name .= '_' . $this->filterSuffix;
314
+ }
315
+ return $name . '-' . $this->slug;
316
+ }
317
+
318
+ /* -------------------------------------------------------------------
319
+ * PUC filters and filter utilities
320
+ * -------------------------------------------------------------------
321
+ */
322
+
323
+ /**
324
+ * Register a callback for one of the update checker filters.
325
+ *
326
+ * Identical to add_filter(), except it automatically adds the "puc_" prefix
327
+ * and the "-$slug" suffix to the filter name. For example, "request_info_result"
328
+ * becomes "puc_request_info_result-your_plugin_slug".
329
+ *
330
+ * @param string $tag
331
+ * @param callable $callback
332
+ * @param int $priority
333
+ * @param int $acceptedArgs
334
+ */
335
+ public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
336
+ add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs);
337
+ }
338
+
339
+ /* -------------------------------------------------------------------
340
+ * Inject updates
341
+ * -------------------------------------------------------------------
342
+ */
343
+
344
+ /**
345
+ * Insert the latest update (if any) into the update list maintained by WP.
346
+ *
347
+ * @param stdClass $updates Update list.
348
+ * @return stdClass Modified update list.
349
+ */
350
+ public function injectUpdate($updates) {
351
+ //Is there an update to insert?
352
+ $update = $this->getUpdate();
353
+
354
+ if ( !$this->shouldShowUpdates() ) {
355
+ $update = null;
356
+ }
357
+
358
+ if ( !empty($update) ) {
359
+ //Let plugins filter the update info before it's passed on to WordPress.
360
+ $update = apply_filters($this->getUniqueName('pre_inject_update'), $update);
361
+ $updates = $this->addUpdateToList($updates, $update->toWpFormat());
362
+ } else {
363
+ //Clean up any stale update info.
364
+ $updates = $this->removeUpdateFromList($updates);
365
+ }
366
+
367
+ return $updates;
368
+ }
369
+
370
+ /**
371
+ * @param stdClass|null $updates
372
+ * @param stdClass|array $updateToAdd
373
+ * @return stdClass
374
+ */
375
+ protected function addUpdateToList($updates, $updateToAdd) {
376
+ if ( !is_object($updates) ) {
377
+ $updates = new stdClass();
378
+ $updates->response = array();
379
+ }
380
+
381
+ $updates->response[$this->getUpdateListKey()] = $updateToAdd;
382
+ return $updates;
383
+ }
384
+
385
+ /**
386
+ * @param stdClass|null $updates
387
+ * @return stdClass|null
388
+ */
389
+ protected function removeUpdateFromList($updates) {
390
+ if ( isset($updates, $updates->response) ) {
391
+ unset($updates->response[$this->getUpdateListKey()]);
392
+ }
393
+ return $updates;
394
+ }
395
+
396
+ /**
397
+ * Get the key that will be used when adding updates to the update list that's maintained
398
+ * by the WordPress core. The list is always an associative array, but the key is different
399
+ * for plugins and themes.
400
+ *
401
+ * @return string
402
+ */
403
+ abstract protected function getUpdateListKey();
404
+
405
+ /**
406
+ * Should we show available updates?
407
+ *
408
+ * Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't
409
+ * support automatic updates installation for mu-plugins, so PUC usually won't show update
410
+ * notifications in that case. See the plugin-specific subclass for details.
411
+ *
412
+ * Note: This method only applies to updates that are displayed (or not) in the WordPress
413
+ * admin. It doesn't affect APIs like requestUpdate and getUpdate.
414
+ *
415
+ * @return bool
416
+ */
417
+ protected function shouldShowUpdates() {
418
+ return true;
419
+ }
420
+
421
+ /* -------------------------------------------------------------------
422
+ * JSON-based update API
423
+ * -------------------------------------------------------------------
424
+ */
425
+
426
+ /**
427
+ * Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl.
428
+ *
429
+ * @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
430
+ * @param string $filterRoot
431
+ * @param array $queryArgs Additional query arguments.
432
+ * @return array [Puc_v4p2_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get().
433
+ */
434
+ protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) {
435
+ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
436
+ $queryArgs = array_merge(
437
+ array(
438
+ 'installed_version' => strval($this->getInstalledVersion()),
439
+ 'php' => phpversion(),
440
+ 'locale' => get_locale(),
441
+ ),
442
+ $queryArgs
443
+ );
444
+ $queryArgs = apply_filters($this->getUniqueName($filterRoot . '_query_args'), $queryArgs);
445
+
446
+ //Various options for the wp_remote_get() call. Plugins can filter these, too.
447
+ $options = array(
448
+ 'timeout' => 10, //seconds
449
+ 'headers' => array(
450
+ 'Accept' => 'application/json',
451
+ ),
452
+ );
453
+ $options = apply_filters($this->getUniqueName($filterRoot . '_options'), $options);
454
+
455
+ //The metadata file should be at 'http://your-api.com/url/here/$slug/info.json'
456
+ $url = $this->metadataUrl;
457
+ if ( !empty($queryArgs) ){
458
+ $url = add_query_arg($queryArgs, $url);
459
+ }
460
+
461
+ $result = wp_remote_get($url, $options);
462
+
463
+ $result = apply_filters($this->getUniqueName('request_metadata_http_result'), $result, $url, $options);
464
+
465
+ //Try to parse the response
466
+ $status = $this->validateApiResponse($result);
467
+ $metadata = null;
468
+ if ( !is_wp_error($status) ){
469
+ $metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
470
+ } else {
471
+ $this->triggerError(
472
+ sprintf('The URL %s does not point to a valid metadata file. ', $url)
473
+ . $status->get_error_message(),
474
+ E_USER_WARNING
475
+ );
476
+ }
477
+
478
+ return array($metadata, $result);
479
+ }
480
+
481
+ /**
482
+ * Check if $result is a successful update API response.
483
+ *
484
+ * @param array|WP_Error $result
485
+ * @return true|WP_Error
486
+ */
487
+ protected function validateApiResponse($result) {
488
+ if ( is_wp_error($result) ) { /** @var WP_Error $result */
489
+ return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
490
+ }
491
+
492
+ if ( !isset($result['response']['code']) ) {
493
+ return new WP_Error(
494
+ 'puc_no_response_code',
495
+ 'wp_remote_get() returned an unexpected result.'
496
+ );
497
+ }
498
+
499
+ if ( $result['response']['code'] !== 200 ) {
500
+ return new WP_Error(
501
+ 'puc_unexpected_response_code',
502
+ 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
503
+ );
504
+ }
505
+
506
+ if ( empty($result['body']) ) {
507
+ return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
508
+ }
509
+
510
+ return true;
511
+ }
512
+
513
+ /* -------------------------------------------------------------------
514
+ * Language packs / Translation updates
515
+ * -------------------------------------------------------------------
516
+ */
517
+
518
+ /**
519
+ * Filter a list of translation updates and return a new list that contains only updates
520
+ * that apply to the current site.
521
+ *
522
+ * @param array $translations
523
+ * @return array
524
+ */
525
+ protected function filterApplicableTranslations($translations) {
526
+ $languages = array_flip(array_values(get_available_languages()));
527
+ $installedTranslations = $this->getInstalledTranslations();
528
+
529
+ $applicableTranslations = array();
530
+ foreach($translations as $translation) {
531
+ //Does it match one of the available core languages?
532
+ $isApplicable = array_key_exists($translation->language, $languages);
533
+ //Is it more recent than an already-installed translation?
534
+ if ( isset($installedTranslations[$translation->language]) ) {
535
+ $updateTimestamp = strtotime($translation->updated);
536
+ $installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
537
+ $isApplicable = $updateTimestamp > $installedTimestamp;
538
+ }
539
+
540
+ if ( $isApplicable ) {
541
+ $applicableTranslations[] = $translation;
542
+ }
543
+ }
544
+
545
+ return $applicableTranslations;
546
+ }
547
+
548
+ /**
549
+ * Get a list of installed translations for this plugin or theme.
550
+ *
551
+ * @return array
552
+ */
553
+ protected function getInstalledTranslations() {
554
+ $installedTranslations = wp_get_installed_translations($this->translationType . 's');
555
+ if ( isset($installedTranslations[$this->directoryName]) ) {
556
+ $installedTranslations = $installedTranslations[$this->directoryName];
557
+ } else {
558
+ $installedTranslations = array();
559
+ }
560
+ return $installedTranslations;
561
+ }
562
+
563
+ /**
564
+ * Insert translation updates into the list maintained by WordPress.
565
+ *
566
+ * @param stdClass $updates
567
+ * @return stdClass
568
+ */
569
+ public function injectTranslationUpdates($updates) {
570
+ $translationUpdates = $this->getTranslationUpdates();
571
+ if ( empty($translationUpdates) ) {
572
+ return $updates;
573
+ }
574
+
575
+ //Being defensive.
576
+ if ( !is_object($updates) ) {
577
+ $updates = new stdClass();
578
+ }
579
+ if ( !isset($updates->translations) ) {
580
+ $updates->translations = array();
581
+ }
582
+
583
+ //In case there's a name collision with a plugin or theme hosted on wordpress.org,
584
+ //remove any preexisting updates that match our thing.
585
+ $updates->translations = array_values(array_filter(
586
+ $updates->translations,
587
+ array($this, 'isNotMyTranslation')
588
+ ));
589
+
590
+ //Add our updates to the list.
591
+ foreach($translationUpdates as $update) {
592
+ $convertedUpdate = array_merge(
593
+ array(
594
+ 'type' => $this->translationType,
595
+ 'slug' => $this->directoryName,
596
+ 'autoupdate' => 0,
597
+ //AFAICT, WordPress doesn't actually use the "version" field for anything.
598
+ //But lets make sure it's there, just in case.
599
+ 'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
600
+ ),
601
+ (array)$update
602
+ );
603
+
604
+ $updates->translations[] = $convertedUpdate;
605
+ }
606
+
607
+ return $updates;
608
+ }
609
+
610
+ /**
611
+ * Get a list of available translation updates.
612
+ *
613
+ * This method will return an empty array if there are no updates.
614
+ * Uses cached update data.
615
+ *
616
+ * @return array
617
+ */
618
+ public function getTranslationUpdates() {
619
+ return $this->updateState->getTranslations();
620
+ }
621
+
622
+ /**
623
+ * Remove all cached translation updates.
624
+ *
625
+ * @see wp_clean_update_cache
626
+ */
627
+ public function clearCachedTranslationUpdates() {
628
+ $this->updateState->setTranslations(array());
629
+ }
630
+
631
+ /**
632
+ * Filter callback. Keeps only translations that *don't* match this plugin or theme.
633
+ *
634
+ * @param array $translation
635
+ * @return bool
636
+ */
637
+ protected function isNotMyTranslation($translation) {
638
+ $isMatch = isset($translation['type'], $translation['slug'])
639
+ && ($translation['type'] === $this->translationType)
640
+ && ($translation['slug'] === $this->directoryName);
641
+
642
+ return !$isMatch;
643
+ }
644
+
645
+ /* -------------------------------------------------------------------
646
+ * Fix directory name when installing updates
647
+ * -------------------------------------------------------------------
648
+ */
649
+
650
+ /**
651
+ * Rename the update directory to match the existing plugin/theme directory.
652
+ *
653
+ * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
654
+ * exactly one directory, and that the directory name will be the same as the directory where
655
+ * the plugin or theme is currently installed.
656
+ *
657
+ * GitHub and other repositories provide ZIP downloads, but they often use directory names like
658
+ * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
659
+ *
660
+ * This is a hook callback. Don't call it from a plugin.
661
+ *
662
+ * @access protected
663
+ *
664
+ * @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource.
665
+ * @param string $remoteSource WordPress has extracted the update to this directory.
666
+ * @param WP_Upgrader $upgrader
667
+ * @return string|WP_Error
668
+ */
669
+ public function fixDirectoryName($source, $remoteSource, $upgrader) {
670
+ global $wp_filesystem;
671
+ /** @var WP_Filesystem_Base $wp_filesystem */
672
+
673
+ //Basic sanity checks.
674
+ if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
675
+ return $source;
676
+ }
677
+
678
+ //If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged.
679
+ if ( !$this->isBeingUpgraded($upgrader) ) {
680
+ return $source;
681
+ }
682
+
683
+ //Rename the source to match the existing directory.
684
+ $correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/';
685
+ if ( $source !== $correctedSource ) {
686
+ //The update archive should contain a single directory that contains the rest of plugin/theme files.
687
+ //Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource).
688
+ //We can't rename $remoteSource because that would break WordPress code that cleans up temporary files
689
+ //after update.
690
+ if ( $this->isBadDirectoryStructure($remoteSource) ) {
691
+ return new WP_Error(
692
+ 'puc-incorrect-directory-structure',
693
+ sprintf(
694
+ 'The directory structure of the update is incorrect. All files should be inside ' .
695
+ 'a directory named <span class="code">%s</span>, not at the root of the ZIP archive.',
696
+ htmlentities($this->slug)
697
+ )
698
+ );
699
+ }
700
+
701
+ /** @var WP_Upgrader_Skin $upgrader ->skin */
702
+ $upgrader->skin->feedback(sprintf(
703
+ 'Renaming %s to %s&#8230;',
704
+ '<span class="code">' . basename($source) . '</span>',
705
+ '<span class="code">' . $this->directoryName . '</span>'
706
+ ));
707
+
708
+ if ( $wp_filesystem->move($source, $correctedSource, true) ) {
709
+ $upgrader->skin->feedback('Directory successfully renamed.');
710
+ return $correctedSource;
711
+ } else {
712
+ return new WP_Error(
713
+ 'puc-rename-failed',
714
+ 'Unable to rename the update to match the existing directory.'
715
+ );
716
+ }
717
+ }
718
+
719
+ return $source;
720
+ }
721
+
722
+ /**
723
+ * Is there an update being installed right now, for this plugin or theme?
724
+ *
725
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
726
+ * @return bool
727
+ */
728
+ abstract public function isBeingUpgraded($upgrader = null);
729
+
730
+ /**
731
+ * Check for incorrect update directory structure. An update must contain a single directory,
732
+ * all other files should be inside that directory.
733
+ *
734
+ * @param string $remoteSource Directory path.
735
+ * @return bool
736
+ */
737
+ protected function isBadDirectoryStructure($remoteSource) {
738
+ global $wp_filesystem;
739
+ /** @var WP_Filesystem_Base $wp_filesystem */
740
+
741
+ $sourceFiles = $wp_filesystem->dirlist($remoteSource);
742
+ if ( is_array($sourceFiles) ) {
743
+ $sourceFiles = array_keys($sourceFiles);
744
+ $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
745
+ return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
746
+ }
747
+
748
+ //Assume it's fine.
749
+ return false;
750
+ }
751
+
752
+ /* -------------------------------------------------------------------
753
+ * File header parsing
754
+ * -------------------------------------------------------------------
755
+ */
756
+
757
+ /**
758
+ * Parse plugin or theme metadata from the header comment.
759
+ *
760
+ * This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
761
+ * It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
762
+ *
763
+ * @param string|null $content File contents.
764
+ * @return string[]
765
+ */
766
+ public function getFileHeader($content) {
767
+ $content = (string) $content;
768
+
769
+ //WordPress only looks at the first 8 KiB of the file, so we do the same.
770
+ $content = substr($content, 0, 8192);
771
+ //Normalize line endings.
772
+ $content = str_replace("\r", "\n", $content);
773
+
774
+ $headers = $this->getHeaderNames();
775
+ $results = array();
776
+ foreach ($headers as $field => $name) {
777
+ $success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
778
+
779
+ if ( ($success === 1) && $matches[1] ) {
780
+ $value = $matches[1];
781
+ if ( function_exists('_cleanup_header_comment') ) {
782
+ $value = _cleanup_header_comment($value);
783
+ }
784
+ $results[$field] = $value;
785
+ } else {
786
+ $results[$field] = '';
787
+ }
788
+ }
789
+
790
+ return $results;
791
+ }
792
+
793
+ /**
794
+ * @return array Format: ['HeaderKey' => 'Header Name']
795
+ */
796
+ abstract protected function getHeaderNames();
797
+
798
+ /* -------------------------------------------------------------------
799
+ * DebugBar integration
800
+ * -------------------------------------------------------------------
801
+ */
802
+
803
+ /**
804
+ * Initialize the update checker Debug Bar plugin/add-on thingy.
805
+ */
806
+ public function maybeInitDebugBar() {
807
+ if ( class_exists('Debug_Bar', false) && file_exists(dirname(__FILE__ . '/DebugBar')) ) {
808
+ $this->createDebugBarExtension();
809
+ }
810
+ }
811
+
812
+ protected function createDebugBarExtension() {
813
+ return new Puc_v4p2_DebugBar_Extension($this);
814
+ }
815
+
816
+ /**
817
+ * Display additional configuration details in the Debug Bar panel.
818
+ *
819
+ * @param Puc_v4p2_DebugBar_Panel $panel
820
+ */
821
+ public function onDisplayConfiguration($panel) {
822
+ //Do nothing. Subclasses can use this to add additional info to the panel.
823
+ }
824
+
825
+ }
826
+
827
+ endif;
admin/update-checker/Puc/v4p2/UpgraderStatus.php ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_UpgraderStatus', false) ):
3
+
4
+ /**
5
+ * A utility class that helps figure out which plugin or theme WordPress is upgrading.
6
+ *
7
+ * It may seem strange to have a separate class just for that, but the task is surprisingly complicated.
8
+ * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
9
+ * This class uses a few workarounds and heuristics to get the file name.
10
+ */
11
+ class Puc_v4p2_UpgraderStatus {
12
+ private $currentType = null; //"plugin" or "theme".
13
+ private $currentId = null; //Plugin basename or theme directory name.
14
+
15
+ public function __construct() {
16
+ //Keep track of which plugin/theme WordPress is currently upgrading.
17
+ add_filter('upgrader_pre_install', array($this, 'setUpgradedThing'), 10, 2);
18
+ add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
19
+ add_filter('upgrader_post_install', array($this, 'clearUpgradedThing'), 10, 1);
20
+ add_action('upgrader_process_complete', array($this, 'clearUpgradedThing'), 10, 1);
21
+ }
22
+
23
+ /**
24
+ * Is there and update being installed RIGHT NOW, for a specific plugin?
25
+ *
26
+ * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
27
+ * and upgrader implementations are liable to change without notice.
28
+ *
29
+ * @param string $pluginFile The plugin to check.
30
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
31
+ * @return bool True if the plugin identified by $pluginFile is being upgraded.
32
+ */
33
+ public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
34
+ return $this->isBeingUpgraded('plugin', $pluginFile, $upgrader);
35
+ }
36
+
37
+ /**
38
+ * Is there an update being installed for a specific theme?
39
+ *
40
+ * @param string $stylesheet Theme directory name.
41
+ * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
42
+ * @return bool
43
+ */
44
+ public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
45
+ return $this->isBeingUpgraded('theme', $stylesheet, $upgrader);
46
+ }
47
+
48
+ /**
49
+ * Check if a specific theme or plugin is being upgraded.
50
+ *
51
+ * @param string $type
52
+ * @param string $id
53
+ * @param Plugin_Upgrader|WP_Upgrader|null $upgrader
54
+ * @return bool
55
+ */
56
+ protected function isBeingUpgraded($type, $id, $upgrader = null) {
57
+ if ( isset($upgrader) ) {
58
+ list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader);
59
+ if ( $currentType !== null ) {
60
+ $this->currentType = $currentType;
61
+ $this->currentId = $currentId;
62
+ }
63
+ }
64
+ return ($this->currentType === $type) && ($this->currentId === $id);
65
+ }
66
+
67
+ /**
68
+ * Figure out which theme or plugin is being upgraded by a WP_Upgrader instance.
69
+ *
70
+ * Returns an array with two items. The first item is the type of the thing that's being
71
+ * upgraded: "plugin" or "theme". The second item is either the plugin basename or
72
+ * the theme directory name. If we can't determine what the upgrader is doing, both items
73
+ * will be NULL.
74
+ *
75
+ * Examples:
76
+ * ['plugin', 'plugin-dir-name/plugin.php']
77
+ * ['theme', 'theme-dir-name']
78
+ *
79
+ * @param Plugin_Upgrader|WP_Upgrader $upgrader
80
+ * @return array
81
+ */
82
+ private function getThingBeingUpgradedBy($upgrader) {
83
+ if ( !isset($upgrader, $upgrader->skin) ) {
84
+ return array(null, null);
85
+ }
86
+
87
+ //Figure out which plugin or theme is being upgraded.
88
+ $pluginFile = null;
89
+ $themeDirectoryName = null;
90
+
91
+ $skin = $upgrader->skin;
92
+ if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) {
93
+ $themeDirectoryName = $skin->theme_info->get_stylesheet();
94
+ } elseif ( $skin instanceof Plugin_Upgrader_Skin ) {
95
+ if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
96
+ $pluginFile = $skin->plugin;
97
+ }
98
+ } elseif ( $skin instanceof Theme_Upgrader_Skin ) {
99
+ if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
100
+ $themeDirectoryName = $skin->theme;
101
+ }
102
+ } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
103
+ //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
104
+ //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
105
+ //do is compare those headers to the headers of installed plugins.
106
+ $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
107
+ }
108
+
109
+ if ( $pluginFile !== null ) {
110
+ return array('plugin', $pluginFile);
111
+ } elseif ( $themeDirectoryName !== null ) {
112
+ return array('theme', $themeDirectoryName);
113
+ }
114
+ return array(null, null);
115
+ }
116
+
117
+ /**
118
+ * Identify an installed plugin based on its headers.
119
+ *
120
+ * @param array $searchHeaders The plugin file header to look for.
121
+ * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
122
+ */
123
+ private function identifyPluginByHeaders($searchHeaders) {
124
+ if ( !function_exists('get_plugins') ){
125
+ /** @noinspection PhpIncludeInspection */
126
+ require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
127
+ }
128
+
129
+ $installedPlugins = get_plugins();
130
+ $matches = array();
131
+ foreach($installedPlugins as $pluginBasename => $headers) {
132
+ $diff1 = array_diff_assoc($headers, $searchHeaders);
133
+ $diff2 = array_diff_assoc($searchHeaders, $headers);
134
+ if ( empty($diff1) && empty($diff2) ) {
135
+ $matches[] = $pluginBasename;
136
+ }
137
+ }
138
+
139
+ //It's possible (though very unlikely) that there could be two plugins with identical
140
+ //headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
141
+ if ( count($matches) !== 1 ) {
142
+ return null;
143
+ }
144
+
145
+ return reset($matches);
146
+ }
147
+
148
+ /**
149
+ * @access private
150
+ *
151
+ * @param mixed $input
152
+ * @param array $hookExtra
153
+ * @return mixed Returns $input unaltered.
154
+ */
155
+ public function setUpgradedThing($input, $hookExtra) {
156
+ if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) {
157
+ $this->currentId = $hookExtra['plugin'];
158
+ $this->currentType = 'plugin';
159
+ } elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) {
160
+ $this->currentId = $hookExtra['theme'];
161
+ $this->currentType = 'theme';
162
+ } else {
163
+ $this->currentType = null;
164
+ $this->currentId = null;
165
+ }
166
+ return $input;
167
+ }
168
+
169
+ /**
170
+ * @access private
171
+ *
172
+ * @param array $options
173
+ * @return array
174
+ */
175
+ public function setUpgradedPluginFromOptions($options) {
176
+ if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) {
177
+ $this->currentType = 'plugin';
178
+ $this->currentId = $options['hook_extra']['plugin'];
179
+ } else {
180
+ $this->currentType = null;
181
+ $this->currentId = null;
182
+ }
183
+ return $options;
184
+ }
185
+
186
+ /**
187
+ * @access private
188
+ *
189
+ * @param mixed $input
190
+ * @return mixed Returns $input unaltered.
191
+ */
192
+ public function clearUpgradedThing($input = null) {
193
+ $this->currentId = null;
194
+ $this->currentType = null;
195
+ return $input;
196
+ }
197
+ }
198
+
199
+ endif;
admin/update-checker/Puc/v4p2/Utils.php ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Utils', false) ):
4
+
5
+ class Puc_v4p2_Utils {
6
+ /**
7
+ * Get a value from a nested array or object based on a path.
8
+ *
9
+ * @param array|object|null $collection Get an entry from this array.
10
+ * @param array|string $path A list of array keys in hierarchy order, or a string path like "foo.bar.baz".
11
+ * @param mixed $default The value to return if the specified path is not found.
12
+ * @param string $separator Path element separator. Only applies to string paths.
13
+ * @return mixed
14
+ */
15
+ public static function get($collection, $path, $default = null, $separator = '.') {
16
+ if ( is_string($path) ) {
17
+ $path = explode($separator, $path);
18
+ }
19
+
20
+ //Follow the $path into $input as far as possible.
21
+ $currentValue = $collection;
22
+ foreach ($path as $node) {
23
+ if ( is_array($currentValue) && isset($currentValue[$node]) ) {
24
+ $currentValue = $currentValue[$node];
25
+ } else if ( is_object($currentValue) && isset($currentValue->$node) ) {
26
+ $currentValue = $currentValue->$node;
27
+ } else {
28
+ return $default;
29
+ }
30
+ }
31
+
32
+ return $currentValue;
33
+ }
34
+
35
+ /**
36
+ * Get the first array element that is not empty.
37
+ *
38
+ * @param array $values
39
+ * @param mixed|null $default Returns this value if there are no non-empty elements.
40
+ * @return mixed|null
41
+ */
42
+ public static function findNotEmpty($values, $default = null) {
43
+ if ( empty($values) ) {
44
+ return $default;
45
+ }
46
+
47
+ foreach ($values as $value) {
48
+ if ( !empty($value) ) {
49
+ return $value;
50
+ }
51
+ }
52
+
53
+ return $default;
54
+ }
55
+
56
+ /**
57
+ * Check if the input string starts with the specified prefix.
58
+ *
59
+ * @param string $input
60
+ * @param string $prefix
61
+ * @return bool
62
+ */
63
+ public static function startsWith($input, $prefix) {
64
+ $length = strlen($prefix);
65
+ return (substr($input, 0, $length) === $prefix);
66
+ }
67
+ }
68
+
69
+ endif;
admin/update-checker/Puc/v4p2/Vcs/Api.php ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Vcs_Api') ):
3
+
4
+ abstract class Puc_v4p2_Vcs_Api {
5
+ protected $tagNameProperty = 'name';
6
+
7
+ /**
8
+ * @var string
9
+ */
10
+ protected $repositoryUrl = '';
11
+
12
+ /**
13
+ * @var mixed Authentication details for private repositories. Format depends on service.
14
+ */
15
+ protected $credentials = null;
16
+
17
+ /**
18
+ * @var string The filter tag that's used to filter options passed to wp_remote_get.
19
+ * For example, "puc_request_info_options-slug" or "puc_request_update_options_theme-slug".
20
+ */
21
+ protected $httpFilterName = '';
22
+
23
+ /**
24
+ * Puc_v4p2_Vcs_Api constructor.
25
+ *
26
+ * @param string $repositoryUrl
27
+ * @param array|string|null $credentials
28
+ */
29
+ public function __construct($repositoryUrl, $credentials = null) {
30
+ $this->repositoryUrl = $repositoryUrl;
31
+ $this->setAuthentication($credentials);
32
+ }
33
+
34
+ /**
35
+ * @return string
36
+ */
37
+ public function getRepositoryUrl() {
38
+ return $this->repositoryUrl;
39
+ }
40
+
41
+ /**
42
+ * Figure out which reference (i.e tag or branch) contains the latest version.
43
+ *
44
+ * @param string $configBranch Start looking in this branch.
45
+ * @return null|Puc_v4p2_Vcs_Reference
46
+ */
47
+ abstract public function chooseReference($configBranch);
48
+
49
+ /**
50
+ * Get the readme.txt file from the remote repository and parse it
51
+ * according to the plugin readme standard.
52
+ *
53
+ * @param string $ref Tag or branch name.
54
+ * @return array Parsed readme.
55
+ */
56
+ public function getRemoteReadme($ref = 'master') {
57
+ $fileContents = $this->getRemoteFile('readme.txt', $ref);
58
+ if ( empty($fileContents) ) {
59
+ return array();
60
+ }
61
+
62
+ $parser = new PucReadmeParser();
63
+ return $parser->parse_readme_contents($fileContents);
64
+ }
65
+
66
+ /**
67
+ * Get a branch.
68
+ *
69
+ * @param string $branchName
70
+ * @return Puc_v4p2_Vcs_Reference|null
71
+ */
72
+ abstract public function getBranch($branchName);
73
+
74
+ /**
75
+ * Get a specific tag.
76
+ *
77
+ * @param string $tagName
78
+ * @return Puc_v4p2_Vcs_Reference|null
79
+ */
80
+ abstract public function getTag($tagName);
81
+
82
+ /**
83
+ * Get the tag that looks like the highest version number.
84
+ * (Implementations should skip pre-release versions if possible.)
85
+ *
86
+ * @return Puc_v4p2_Vcs_Reference|null
87
+ */
88
+ abstract public function getLatestTag();
89
+
90
+ /**
91
+ * Check if a tag name string looks like a version number.
92
+ *
93
+ * @param string $name
94
+ * @return bool
95
+ */
96
+ protected function looksLikeVersion($name) {
97
+ //Tag names may be prefixed with "v", e.g. "v1.2.3".
98
+ $name = ltrim($name, 'v');
99
+
100
+ //The version string must start with a number.
101
+ if ( !is_numeric(substr($name, 0, 1)) ) {
102
+ return false;
103
+ }
104
+
105
+ //The goal is to accept any SemVer-compatible or "PHP-standardized" version number.
106
+ return (preg_match('@^(\d{1,5}?)(\.\d{1,10}?){0,4}?($|[abrdp+_\-]|\s)@i', $name) === 1);
107
+ }
108
+
109
+ /**
110
+ * Check if a tag appears to be named like a version number.
111
+ *
112
+ * @param stdClass $tag
113
+ * @return bool
114
+ */
115
+ protected function isVersionTag($tag) {
116
+ $property = $this->tagNameProperty;
117
+ return isset($tag->$property) && $this->looksLikeVersion($tag->$property);
118
+ }
119
+
120
+ /**
121
+ * Sort a list of tags as if they were version numbers.
122
+ * Tags that don't look like version number will be removed.
123
+ *
124
+ * @param stdClass[] $tags Array of tag objects.
125
+ * @return stdClass[] Filtered array of tags sorted in descending order.
126
+ */
127
+ protected function sortTagsByVersion($tags) {
128
+ //Keep only those tags that look like version numbers.
129
+ $versionTags = array_filter($tags, array($this, 'isVersionTag'));
130
+ //Sort them in descending order.
131
+ usort($versionTags, array($this, 'compareTagNames'));
132
+
133
+ return $versionTags;
134
+ }
135
+
136
+ /**
137
+ * Compare two tags as if they were version number.
138
+ *
139
+ * @param stdClass $tag1 Tag object.
140
+ * @param stdClass $tag2 Another tag object.
141
+ * @return int
142
+ */
143
+ protected function compareTagNames($tag1, $tag2) {
144
+ $property = $this->tagNameProperty;
145
+ if ( !isset($tag1->$property) ) {
146
+ return 1;
147
+ }
148
+ if ( !isset($tag2->$property) ) {
149
+ return -1;
150
+ }
151
+ return -version_compare(ltrim($tag1->$property, 'v'), ltrim($tag2->$property, 'v'));
152
+ }
153
+
154
+ /**
155
+ * Get the contents of a file from a specific branch or tag.
156
+ *
157
+ * @param string $path File name.
158
+ * @param string $ref
159
+ * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
160
+ */
161
+ abstract public function getRemoteFile($path, $ref = 'master');
162
+
163
+ /**
164
+ * Get the timestamp of the latest commit that changed the specified branch or tag.
165
+ *
166
+ * @param string $ref Reference name (e.g. branch or tag).
167
+ * @return string|null
168
+ */
169
+ abstract public function getLatestCommitTime($ref);
170
+
171
+ /**
172
+ * Get the contents of the changelog file from the repository.
173
+ *
174
+ * @param string $ref
175
+ * @param string $localDirectory Full path to the local plugin or theme directory.
176
+ * @return null|string The HTML contents of the changelog.
177
+ */
178
+ public function getRemoteChangelog($ref, $localDirectory) {
179
+ $filename = $this->findChangelogName($localDirectory);
180
+ if ( empty($filename) ) {
181
+ return null;
182
+ }
183
+
184
+ $changelog = $this->getRemoteFile($filename, $ref);
185
+ if ( $changelog === null ) {
186
+ return null;
187
+ }
188
+
189
+ /** @noinspection PhpUndefinedClassInspection */
190
+ return Parsedown::instance()->text($changelog);
191
+ }
192
+
193
+ /**
194
+ * Guess the name of the changelog file.
195
+ *
196
+ * @param string $directory
197
+ * @return string|null
198
+ */
199
+ protected function findChangelogName($directory) {
200
+ if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
201
+ return null;
202
+ }
203
+
204
+ $possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
205
+ $files = scandir($directory);
206
+ $foundNames = array_intersect($possibleNames, $files);
207
+
208
+ if ( !empty($foundNames) ) {
209
+ return reset($foundNames);
210
+ }
211
+ return null;
212
+ }
213
+
214
+ /**
215
+ * Set authentication credentials.
216
+ *
217
+ * @param $credentials
218
+ */
219
+ public function setAuthentication($credentials) {
220
+ $this->credentials = $credentials;
221
+ }
222
+
223
+ public function isAuthenticationEnabled() {
224
+ return !empty($this->credentials);
225
+ }
226
+
227
+ /**
228
+ * @param string $url
229
+ * @return string
230
+ */
231
+ public function signDownloadUrl($url) {
232
+ return $url;
233
+ }
234
+
235
+ /**
236
+ * @param string $filterName
237
+ */
238
+ public function setHttpFilterName($filterName) {
239
+ $this->httpFilterName = $filterName;
240
+ }
241
+ }
242
+
243
+ endif;
admin/update-checker/Puc/v4p2/Vcs/BaseChecker.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !interface_exists('Puc_v4p2_Vcs_BaseChecker', false) ):
3
+
4
+ interface Puc_v4p2_Vcs_BaseChecker {
5
+ /**
6
+ * Set the repository branch to use for updates. Defaults to 'master'.
7
+ *
8
+ * @param string $branch
9
+ * @return $this
10
+ */
11
+ public function setBranch($branch);
12
+
13
+ /**
14
+ * Set authentication credentials.
15
+ *
16
+ * @param array|string $credentials
17
+ * @return $this
18
+ */
19
+ public function setAuthentication($credentials);
20
+ }
21
+
22
+ endif;
admin/update-checker/Puc/v4p2/Vcs/BitBucketApi.php ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Vcs_BitBucketApi', false) ):
3
+
4
+ class Puc_v4p2_Vcs_BitBucketApi extends Puc_v4p2_Vcs_Api {
5
+ /**
6
+ * @var Puc_v4p2_OAuthSignature
7
+ */
8
+ private $oauth = null;
9
+
10
+ /**
11
+ * @var string
12
+ */
13
+ private $username;
14
+
15
+ /**
16
+ * @var string
17
+ */
18
+ private $repository;
19
+
20
+ public function __construct($repositoryUrl, $credentials = array()) {
21
+ $path = @parse_url($repositoryUrl, PHP_URL_PATH);
22
+ if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
23
+ $this->username = $matches['username'];
24
+ $this->repository = $matches['repository'];
25
+ } else {
26
+ throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
27
+ }
28
+
29
+ parent::__construct($repositoryUrl, $credentials);
30
+ }
31
+
32
+ /**
33
+ * Figure out which reference (i.e tag or branch) contains the latest version.
34
+ *
35
+ * @param string $configBranch Start looking in this branch.
36
+ * @return null|Puc_v4p2_Vcs_Reference
37
+ */
38
+ public function chooseReference($configBranch) {
39
+ $updateSource = null;
40
+
41
+ //Check if there's a "Stable tag: 1.2.3" header that points to a valid tag.
42
+ $updateSource = $this->getStableTag($configBranch);
43
+
44
+ //Look for version-like tags.
45
+ if ( !$updateSource && ($configBranch === 'master') ) {
46
+ $updateSource = $this->getLatestTag();
47
+ }
48
+ //If all else fails, use the specified branch itself.
49
+ if ( !$updateSource ) {
50
+ $updateSource = $this->getBranch($configBranch);
51
+ }
52
+
53
+ return $updateSource;
54
+ }
55
+
56
+ public function getBranch($branchName) {
57
+ $branch = $this->api('/refs/branches/' . $branchName);
58
+ if ( is_wp_error($branch) || empty($branch) ) {
59
+ return null;
60
+ }
61
+
62
+ return new Puc_v4p2_Vcs_Reference(array(
63
+ 'name' => $branch->name,
64
+ 'updated' => $branch->target->date,
65
+ 'downloadUrl' => $this->getDownloadUrl($branch->name),
66
+ ));
67
+ }
68
+
69
+ /**
70
+ * Get a specific tag.
71
+ *
72
+ * @param string $tagName
73
+ * @return Puc_v4p2_Vcs_Reference|null
74
+ */
75
+ public function getTag($tagName) {
76
+ $tag = $this->api('/refs/tags/' . $tagName);
77
+ if ( is_wp_error($tag) || empty($tag) ) {
78
+ return null;
79
+ }
80
+
81
+ return new Puc_v4p2_Vcs_Reference(array(
82
+ 'name' => $tag->name,
83
+ 'version' => ltrim($tag->name, 'v'),
84
+ 'updated' => $tag->target->date,
85
+ 'downloadUrl' => $this->getDownloadUrl($tag->name),
86
+ ));
87
+ }
88
+
89
+ /**
90
+ * Get the tag that looks like the highest version number.
91
+ *
92
+ * @return Puc_v4p2_Vcs_Reference|null
93
+ */
94
+ public function getLatestTag() {
95
+ $tags = $this->api('/refs/tags?sort=-target.date');
96
+ if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
97
+ return null;
98
+ }
99
+
100
+ //Filter and sort the list of tags.
101
+ $versionTags = $this->sortTagsByVersion($tags->values);
102
+
103
+ //Return the first result.
104
+ if ( !empty($versionTags) ) {
105
+ $tag = $versionTags[0];
106
+ return new Puc_v4p2_Vcs_Reference(array(
107
+ 'name' => $tag->name,
108
+ 'version' => ltrim($tag->name, 'v'),
109
+ 'updated' => $tag->target->date,
110
+ 'downloadUrl' => $this->getDownloadUrl($tag->name),
111
+ ));
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /**
117
+ * Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
118
+ *
119
+ * @param string $branch
120
+ * @return null|Puc_v4p2_Vcs_Reference
121
+ */
122
+ protected function getStableTag($branch) {
123
+ $remoteReadme = $this->getRemoteReadme($branch);
124
+ if ( !empty($remoteReadme['stable_tag']) ) {
125
+ $tag = $remoteReadme['stable_tag'];
126
+
127
+ //You can explicitly opt out of using tags by setting "Stable tag" to
128
+ //"trunk" or the name of the current branch.
129
+ if ( ($tag === $branch) || ($tag === 'trunk') ) {
130
+ return $this->getBranch($branch);
131
+ }
132
+
133
+ return $this->getTag($tag);
134
+ }
135
+
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * @param string $ref
141
+ * @return string
142
+ */
143
+ protected function getDownloadUrl($ref) {
144
+ return sprintf(
145
+ 'https://bitbucket.org/%s/%s/get/%s.zip',
146
+ $this->username,
147
+ $this->repository,
148
+ $ref
149
+ );
150
+ }
151
+
152
+ /**
153
+ * Get the contents of a file from a specific branch or tag.
154
+ *
155
+ * @param string $path File name.
156
+ * @param string $ref
157
+ * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
158
+ */
159
+ public function getRemoteFile($path, $ref = 'master') {
160
+ $response = $this->api('src/' . $ref . '/' . ltrim($path), '1.0');
161
+ if ( is_wp_error($response) || !isset($response, $response->data) ) {
162
+ return null;
163
+ }
164
+ return $response->data;
165
+ }
166
+
167
+ /**
168
+ * Get the timestamp of the latest commit that changed the specified branch or tag.
169
+ *
170
+ * @param string $ref Reference name (e.g. branch or tag).
171
+ * @return string|null
172
+ */
173
+ public function getLatestCommitTime($ref) {
174
+ $response = $this->api('commits/' . $ref);
175
+ if ( isset($response->values, $response->values[0], $response->values[0]->date) ) {
176
+ return $response->values[0]->date;
177
+ }
178
+ return null;
179
+ }
180
+
181
+ /**
182
+ * Perform a BitBucket API 2.0 request.
183
+ *
184
+ * @param string $url
185
+ * @param string $version
186
+ * @return mixed|WP_Error
187
+ */
188
+ public function api($url, $version = '2.0') {
189
+ $url = implode('/', array(
190
+ 'https://api.bitbucket.org',
191
+ $version,
192
+ 'repositories',
193
+ $this->username,
194
+ $this->repository,
195
+ ltrim($url, '/')
196
+ ));
197
+
198
+ if ( $this->oauth ) {
199
+ $url = $this->oauth->sign($url,'GET');
200
+ }
201
+
202
+ $options = array('timeout' => 10);
203
+ if ( !empty($this->httpFilterName) ) {
204
+ $options = apply_filters($this->httpFilterName, $options);
205
+ }
206
+ $response = wp_remote_get($url, $options);
207
+ if ( is_wp_error($response) ) {
208
+ return $response;
209
+ }
210
+
211
+ $code = wp_remote_retrieve_response_code($response);
212
+ $body = wp_remote_retrieve_body($response);
213
+ if ( $code === 200 ) {
214
+ $document = json_decode($body);
215
+ return $document;
216
+ }
217
+
218
+ return new WP_Error(
219
+ 'puc-bitbucket-http-error',
220
+ 'BitBucket API error. HTTP status: ' . $code
221
+ );
222
+ }
223
+
224
+ /**
225
+ * @param array $credentials
226
+ */
227
+ public function setAuthentication($credentials) {
228
+ parent::setAuthentication($credentials);
229
+
230
+ if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
231
+ $this->oauth = new Puc_v4p2_OAuthSignature(
232
+ $credentials['consumer_key'],
233
+ $credentials['consumer_secret']
234
+ );
235
+ } else {
236
+ $this->oauth = null;
237
+ }
238
+ }
239
+
240
+ public function signDownloadUrl($url) {
241
+ //Add authentication data to download URLs. Since OAuth signatures incorporate
242
+ //timestamps, we have to do this immediately before inserting the update. Otherwise
243
+ //authentication could fail due to a stale timestamp.
244
+ if ( $this->oauth ) {
245
+ $url = $this->oauth->sign($url);
246
+ }
247
+ return $url;
248
+ }
249
+ }
250
+
251
+ endif;
admin/update-checker/Puc/v4p2/Vcs/GitHubApi.php ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Vcs_GitHubApi', false) ):
4
+
5
+ class Puc_v4p2_Vcs_GitHubApi extends Puc_v4p2_Vcs_Api {
6
+ /**
7
+ * @var string GitHub username.
8
+ */
9
+ protected $userName;
10
+ /**
11
+ * @var string GitHub repository name.
12
+ */
13
+ protected $repositoryName;
14
+
15
+ /**
16
+ * @var string Either a fully qualified repository URL, or just "user/repo-name".
17
+ */
18
+ protected $repositoryUrl;
19
+
20
+ /**
21
+ * @var string GitHub authentication token. Optional.
22
+ */
23
+ protected $accessToken;
24
+
25
+ public function __construct($repositoryUrl, $accessToken = null) {
26
+ $path = @parse_url($repositoryUrl, PHP_URL_PATH);
27
+ if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
28
+ $this->userName = $matches['username'];
29
+ $this->repositoryName = $matches['repository'];
30
+ } else {
31
+ throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
32
+ }
33
+
34
+ parent::__construct($repositoryUrl, $accessToken);
35
+ }
36
+
37
+ /**
38
+ * Get the latest release from GitHub.
39
+ *
40
+ * @return Puc_v4p2_Vcs_Reference|null
41
+ */
42
+ public function getLatestRelease() {
43
+ $release = $this->api('/repos/:user/:repo/releases/latest');
44
+ if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
45
+ return null;
46
+ }
47
+
48
+ $reference = new Puc_v4p2_Vcs_Reference(array(
49
+ 'name' => $release->tag_name,
50
+ 'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
51
+ 'downloadUrl' => $this->signDownloadUrl($release->zipball_url),
52
+ 'updated' => $release->created_at,
53
+ 'apiResponse' => $release,
54
+ ));
55
+
56
+ if ( !empty($release->body) ) {
57
+ /** @noinspection PhpUndefinedClassInspection */
58
+ $reference->changelog = Parsedown::instance()->text($release->body);
59
+ }
60
+ if ( isset($release->assets[0]) ) {
61
+ $reference->downloadCount = $release->assets[0]->download_count;
62
+ }
63
+
64
+ return $reference;
65
+ }
66
+
67
+ /**
68
+ * Get the tag that looks like the highest version number.
69
+ *
70
+ * @return Puc_v4p2_Vcs_Reference|null
71
+ */
72
+ public function getLatestTag() {
73
+ $tags = $this->api('/repos/:user/:repo/tags');
74
+
75
+ if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
76
+ return null;
77
+ }
78
+
79
+ $versionTags = $this->sortTagsByVersion($tags);
80
+ if ( empty($versionTags) ) {
81
+ return null;
82
+ }
83
+
84
+ $tag = $versionTags[0];
85
+ return new Puc_v4p2_Vcs_Reference(array(
86
+ 'name' => $tag->name,
87
+ 'version' => ltrim($tag->name, 'v'),
88
+ 'downloadUrl' => $this->signDownloadUrl($tag->zipball_url),
89
+ 'apiResponse' => $tag,
90
+ ));
91
+ }
92
+
93
+ /**
94
+ * Get a branch by name.
95
+ *
96
+ * @param string $branchName
97
+ * @return null|Puc_v4p2_Vcs_Reference
98
+ */
99
+ public function getBranch($branchName) {
100
+ $branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
101
+ if ( is_wp_error($branch) || empty($branch) ) {
102
+ return null;
103
+ }
104
+
105
+ $reference = new Puc_v4p2_Vcs_Reference(array(
106
+ 'name' => $branch->name,
107
+ 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
108
+ 'apiResponse' => $branch,
109
+ ));
110
+
111
+ if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
112
+ $reference->updated = $branch->commit->commit->author->date;
113
+ }
114
+
115
+ return $reference;
116
+ }
117
+
118
+ /**
119
+ * Get the latest commit that changed the specified file.
120
+ *
121
+ * @param string $filename
122
+ * @param string $ref Reference name (e.g. branch or tag).
123
+ * @return StdClass|null
124
+ */
125
+ public function getLatestCommit($filename, $ref = 'master') {
126
+ $commits = $this->api(
127
+ '/repos/:user/:repo/commits',
128
+ array(
129
+ 'path' => $filename,
130
+ 'sha' => $ref,
131
+ )
132
+ );
133
+ if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
134
+ return $commits[0];
135
+ }
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * Get the timestamp of the latest commit that changed the specified branch or tag.
141
+ *
142
+ * @param string $ref Reference name (e.g. branch or tag).
143
+ * @return string|null
144
+ */
145
+ public function getLatestCommitTime($ref) {
146
+ $commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
147
+ if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
148
+ return $commits[0]->commit->author->date;
149
+ }
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * Perform a GitHub API request.
155
+ *
156
+ * @param string $url
157
+ * @param array $queryParams
158
+ * @return mixed|WP_Error
159
+ */
160
+ protected function api($url, $queryParams = array()) {
161
+ $url = $this->buildApiUrl($url, $queryParams);
162
+
163
+ $options = array('timeout' => 10);
164
+ if ( !empty($this->httpFilterName) ) {
165
+ $options = apply_filters($this->httpFilterName, $options);
166
+ }
167
+ $response = wp_remote_get($url, $options);
168
+ if ( is_wp_error($response) ) {
169
+ return $response;
170
+ }
171
+
172
+ $code = wp_remote_retrieve_response_code($response);
173
+ $body = wp_remote_retrieve_body($response);
174
+ if ( $code === 200 ) {
175
+ $document = json_decode($body);
176
+ return $document;
177
+ }
178
+
179
+ return new WP_Error(
180
+ 'puc-github-http-error',
181
+ 'GitHub API error. HTTP status: ' . $code
182
+ );
183
+ }
184
+
185
+ /**
186
+ * Build a fully qualified URL for an API request.
187
+ *
188
+ * @param string $url
189
+ * @param array $queryParams
190
+ * @return string
191
+ */
192
+ protected function buildApiUrl($url, $queryParams) {
193
+ $variables = array(
194
+ 'user' => $this->userName,
195
+ 'repo' => $this->repositoryName,
196
+ );
197
+ foreach ($variables as $name => $value) {
198
+ $url = str_replace('/:' . $name, '/' . urlencode($value), $url);
199
+ }
200
+ $url = 'https://api.github.com' . $url;
201
+
202
+ if ( !empty($this->accessToken) ) {
203
+ $queryParams['access_token'] = $this->accessToken;
204
+ }
205
+ if ( !empty($queryParams) ) {
206
+ $url = add_query_arg($queryParams, $url);
207
+ }
208
+
209
+ return $url;
210
+ }
211
+
212
+ /**
213
+ * Get the contents of a file from a specific branch or tag.
214
+ *
215
+ * @param string $path File name.
216
+ * @param string $ref
217
+ * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
218
+ */
219
+ public function getRemoteFile($path, $ref = 'master') {
220
+ $apiUrl = '/repos/:user/:repo/contents/' . $path;
221
+ $response = $this->api($apiUrl, array('ref' => $ref));
222
+
223
+ if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
224
+ return null;
225
+ }
226
+ return base64_decode($response->content);
227
+ }
228
+
229
+ /**
230
+ * Generate a URL to download a ZIP archive of the specified branch/tag/etc.
231
+ *
232
+ * @param string $ref
233
+ * @return string
234
+ */
235
+ public function buildArchiveDownloadUrl($ref = 'master') {
236
+ $url = sprintf(
237
+ 'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
238
+ urlencode($this->userName),
239
+ urlencode($this->repositoryName),
240
+ urlencode($ref)
241
+ );
242
+ if ( !empty($this->accessToken) ) {
243
+ $url = $this->signDownloadUrl($url);
244
+ }
245
+ return $url;
246
+ }
247
+
248
+ /**
249
+ * Get a specific tag.
250
+ *
251
+ * @param string $tagName
252
+ * @return Puc_v4p2_Vcs_Reference|null
253
+ */
254
+ public function getTag($tagName) {
255
+ //The current GitHub update checker doesn't use getTag, so I didn't bother to implement it.
256
+ throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
257
+ }
258
+
259
+ public function setAuthentication($credentials) {
260
+ parent::setAuthentication($credentials);
261
+ $this->accessToken = is_string($credentials) ? $credentials : null;
262
+ }
263
+
264
+ /**
265
+ * Figure out which reference (i.e tag or branch) contains the latest version.
266
+ *
267
+ * @param string $configBranch Start looking in this branch.
268
+ * @return null|Puc_v4p2_Vcs_Reference
269
+ */
270
+ public function chooseReference($configBranch) {
271
+ $updateSource = null;
272
+
273
+ if ( $configBranch === 'master' ) {
274
+ //Use the latest release.
275
+ $updateSource = $this->getLatestRelease();
276
+ if ( $updateSource === null ) {
277
+ //Failing that, use the tag with the highest version number.
278
+ $updateSource = $this->getLatestTag();
279
+ }
280
+ }
281
+ //Alternatively, just use the branch itself.
282
+ if ( empty($updateSource) ) {
283
+ $updateSource = $this->getBranch($configBranch);
284
+ }
285
+
286
+ return $updateSource;
287
+ }
288
+
289
+ /**
290
+ * @param string $url
291
+ * @return string
292
+ */
293
+ public function signDownloadUrl($url) {
294
+ if ( empty($this->credentials) ) {
295
+ return $url;
296
+ }
297
+ return add_query_arg('access_token', $this->credentials, $url);
298
+ }
299
+
300
+ }
301
+
302
+ endif;
admin/update-checker/Puc/v4p2/Vcs/PluginUpdateChecker.php ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Vcs_PluginUpdateChecker') ):
3
+
4
+ class Puc_v4p2_Vcs_PluginUpdateChecker extends Puc_v4p2_Plugin_UpdateChecker implements Puc_v4p2_Vcs_BaseChecker {
5
+ /**
6
+ * @var string The branch where to look for updates. Defaults to "master".
7
+ */
8
+ protected $branch = 'master';
9
+
10
+ /**
11
+ * @var Puc_v4p2_Vcs_Api Repository API client.
12
+ */
13
+ protected $api = null;
14
+
15
+ /**
16
+ * Puc_v4p2_Vcs_PluginUpdateChecker constructor.
17
+ *
18
+ * @param Puc_v4p2_Vcs_Api $api
19
+ * @param string $pluginFile
20
+ * @param string $slug
21
+ * @param int $checkPeriod
22
+ * @param string $optionName
23
+ * @param string $muPluginFile
24
+ */
25
+ public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
26
+ $this->api = $api;
27
+ $this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
28
+
29
+ parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
30
+ }
31
+
32
+ public function requestInfo($unusedParameter = null) {
33
+ //We have to make several remote API requests to gather all the necessary info
34
+ //which can take a while on slow networks.
35
+ if ( function_exists('set_time_limit') ) {
36
+ @set_time_limit(60);
37
+ }
38
+
39
+ $api = $this->api;
40
+
41
+ $info = new Puc_v4p2_Plugin_Info();
42
+ $info->filename = $this->pluginFile;
43
+ $info->slug = $this->slug;
44
+
45
+ $this->setInfoFromHeader($this->getPluginHeader(), $info);
46
+
47
+ //Pick a branch or tag.
48
+ $updateSource = $api->chooseReference($this->branch);
49
+ if ( $updateSource ) {
50
+ $ref = $updateSource->name;
51
+ $info->version = $updateSource->version;
52
+ $info->last_updated = $updateSource->updated;
53
+ $info->download_url = $updateSource->downloadUrl;
54
+
55
+ if ( !empty($updateSource->changelog) ) {
56
+ $info->sections['changelog'] = $updateSource->changelog;
57
+ }
58
+ if ( isset($updateSource->downloadCount) ) {
59
+ $info->downloaded = $updateSource->downloadCount;
60
+ }
61
+ } else {
62
+ //There's probably a network problem or an authentication error.
63
+ return null;
64
+ }
65
+
66
+ //Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
67
+ //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
68
+ $mainPluginFile = basename($this->pluginFile);
69
+ $remotePlugin = $api->getRemoteFile($mainPluginFile, $ref);
70
+ if ( !empty($remotePlugin) ) {
71
+ $remoteHeader = $this->getFileHeader($remotePlugin);
72
+ $this->setInfoFromHeader($remoteHeader, $info);
73
+ }
74
+
75
+ //Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
76
+ //a lot of useful information like the required/tested WP version, changelog, and so on.
77
+ if ( $this->readmeTxtExistsLocally() ) {
78
+ $this->setInfoFromRemoteReadme($ref, $info);
79
+ }
80
+
81
+ //The changelog might be in a separate file.
82
+ if ( empty($info->sections['changelog']) ) {
83
+ $info->sections['changelog'] = $api->getRemoteChangelog($ref, dirname($this->getAbsolutePath()));
84
+ if ( empty($info->sections['changelog']) ) {
85
+ $info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
86
+ }
87
+ }
88
+
89
+ if ( empty($info->last_updated) ) {
90
+ //Fetch the latest commit that changed the tag or branch and use it as the "last_updated" date.
91
+ $latestCommitTime = $api->getLatestCommitTime($ref);
92
+ if ( $latestCommitTime !== null ) {
93
+ $info->last_updated = $latestCommitTime;
94
+ }
95
+ }
96
+
97
+ $info = apply_filters($this->getUniqueName('request_info_result'), $info, null);
98
+ return $info;
99
+ }
100
+
101
+ /**
102
+ * Check if the currently installed version has a readme.txt file.
103
+ *
104
+ * @return bool
105
+ */
106
+ protected function readmeTxtExistsLocally() {
107
+ $pluginDirectory = dirname($this->pluginAbsolutePath);
108
+ if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
109
+ return false;
110
+ }
111
+ return is_file($pluginDirectory . '/readme.txt');
112
+ }
113
+
114
+ /**
115
+ * Copy plugin metadata from a file header to a Plugin Info object.
116
+ *
117
+ * @param array $fileHeader
118
+ * @param Puc_v4p2_Plugin_Info $pluginInfo
119
+ */
120
+ protected function setInfoFromHeader($fileHeader, $pluginInfo) {
121
+ $headerToPropertyMap = array(
122
+ 'Version' => 'version',
123
+ 'Name' => 'name',
124
+ 'PluginURI' => 'homepage',
125
+ 'Author' => 'author',
126
+ 'AuthorName' => 'author',
127
+ 'AuthorURI' => 'author_homepage',
128
+
129
+ 'Requires WP' => 'requires',
130
+ 'Tested WP' => 'tested',
131
+ 'Requires at least' => 'requires',
132
+ 'Tested up to' => 'tested',
133
+ );
134
+ foreach ($headerToPropertyMap as $headerName => $property) {
135
+ if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
136
+ $pluginInfo->$property = $fileHeader[$headerName];
137
+ }
138
+ }
139
+
140
+ if ( !empty($fileHeader['Description']) ) {
141
+ $pluginInfo->sections['description'] = $fileHeader['Description'];
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Copy plugin metadata from the remote readme.txt file.
147
+ *
148
+ * @param string $ref GitHub tag or branch where to look for the readme.
149
+ * @param Puc_v4p2_Plugin_Info $pluginInfo
150
+ */
151
+ protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
152
+ $readme = $this->api->getRemoteReadme($ref);
153
+ if ( empty($readme) ) {
154
+ return;
155
+ }
156
+
157
+ if ( isset($readme['sections']) ) {
158
+ $pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
159
+ }
160
+ if ( !empty($readme['tested_up_to']) ) {
161
+ $pluginInfo->tested = $readme['tested_up_to'];
162
+ }
163
+ if ( !empty($readme['requires_at_least']) ) {
164
+ $pluginInfo->requires = $readme['requires_at_least'];
165
+ }
166
+
167
+ if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
168
+ $pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
169
+ }
170
+ }
171
+
172
+ public function setBranch($branch) {
173
+ $this->branch = $branch;
174
+ return $this;
175
+ }
176
+
177
+ public function setAuthentication($credentials) {
178
+ $this->api->setAuthentication($credentials);
179
+ return $this;
180
+ }
181
+
182
+ public function getUpdate() {
183
+ $update = parent::getUpdate();
184
+
185
+ if ( isset($update) && !empty($update->download_url) ) {
186
+ $update->download_url = $this->api->signDownloadUrl($update->download_url);
187
+ }
188
+
189
+ return $update;
190
+ }
191
+
192
+ public function onDisplayConfiguration($panel) {
193
+ parent::onDisplayConfiguration($panel);
194
+ $panel->row('Branch', $this->branch);
195
+ $panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
196
+ $panel->row('API client', get_class($this->api));
197
+ }
198
+ }
199
+
200
+ endif;
admin/update-checker/Puc/v4p2/Vcs/Reference.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !class_exists('Puc_v4p2_Vcs_Reference', false) ):
3
+
4
+ /**
5
+ * This class represents a VCS branch or tag. It's intended as a read only, short-lived container
6
+ * that only exists to provide a limited degree of type checking.
7
+ *
8
+ * @property string $name
9
+ * @property string|null version
10
+ * @property string $downloadUrl
11
+ * @property string $updated
12
+ *
13
+ * @property string|null $changelog
14
+ * @property int|null $downloadCount
15
+ */
16
+ class Puc_v4p2_Vcs_Reference {
17
+ private $properties = array();
18
+
19
+ public function __construct($properties = array()) {
20
+ $this->properties = $properties;
21
+ }
22
+
23
+ /**
24
+ * @param string $name
25
+ * @return mixed|null
26
+ */
27
+ public function __get($name) {
28
+ return array_key_exists($name, $this->properties) ? $this->properties[$name] : null;
29
+ }
30
+
31
+ /**
32
+ * @param string $name
33
+ * @param mixed $value
34
+ */
35
+ public function __set($name, $value) {
36
+ $this->properties[$name] = $value;
37
+ }
38
+
39
+ /**
40
+ * @param string $name
41
+ * @return bool
42
+ */
43
+ public function __isset($name) {
44
+ return isset($this->properties[$name]);
45
+ }
46
+
47
+ }
48
+
49
+ endif;
admin/update-checker/Puc/v4p2/Vcs/ThemeUpdateChecker.php ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ if ( !class_exists('Puc_v4p2_Vcs_ThemeUpdateChecker', false) ):
4
+
5
+ class Puc_v4p2_Vcs_ThemeUpdateChecker extends Puc_v4p2_Theme_UpdateChecker implements Puc_v4p2_Vcs_BaseChecker {
6
+ /**
7
+ * @var string The branch where to look for updates. Defaults to "master".
8
+ */
9
+ protected $branch = 'master';
10
+
11
+ /**
12
+ * @var Puc_v4p2_Vcs_Api Repository API client.
13
+ */
14
+ protected $api = null;
15
+
16
+ /**
17
+ * Puc_v4p2_Vcs_ThemeUpdateChecker constructor.
18
+ *
19
+ * @param Puc_v4p2_Vcs_Api $api
20
+ * @param null $stylesheet
21
+ * @param null $customSlug
22
+ * @param int $checkPeriod
23
+ * @param string $optionName
24
+ */
25
+ public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
26
+ $this->api = $api;
27
+ $this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
28
+
29
+ parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName);
30
+ }
31
+
32
+ public function requestUpdate() {
33
+ $api = $this->api;
34
+
35
+ $update = new Puc_v4p2_Theme_Update();
36
+ $update->slug = $this->slug;
37
+
38
+ //Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
39
+ $updateSource = $api->chooseReference($this->branch);
40
+ if ( $updateSource ) {
41
+ $ref = $updateSource->name;
42
+ $update->download_url = $updateSource->downloadUrl;
43
+ } else {
44
+ $ref = $this->branch;
45
+ }
46
+
47
+ //Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata
48
+ //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
49
+ $remoteHeader = $this->getFileHeader($api->getRemoteFile('style.css', $ref));
50
+ $update->version = Puc_v4p2_Utils::findNotEmpty(array(
51
+ $remoteHeader['Version'],
52
+ Puc_v4p2_Utils::get($updateSource, 'version'),
53
+ ));
54
+
55
+ //The details URL defaults to the Theme URI header or the repository URL.
56
+ $update->details_url = Puc_v4p2_Utils::findNotEmpty(array(
57
+ $remoteHeader['ThemeURI'],
58
+ $this->theme->get('ThemeURI'),
59
+ $this->metadataUrl,
60
+ ));
61
+
62
+ if ( empty($update->version) ) {
63
+ //It looks like we didn't find a valid update after all.
64
+ $update = null;
65
+ }
66
+
67
+ $update = $this->filterUpdateResult($update);
68
+ return $update;
69
+ }
70
+
71
+ //FIXME: This is duplicated code. Both theme and plugin subclasses that use VCS share these methods.
72
+
73
+ public function setBranch($branch) {
74
+ $this->branch = $branch;
75
+ return $this;
76
+ }
77
+
78
+ public function setAuthentication($credentials) {
79
+ $this->api->setAuthentication($credentials);
80
+ return $this;
81
+ }
82
+
83
+ public function getUpdate() {
84
+ $update = parent::getUpdate();
85
+
86
+ if ( isset($update) && !empty($update->download_url) ) {
87
+ $update->download_url = $this->api->signDownloadUrl($update->download_url);
88
+ }
89
+
90
+ return $update;
91
+ }
92
+
93
+ public function onDisplayConfiguration($panel) {
94
+ parent::onDisplayConfiguration($panel);
95
+ $panel->row('Branch', $this->branch);
96
+ $panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
97
+ $panel->row('API client', get_class($this->api));
98
+ }
99
+ }
100
+
101
+ endif;
admin/update-checker/css/puc-debug-bar.css DELETED
@@ -1,62 +0,0 @@
1
- .puc-debug-bar-panel pre {
2
- margin-top: 0;
3
- }
4
-
5
- /* Style the debug data table to match "widefat" table style used by WordPress. */
6
- table.puc-debug-data {
7
- width: 100%;
8
- clear: both;
9
- margin: 0;
10
-
11
- border-spacing: 0;
12
- background-color: #f9f9f9;
13
-
14
- border-radius: 3px;
15
- border: 1px solid #dfdfdf;
16
- border-collapse: separate;
17
- }
18
-
19
- table.puc-debug-data * {
20
- word-wrap: break-word;
21
- }
22
-
23
- table.puc-debug-data th {
24
- width: 11em;
25
- padding: 7px 7px 8px;
26
- text-align: left;
27
-
28
- font-family: "Georgia", "Times New Roman", "Bitstream Charter", "Times", serif;
29
- font-weight: 400;
30
- font-size: 14px;
31
- line-height: 1.3em;
32
- text-shadow: rgba(255, 255, 255, 0.804) 0 1px 0;
33
- }
34
-
35
- table.puc-debug-data td, table.puc-debug-data th {
36
- border-width: 1px 0;
37
- border-style: solid;
38
-
39
- border-top-color: #fff;
40
- border-bottom-color: #dfdfdf;
41
-
42
- text-transform: none;
43
- }
44
-
45
- table.puc-debug-data td {
46
- color: #555;
47
- font-size: 12px;
48
- padding: 4px 7px 2px;
49
- vertical-align: top;
50
- }
51
-
52
- .puc-ajax-response {
53
- border: 1px solid #dfdfdf;
54
- border-radius: 3px;
55
- padding: 0.5em;
56
- margin: 5px 0;
57
- background-color: white;
58
- }
59
-
60
- .puc-ajax-nonce {
61
- display: none;
62
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/debug-bar-panel.php DELETED
@@ -1,146 +0,0 @@
1
- <?php
2
-
3
- if ( !class_exists('PluginUpdateCheckerPanel', false) && class_exists('Debug_Bar_Panel', false) ) {
4
-
5
- /**
6
- * A Debug Bar panel for the plugin update checker.
7
- */
8
- class PluginUpdateCheckerPanel extends Debug_Bar_Panel {
9
- /** @var PluginUpdateChecker */
10
- private $updateChecker;
11
-
12
- private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
13
-
14
- public function __construct($updateChecker) {
15
- $this->updateChecker = $updateChecker;
16
- $title = sprintf(
17
- '<span id="puc-debug-menu-link-%s">PUC (%s)</span>',
18
- esc_attr($this->updateChecker->slug),
19
- $this->updateChecker->slug
20
- );
21
- parent::Debug_Bar_Panel($title);
22
- }
23
-
24
- public function render() {
25
- printf(
26
- '<div class="puc-debug-bar-panel" id="puc-debug-bar-panel_%1$s" data-slug="%1$s" data-nonce="%2$s">',
27
- esc_attr($this->updateChecker->slug),
28
- esc_attr(wp_create_nonce('puc-ajax'))
29
- );
30
-
31
- $this->displayConfiguration();
32
- $this->displayStatus();
33
- $this->displayCurrentUpdate();
34
-
35
- echo '</div>';
36
- }
37
-
38
- private function displayConfiguration() {
39
- echo '<h3>Configuration</h3>';
40
- echo '<table class="puc-debug-data">';
41
- $this->row('Plugin file', htmlentities($this->updateChecker->pluginFile));
42
- $this->row('Slug', htmlentities($this->updateChecker->slug));
43
- $this->row('DB option', htmlentities($this->updateChecker->optionName));
44
-
45
- $requestInfoButton = '';
46
- if ( function_exists('get_submit_button') ) {
47
- $requestInfoButton = get_submit_button('Request Info', 'secondary', 'puc-request-info-button', false, array('id' => 'puc-request-info-button-' . $this->updateChecker->slug));
48
- }
49
- $this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
50
-
51
- $scheduler = $this->updateChecker->scheduler;
52
- if ( $scheduler->checkPeriod > 0 ) {
53
- $this->row('Automatic checks', 'Every ' . $scheduler->checkPeriod . ' hours');
54
- } else {
55
- $this->row('Automatic checks', 'Disabled');
56
- }
57
-
58
- if ( isset($scheduler->throttleRedundantChecks) ) {
59
- if ( $scheduler->throttleRedundantChecks && ($scheduler->checkPeriod > 0) ) {
60
- $this->row(
61
- 'Throttling',
62
- sprintf(
63
- 'Enabled. If an update is already available, check for updates every %1$d hours instead of every %2$d hours.',
64
- $scheduler->throttledCheckPeriod,
65
- $scheduler->checkPeriod
66
- )
67
- );
68
- } else {
69
- $this->row('Throttling', 'Disabled');
70
- }
71
- }
72
- echo '</table>';
73
- }
74
-
75
- private function displayStatus() {
76
- echo '<h3>Status</h3>';
77
- echo '<table class="puc-debug-data">';
78
- $state = $this->updateChecker->getUpdateState();
79
- $checkNowButton = '';
80
- if ( function_exists('get_submit_button') ) {
81
- $checkNowButton = get_submit_button('Check Now', 'secondary', 'puc-check-now-button', false, array('id' => 'puc-check-now-button-' . $this->updateChecker->slug));
82
- }
83
-
84
- if ( isset($state, $state->lastCheck) ) {
85
- $this->row('Last check', $this->formatTimeWithDelta($state->lastCheck) . ' ' . $checkNowButton . $this->responseBox);
86
- } else {
87
- $this->row('Last check', 'Never');
88
- }
89
-
90
- $nextCheck = wp_next_scheduled($this->updateChecker->scheduler->getCronHookName());
91
- $this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck));
92
-
93
- if ( isset($state, $state->checkedVersion) ) {
94
- $this->row('Checked version', htmlentities($state->checkedVersion));
95
- $this->row('Cached update', $state->update);
96
- }
97
- $this->row('Update checker class', htmlentities(get_class($this->updateChecker)));
98
- echo '</table>';
99
- }
100
-
101
- private function displayCurrentUpdate() {
102
- $update = $this->updateChecker->getUpdate();
103
- if ( $update !== null ) {
104
- echo '<h3>An Update Is Available</h3>';
105
- echo '<table class="puc-debug-data">';
106
- $fields = array('version', 'download_url', 'slug', 'homepage', 'upgrade_notice');
107
- foreach($fields as $field) {
108
- $this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field));
109
- }
110
- echo '</table>';
111
- } else {
112
- echo '<h3>No updates currently available</h3>';
113
- }
114
- }
115
-
116
- private function formatTimeWithDelta($unixTime) {
117
- if ( empty($unixTime) ) {
118
- return 'Never';
119
- }
120
-
121
- $delta = time() - $unixTime;
122
- $result = human_time_diff(time(), $unixTime);
123
- if ( $delta < 0 ) {
124
- $result = 'after ' . $result;
125
- } else {
126
- $result = $result . ' ago';
127
- }
128
- $result .= ' (' . $this->formatTimestamp($unixTime) . ')';
129
- return $result;
130
- }
131
-
132
- private function formatTimestamp($unixTime) {
133
- return gmdate('Y-m-d H:i:s', $unixTime + (get_option('gmt_offset') * 3600));
134
- }
135
-
136
- private function row($name, $value) {
137
- if ( is_object($value) || is_array($value) ) {
138
- $value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
139
- } else if ($value === null) {
140
- $value = '<code>null</code>';
141
- }
142
- printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value);
143
- }
144
- }
145
-
146
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/debug-bar-plugin.php DELETED
@@ -1,102 +0,0 @@
1
- <?php
2
- if ( !class_exists('PucDebugBarPlugin', false) ) {
3
-
4
- class PucDebugBarPlugin {
5
- /** @var PluginUpdateChecker_3_0 */
6
- private $updateChecker;
7
-
8
- public function __construct($updateChecker) {
9
- $this->updateChecker = $updateChecker;
10
-
11
- add_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
12
- add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
13
-
14
- add_action('wp_ajax_puc_debug_check_now', array($this, 'ajaxCheckNow'));
15
- add_action('wp_ajax_puc_debug_request_info', array($this, 'ajaxRequestInfo'));
16
- }
17
-
18
- /**
19
- * Register the PUC Debug Bar panel.
20
- *
21
- * @param array $panels
22
- * @return array
23
- */
24
- public function addDebugBarPanel($panels) {
25
- require_once dirname(__FILE__) . '/debug-bar-panel.php';
26
- if ( current_user_can('update_plugins') && class_exists('PluginUpdateCheckerPanel', false) ) {
27
- $panels[] = new PluginUpdateCheckerPanel($this->updateChecker);
28
- }
29
- return $panels;
30
- }
31
-
32
- /**
33
- * Enqueue our Debug Bar scripts and styles.
34
- */
35
- public function enqueuePanelDependencies() {
36
- wp_enqueue_style(
37
- 'puc-debug-bar-style',
38
- plugins_url( "/css/puc-debug-bar.css", __FILE__ ),
39
- array('debug-bar'),
40
- '20130927'
41
- );
42
-
43
- wp_enqueue_script(
44
- 'puc-debug-bar-js',
45
- plugins_url( "/js/debug-bar.js", __FILE__ ),
46
- array('jquery'),
47
- '20121026'
48
- );
49
- }
50
-
51
- /**
52
- * Run an update check and output the result. Useful for making sure that
53
- * the update checking process works as expected.
54
- */
55
- public function ajaxCheckNow() {
56
- if ( $_POST['slug'] !== $this->updateChecker->slug ) {
57
- return;
58
- }
59
- $this->preAjaxReqest();
60
- $update = $this->updateChecker->checkForUpdates();
61
- if ( $update !== null ) {
62
- echo "An update is available:";
63
- echo '<pre>', htmlentities(print_r($update, true)), '</pre>';
64
- } else {
65
- echo 'No updates found.';
66
- }
67
- exit;
68
- }
69
-
70
- /**
71
- * Request plugin info and output it.
72
- */
73
- public function ajaxRequestInfo() {
74
- if ( $_POST['slug'] !== $this->updateChecker->slug ) {
75
- return;
76
- }
77
- $this->preAjaxReqest();
78
- $info = $this->updateChecker->requestInfo();
79
- if ( $info !== null ) {
80
- echo 'Successfully retrieved plugin info from the metadata URL:';
81
- echo '<pre>', htmlentities(print_r($info, true)), '</pre>';
82
- } else {
83
- echo 'Failed to retrieve plugin info from the metadata URL.';
84
- }
85
- exit;
86
- }
87
-
88
- /**
89
- * Check access permissions and enable error display (for debugging).
90
- */
91
- private function preAjaxReqest() {
92
- if ( !current_user_can('update_plugins') ) {
93
- die('Access denied');
94
- }
95
- check_ajax_referer('puc-ajax');
96
-
97
- error_reporting(E_ALL);
98
- @ini_set('display_errors','On');
99
- }
100
- }
101
-
102
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/github-checker.php DELETED
@@ -1,463 +0,0 @@
1
- <?php
2
-
3
- if ( !class_exists('PucGitHubChecker_3_0', false) ):
4
-
5
- class PucGitHubChecker_3_0 extends PluginUpdateChecker_3_0 {
6
- /**
7
- * @var string GitHub username.
8
- */
9
- protected $userName;
10
- /**
11
- * @var string GitHub repository name.
12
- */
13
- protected $repositoryName;
14
-
15
- /**
16
- * @var string Either a fully qualified repository URL, or just "user/repo-name".
17
- */
18
- protected $repositoryUrl;
19
-
20
- /**
21
- * @var string The branch to use as the latest version. Defaults to "master".
22
- */
23
- protected $branch;
24
-
25
- /**
26
- * @var string GitHub authentication token. Optional.
27
- */
28
- protected $accessToken;
29
-
30
- public function __construct(
31
- $repositoryUrl,
32
- $pluginFile,
33
- $branch = 'master',
34
- $checkPeriod = 12,
35
- $optionName = '',
36
- $muPluginFile = ''
37
- ) {
38
-
39
- $this->repositoryUrl = $repositoryUrl;
40
- $this->branch = empty($branch) ? 'master' : $branch;
41
-
42
- $path = @parse_url($repositoryUrl, PHP_URL_PATH);
43
- if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
44
- $this->userName = $matches['username'];
45
- $this->repositoryName = $matches['repository'];
46
- } else {
47
- throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
48
- }
49
-
50
- parent::__construct($repositoryUrl, $pluginFile, '', $checkPeriod, $optionName, $muPluginFile);
51
- }
52
-
53
- /**
54
- * Retrieve details about the latest plugin version from GitHub.
55
- *
56
- * @param array $unusedQueryArgs Unused.
57
- * @return PluginInfo_3_0
58
- */
59
- public function requestInfo($unusedQueryArgs = array()) {
60
- $info = new PluginInfo_3_0();
61
- $info->filename = $this->pluginFile;
62
- $info->slug = $this->slug;
63
- $info->sections = array();
64
-
65
- $this->setInfoFromHeader($this->getPluginHeader(), $info);
66
-
67
- //Figure out which reference (tag or branch) we'll use to get the latest version of the plugin.
68
- $ref = $this->branch;
69
- if ( $this->branch === 'master' ) {
70
- //Use the latest release.
71
- $release = $this->getLatestRelease();
72
- if ( $release !== null ) {
73
- $ref = $release->tag_name;
74
- $info->version = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
75
- $info->last_updated = $release->created_at;
76
- $info->download_url = $release->zipball_url;
77
-
78
- if ( !empty($release->body) ) {
79
- $info->sections['changelog'] = $this->parseMarkdown($release->body);
80
- }
81
- if ( isset($release->assets[0]) ) {
82
- $info->downloaded = $release->assets[0]->download_count;
83
- }
84
- } else {
85
- //Failing that, use the tag with the highest version number.
86
- $tag = $this->getLatestTag();
87
- if ( $tag !== null ) {
88
- $ref = $tag->name;
89
- $info->version = $tag->name;
90
- $info->download_url = $tag->zipball_url;
91
- }
92
- }
93
- }
94
-
95
- if ( empty($info->download_url) ) {
96
- $info->download_url = $this->buildArchiveDownloadUrl($ref);
97
- } else if ( !empty($this->accessToken) ) {
98
- $info->download_url = add_query_arg('access_token', $this->accessToken, $info->download_url);
99
- }
100
-
101
- //Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
102
- //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
103
- $mainPluginFile = basename($this->pluginFile);
104
- $remotePlugin = $this->getRemoteFile($mainPluginFile, $ref);
105
- if ( !empty($remotePlugin) ) {
106
- $remoteHeader = $this->getFileHeader($remotePlugin);
107
- $this->setInfoFromHeader($remoteHeader, $info);
108
- }
109
-
110
- //Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
111
- //a lot of useful information like the required/tested WP version, changelog, and so on.
112
- if ( $this->readmeTxtExistsLocally() ) {
113
- $this->setInfoFromRemoteReadme($ref, $info);
114
- }
115
-
116
- //The changelog might be in a separate file.
117
- if ( empty($info->sections['changelog']) ) {
118
- $info->sections['changelog'] = $this->getRemoteChangelog($ref);
119
- if ( empty($info->sections['changelog']) ) {
120
- $info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
121
- }
122
- }
123
-
124
- if ( empty($info->last_updated) ) {
125
- //Fetch the latest commit that changed the main plugin file and use it as the "last_updated" date.
126
- //It's reasonable to assume that every update will change the version number in that file.
127
- $latestCommit = $this->getLatestCommit($mainPluginFile, $ref);
128
- if ( $latestCommit !== null ) {
129
- $info->last_updated = $latestCommit->commit->author->date;
130
- }
131
- }
132
-
133
- $info = apply_filters('puc_request_info_result-' . $this->slug, $info, null);
134
- return $info;
135
- }
136
-
137
- /**
138
- * Get the latest release from GitHub.
139
- *
140
- * @return StdClass|null
141
- */
142
- protected function getLatestRelease() {
143
- $releases = $this->api('/repos/:user/:repo/releases');
144
- if ( is_wp_error($releases) || !is_array($releases) || !isset($releases[0]) ) {
145
- return null;
146
- }
147
-
148
- $latestRelease = $releases[0];
149
- return $latestRelease;
150
- }
151
-
152
- /**
153
- * Get the tag that looks like the highest version number.
154
- *
155
- * @return StdClass|null
156
- */
157
- protected function getLatestTag() {
158
- $tags = $this->api('/repos/:user/:repo/tags');
159
-
160
- if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
161
- return null;
162
- }
163
-
164
- usort($tags, array($this, 'compareTagNames')); //Sort from highest to lowest.
165
- return $tags[0];
166
- }
167
-
168
- /**
169
- * Compare two GitHub tags as if they were version number.
170
- *
171
- * @param string $tag1
172
- * @param string $tag2
173
- * @return int
174
- */
175
- protected function compareTagNames($tag1, $tag2) {
176
- if ( !isset($tag1->name) ) {
177
- return 1;
178
- }
179
- if ( !isset($tag2->name) ) {
180
- return -1;
181
- }
182
- return -version_compare($tag1->name, $tag2->name);
183
- }
184
-
185
- /**
186
- * Get the latest commit that changed the specified file.
187
- *
188
- * @param string $filename
189
- * @param string $ref Reference name (e.g. branch or tag).
190
- * @return StdClass|null
191
- */
192
- protected function getLatestCommit($filename, $ref = 'master') {
193
- $commits = $this->api(
194
- '/repos/:user/:repo/commits',
195
- array(
196
- 'path' => $filename,
197
- 'sha' => $ref,
198
- )
199
- );
200
- if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
201
- return $commits[0];
202
- }
203
- return null;
204
- }
205
-
206
- protected function getRemoteChangelog($ref = '') {
207
- $filename = $this->getChangelogFilename();
208
- if ( empty($filename) ) {
209
- return null;
210
- }
211
-
212
- $changelog = $this->getRemoteFile($filename, $ref);
213
- if ( $changelog === null ) {
214
- return null;
215
- }
216
- return $this->parseMarkdown($changelog);
217
- }
218
-
219
- protected function getChangelogFilename() {
220
- $pluginDirectory = dirname($this->pluginAbsolutePath);
221
- if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
222
- return null;
223
- }
224
-
225
- $possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
226
- $files = scandir($pluginDirectory);
227
- $foundNames = array_intersect($possibleNames, $files);
228
-
229
- if ( !empty($foundNames) ) {
230
- return reset($foundNames);
231
- }
232
- return null;
233
- }
234
-
235
- /**
236
- * Convert Markdown to HTML.
237
- *
238
- * @param string $markdown
239
- * @return string
240
- */
241
- protected function parseMarkdown($markdown) {
242
- if ( !class_exists('Parsedown', false) ) {
243
- require_once(dirname(__FILE__) . '/vendor/Parsedown.php');
244
- }
245
-
246
- $instance = Parsedown::instance();
247
- return $instance->text($markdown);
248
- }
249
-
250
- /**
251
- * Perform a GitHub API request.
252
- *
253
- * @param string $url
254
- * @param array $queryParams
255
- * @return mixed|WP_Error
256
- */
257
- protected function api($url, $queryParams = array()) {
258
- $variables = array(
259
- 'user' => $this->userName,
260
- 'repo' => $this->repositoryName,
261
- );
262
- foreach ($variables as $name => $value) {
263
- $url = str_replace('/:' . $name, '/' . urlencode($value), $url);
264
- }
265
- $url = 'https://api.github.com' . $url;
266
-
267
- if ( !empty($this->accessToken) ) {
268
- $queryParams['access_token'] = $this->accessToken;
269
- }
270
- if ( !empty($queryParams) ) {
271
- $url = add_query_arg($queryParams, $url);
272
- }
273
-
274
- $response = wp_remote_get($url, array('timeout' => 10));
275
- if ( is_wp_error($response) ) {
276
- return $response;
277
- }
278
-
279
- $code = wp_remote_retrieve_response_code($response);
280
- $body = wp_remote_retrieve_body($response);
281
- if ( $code === 200 ) {
282
- $document = json_decode($body);
283
- return $document;
284
- }
285
-
286
- return new WP_Error(
287
- 'puc-github-http-error',
288
- 'GitHub API error. HTTP status: ' . $code
289
- );
290
- }
291
-
292
- /**
293
- * Set the access token that will be used to make authenticated GitHub API requests.
294
- *
295
- * @param string $accessToken
296
- */
297
- public function setAccessToken($accessToken) {
298
- $this->accessToken = $accessToken;
299
- }
300
-
301
- /**
302
- * Get the contents of a file from a specific branch or tag.
303
- *
304
- * @param string $path File name.
305
- * @param string $ref
306
- * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
307
- */
308
- protected function getRemoteFile($path, $ref = 'master') {
309
- $apiUrl = '/repos/:user/:repo/contents/' . $path;
310
- $response = $this->api($apiUrl, array('ref' => $ref));
311
-
312
- if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
313
- return null;
314
- }
315
- return base64_decode($response->content);
316
- }
317
-
318
- /**
319
- * Parse plugin metadata from the header comment.
320
- * This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
321
- *
322
- * @param $content
323
- * @return array
324
- */
325
- protected function getFileHeader($content) {
326
- $headers = array(
327
- 'Name' => 'Plugin Name',
328
- 'PluginURI' => 'Plugin URI',
329
- 'Version' => 'Version',
330
- 'Description' => 'Description',
331
- 'Author' => 'Author',
332
- 'AuthorURI' => 'Author URI',
333
- 'TextDomain' => 'Text Domain',
334
- 'DomainPath' => 'Domain Path',
335
- 'Network' => 'Network',
336
-
337
- //The newest WordPress version that this plugin requires or has been tested with.
338
- //We support several different formats for compatibility with other libraries.
339
- 'Tested WP' => 'Tested WP',
340
- 'Requires WP' => 'Requires WP',
341
- 'Tested up to' => 'Tested up to',
342
- 'Requires at least' => 'Requires at least',
343
- );
344
-
345
- $content = str_replace("\r", "\n", $content); //Normalize line endings.
346
- $results = array();
347
- foreach ($headers as $field => $name) {
348
- $success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
349
- if ( ($success === 1) && $matches[1] ) {
350
- $results[$field] = _cleanup_header_comment($matches[1]);
351
- } else {
352
- $results[$field] = '';
353
- }
354
- }
355
-
356
- return $results;
357
- }
358
-
359
- /**
360
- * Copy plugin metadata from a file header to a PluginInfo object.
361
- *
362
- * @param array $fileHeader
363
- * @param PluginInfo_3_0 $pluginInfo
364
- */
365
- protected function setInfoFromHeader($fileHeader, $pluginInfo) {
366
- $headerToPropertyMap = array(
367
- 'Version' => 'version',
368
- 'Name' => 'name',
369
- 'PluginURI' => 'homepage',
370
- 'Author' => 'author',
371
- 'AuthorName' => 'author',
372
- 'AuthorURI' => 'author_homepage',
373
-
374
- 'Requires WP' => 'requires',
375
- 'Tested WP' => 'tested',
376
- 'Requires at least' => 'requires',
377
- 'Tested up to' => 'tested',
378
- );
379
- foreach ($headerToPropertyMap as $headerName => $property) {
380
- if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
381
- $pluginInfo->$property = $fileHeader[$headerName];
382
- }
383
- }
384
-
385
- if ( !isset($pluginInfo->sections) ) {
386
- $pluginInfo->sections = array();
387
- }
388
- if ( !empty($fileHeader['Description']) ) {
389
- $pluginInfo->sections['description'] = $fileHeader['Description'];
390
- }
391
- }
392
-
393
- /**
394
- * Copy plugin metadata from the remote readme.txt file.
395
- *
396
- * @param string $ref GitHub tag or branch where to look for the readme.
397
- * @param PluginInfo_3_0 $pluginInfo
398
- */
399
- protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
400
- $readmeTxt = $this->getRemoteFile('readme.txt', $ref);
401
- if ( empty($readmeTxt) ) {
402
- return;
403
- }
404
-
405
- $readme = $this->parseReadme($readmeTxt);
406
-
407
- if ( isset($readme['sections']) ) {
408
- $pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
409
- }
410
- if ( !empty($readme['tested_up_to']) ) {
411
- $pluginInfo->tested = $readme['tested_up_to'];
412
- }
413
- if ( !empty($readme['requires_at_least']) ) {
414
- $pluginInfo->requires = $readme['requires_at_least'];
415
- }
416
-
417
- if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
418
- $pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
419
- }
420
- }
421
-
422
- protected function parseReadme($content) {
423
- if ( !class_exists('PucReadmeParser', false) ) {
424
- require_once(dirname(__FILE__) . '/vendor/readme-parser.php');
425
- }
426
- $parser = new PucReadmeParser();
427
- return $parser->parse_readme_contents($content);
428
- }
429
-
430
- /**
431
- * Check if the currently installed version has a readme.txt file.
432
- *
433
- * @return bool
434
- */
435
- protected function readmeTxtExistsLocally() {
436
- $pluginDirectory = dirname($this->pluginAbsolutePath);
437
- if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
438
- return false;
439
- }
440
- return is_file($pluginDirectory . '/readme.txt');
441
- }
442
-
443
- /**
444
- * Generate a URL to download a ZIP archive of the specified branch/tag/etc.
445
- *
446
- * @param string $ref
447
- * @return string
448
- */
449
- protected function buildArchiveDownloadUrl($ref = 'master') {
450
- $url = sprintf(
451
- 'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
452
- urlencode($this->userName),
453
- urlencode($this->repositoryName),
454
- urlencode($ref)
455
- );
456
- if ( !empty($this->accessToken) ) {
457
- $url = add_query_arg('access_token', $this->accessToken, $url);
458
- }
459
- return $url;
460
- }
461
- }
462
-
463
- endif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/js/debug-bar.js DELETED
@@ -1,52 +0,0 @@
1
- jQuery(function($) {
2
-
3
- function runAjaxAction(button, action) {
4
- button = $(button);
5
- var panel = button.closest('.puc-debug-bar-panel');
6
- var responseBox = button.closest('td').find('.puc-ajax-response');
7
-
8
- responseBox.text('Processing...').show();
9
- $.post(
10
- ajaxurl,
11
- {
12
- action : action,
13
- slug : panel.data('slug'),
14
- _wpnonce: panel.data('nonce')
15
- },
16
- function(data) {
17
- responseBox.html(data);
18
- },
19
- 'html'
20
- );
21
- }
22
-
23
- $('.puc-debug-bar-panel input[name="puc-check-now-button"]').click(function() {
24
- runAjaxAction(this, 'puc_debug_check_now');
25
- return false;
26
- });
27
-
28
- $('.puc-debug-bar-panel input[name="puc-request-info-button"]').click(function() {
29
- runAjaxAction(this, 'puc_debug_request_info');
30
- return false;
31
- });
32
-
33
-
34
- // Debug Bar uses the panel class name as part of its link and container IDs. This means we can
35
- // end up with multiple identical IDs if more than one plugin uses the update checker library.
36
- // Fix it by replacing the class name with the plugin slug.
37
- var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel');
38
- panels.each(function(index) {
39
- var panel = $(this);
40
- var slug = panel.data('slug');
41
- var target = panel.closest('.debug-menu-target');
42
-
43
- //Change the panel wrapper ID.
44
- target.attr('id', 'debug-menu-target-puc-' + slug);
45
-
46
- //Change the menu link ID as well and point it at the new target ID.
47
- $('#puc-debug-menu-link-' + panel.data('slug'))
48
- .closest('.debug-menu-link')
49
- .attr('id', 'debug-menu-link-puc-' + slug)
50
- .attr('href', '#' + target.attr('id'));
51
- });
52
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/plugin-update-checker.php CHANGED
@@ -1,1494 +1,22 @@
1
- <?php
2
- /**
3
- * Plugin Update Checker Library 3.0
4
- * http://w-shadow.com/
5
- *
6
- * Copyright 2016 Janis Elsts
7
- * Released under the MIT license. See license.txt for details.
8
- */
9
-
10
- if ( !class_exists('PluginUpdateChecker_3_0', false) ):
11
-
12
- /**
13
- * A custom plugin update checker.
14
- *
15
- * @author Janis Elsts
16
- * @copyright 2016
17
- * @version 3.0
18
- * @access public
19
- */
20
- class PluginUpdateChecker_3_0 {
21
- public $metadataUrl = ''; //The URL of the plugin's metadata file.
22
- public $pluginAbsolutePath = ''; //Full path of the main plugin file.
23
- public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
24
- public $slug = ''; //Plugin slug.
25
- public $optionName = ''; //Where to store the update info.
26
- public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
27
-
28
- public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error()
29
- //and should be logged to the standard PHP error log.
30
- public $scheduler;
31
-
32
- protected $upgraderStatus;
33
-
34
- private $debugBarPlugin = null;
35
- private $cachedInstalledVersion = null;
36
-
37
- private $metadataHost = ''; //The host component of $metadataUrl.
38
-
39
- /**
40
- * Class constructor.
41
- *
42
- * @param string $metadataUrl The URL of the plugin's metadata file.
43
- * @param string $pluginFile Fully qualified path to the main plugin file.
44
- * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
45
- * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
46
- * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
47
- * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
48
- */
49
- public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
50
- $this->metadataUrl = $metadataUrl;
51
- $this->pluginAbsolutePath = $pluginFile;
52
- $this->pluginFile = plugin_basename($this->pluginAbsolutePath);
53
- $this->muPluginFile = $muPluginFile;
54
- $this->slug = $slug;
55
- $this->optionName = $optionName;
56
- $this->debugMode = (bool)(constant('WP_DEBUG'));
57
-
58
- //If no slug is specified, use the name of the main plugin file as the slug.
59
- //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
60
- if ( empty($this->slug) ){
61
- $this->slug = basename($this->pluginFile, '.php');
62
- }
63
-
64
- if ( empty($this->optionName) ){
65
- $this->optionName = 'external_updates-' . $this->slug;
66
- }
67
-
68
- //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
69
- //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
70
- if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
71
- $this->muPluginFile = $this->pluginFile;
72
- }
73
-
74
- $this->scheduler = $this->createScheduler($checkPeriod);
75
- $this->upgraderStatus = new PucUpgraderStatus_3_0();
76
-
77
- $this->installHooks();
78
- }
79
-
80
- /**
81
- * Create an instance of the scheduler.
82
- *
83
- * This is implemented as a method to make it possible for plugins to subclass the update checker
84
- * and substitute their own scheduler.
85
- *
86
- * @param int $checkPeriod
87
- * @return PucScheduler_3_0
88
- */
89
- protected function createScheduler($checkPeriod) {
90
- return new PucScheduler_3_0($this, $checkPeriod);
91
- }
92
-
93
- /**
94
- * Install the hooks required to run periodic update checks and inject update info
95
- * into WP data structures.
96
- *
97
- * @return void
98
- */
99
- protected function installHooks(){
100
- //Override requests for plugin information
101
- add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
102
-
103
- //Insert our update info into the update array maintained by WP
104
- add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+
105
- add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+
106
-
107
- add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
108
- add_action('admin_init', array($this, 'handleManualCheck'));
109
- add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
110
-
111
- //Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
112
- add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
113
- add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
114
-
115
- if ( did_action('plugins_loaded') ) {
116
- $this->initDebugBarPanel();
117
- } else {
118
- add_action('plugins_loaded', array($this, 'initDebugBarPanel'));
119
- }
120
-
121
- //Rename the update directory to be the same as the existing directory.
122
- add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
123
-
124
- //Enable language support (i18n).
125
- load_plugin_textdomain('plugin-update-checker', false, plugin_basename(dirname(__FILE__)) . '/languages');
126
-
127
- //Allow HTTP requests to the metadata URL even if it's on a local host.
128
- $this->metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
129
- add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
130
- }
131
-
132
- /**
133
- * Explicitly allow HTTP requests to the metadata URL.
134
- *
135
- * WordPress has a security feature where the HTTP API will reject all requests that are sent to
136
- * another site hosted on the same server as the current site (IP match), a local host, or a local
137
- * IP, unless the host exactly matches the current site.
138
- *
139
- * This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
140
- *
141
- * That can be a problem when you're developing your plugin and you decide to host the update information
142
- * on the same server as your test site. Update requests will mysteriously fail.
143
- *
144
- * We fix that by adding an exception for the metadata host.
145
- *
146
- * @param bool $allow
147
- * @param string $host
148
- * @return bool
149
- */
150
- public function allowMetadataHost($allow, $host) {
151
- if ( strtolower($host) === strtolower($this->metadataHost) ) {
152
- return true;
153
- }
154
- return $allow;
155
- }
156
-
157
- /**
158
- * Retrieve plugin info from the configured API endpoint.
159
- *
160
- * @uses wp_remote_get()
161
- *
162
- * @param array $queryArgs Additional query arguments to append to the request. Optional.
163
- * @return PluginInfo_3_0
164
- */
165
- public function requestInfo($queryArgs = array()){
166
- //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
167
- $installedVersion = $this->getInstalledVersion();
168
- $queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
169
- $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs);
170
-
171
- //Various options for the wp_remote_get() call. Plugins can filter these, too.
172
- $options = array(
173
- 'timeout' => 10, //seconds
174
- 'headers' => array(
175
- 'Accept' => 'application/json'
176
- ),
177
- );
178
- $options = apply_filters('puc_request_info_options-'.$this->slug, $options);
179
-
180
- //The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
181
- $url = $this->metadataUrl;
182
- if ( !empty($queryArgs) ){
183
- $url = add_query_arg($queryArgs, $url);
184
- }
185
-
186
- $result = wp_remote_get(
187
- $url,
188
- $options
189
- );
190
-
191
- //Try to parse the response
192
- $status = $this->validateApiResponse($result);
193
- $pluginInfo = null;
194
- if ( !is_wp_error($status) ){
195
- $pluginInfo = PluginInfo_3_0::fromJson($result['body']);
196
- if ( $pluginInfo !== null ) {
197
- $pluginInfo->filename = $this->pluginFile;
198
- $pluginInfo->slug = $this->slug;
199
- }
200
- } else {
201
- $this->triggerError(
202
- sprintf('The URL %s does not point to a valid plugin metadata file. ', $url)
203
- . $status->get_error_message(),
204
- E_USER_WARNING
205
- );
206
- }
207
-
208
- $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
209
- return $pluginInfo;
210
- }
211
-
212
- /**
213
- * Check if $result is a successful update API response.
214
- *
215
- * @param array|WP_Error $result
216
- * @return true|WP_Error
217
- */
218
- private function validateApiResponse($result) {
219
- if ( is_wp_error($result) ) { /** @var WP_Error $result */
220
- return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
221
- }
222
-
223
- if ( !isset($result['response']['code']) ) {
224
- return new WP_Error('puc_no_response_code', 'wp_remote_get() returned an unexpected result.');
225
- }
226
-
227
- if ( $result['response']['code'] !== 200 ) {
228
- return new WP_Error(
229
- 'puc_unexpected_response_code',
230
- 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
231
- );
232
- }
233
-
234
- if ( empty($result['body']) ) {
235
- return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
236
- }
237
-
238
- return true;
239
- }
240
-
241
- /**
242
- * Retrieve the latest update (if any) from the configured API endpoint.
243
- *
244
- * @uses PluginUpdateChecker::requestInfo()
245
- *
246
- * @return PluginUpdate_3_0 An instance of PluginUpdate, or NULL when no updates are available.
247
- */
248
- public function requestUpdate(){
249
- //For the sake of simplicity, this function just calls requestInfo()
250
- //and transforms the result accordingly.
251
- $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
252
- if ( $pluginInfo == null ){
253
- return null;
254
- }
255
- return PluginUpdate_3_0::fromPluginInfo($pluginInfo);
256
- }
257
-
258
- /**
259
- * Get the currently installed version of the plugin.
260
- *
261
- * @return string Version number.
262
- */
263
- public function getInstalledVersion(){
264
- if ( isset($this->cachedInstalledVersion) ) {
265
- return $this->cachedInstalledVersion;
266
- }
267
-
268
- $pluginHeader = $this->getPluginHeader();
269
- if ( isset($pluginHeader['Version']) ) {
270
- $this->cachedInstalledVersion = $pluginHeader['Version'];
271
- return $pluginHeader['Version'];
272
- } else {
273
- //This can happen if the filename points to something that is not a plugin.
274
- $this->triggerError(
275
- sprintf(
276
- "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
277
- $this->pluginFile
278
- ),
279
- E_USER_WARNING
280
- );
281
- return null;
282
- }
283
- }
284
-
285
- /**
286
- * Get plugin's metadata from its file header.
287
- *
288
- * @return array
289
- */
290
- protected function getPluginHeader() {
291
- if ( !is_file($this->pluginAbsolutePath) ) {
292
- //This can happen if the plugin filename is wrong.
293
- $this->triggerError(
294
- sprintf(
295
- "Can't to read the plugin header for '%s'. The file does not exist.",
296
- $this->pluginFile
297
- ),
298
- E_USER_WARNING
299
- );
300
- return array();
301
- }
302
-
303
- if ( !function_exists('get_plugin_data') ){
304
- /** @noinspection PhpIncludeInspection */
305
- require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
306
- }
307
- return get_plugin_data($this->pluginAbsolutePath, false, false);
308
- }
309
-
310
- /**
311
- * Check for plugin updates.
312
- * The results are stored in the DB option specified in $optionName.
313
- *
314
- * @return PluginUpdate_3_0|null
315
- */
316
- public function checkForUpdates(){
317
- $installedVersion = $this->getInstalledVersion();
318
- //Fail silently if we can't find the plugin or read its header.
319
- if ( $installedVersion === null ) {
320
- $this->triggerError(
321
- sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile),
322
- E_USER_WARNING
323
- );
324
- return null;
325
- }
326
-
327
- $state = $this->getUpdateState();
328
- if ( empty($state) ){
329
- $state = new StdClass;
330
- $state->lastCheck = 0;
331
- $state->checkedVersion = '';
332
- $state->update = null;
333
- }
334
-
335
- $state->lastCheck = time();
336
- $state->checkedVersion = $installedVersion;
337
- $this->setUpdateState($state); //Save before checking in case something goes wrong
338
-
339
- $state->update = $this->requestUpdate();
340
- $this->setUpdateState($state);
341
-
342
- return $this->getUpdate();
343
- }
344
-
345
- /**
346
- * Load the update checker state from the DB.
347
- *
348
- * @return StdClass|null
349
- */
350
- public function getUpdateState() {
351
- $state = get_site_option($this->optionName, null);
352
- if ( empty($state) || !is_object($state)) {
353
- $state = null;
354
- }
355
-
356
- if ( !empty($state) && isset($state->update) && is_object($state->update) ){
357
- $state->update = PluginUpdate_3_0::fromObject($state->update);
358
- }
359
- return $state;
360
- }
361
-
362
-
363
- /**
364
- * Persist the update checker state to the DB.
365
- *
366
- * @param StdClass $state
367
- * @return void
368
- */
369
- private function setUpdateState($state) {
370
- if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) {
371
- $update = $state->update; /** @var PluginUpdate_3_0 $update */
372
- $state->update = $update->toStdClass();
373
- }
374
- update_site_option($this->optionName, $state);
375
- }
376
-
377
- /**
378
- * Reset update checker state - i.e. last check time, cached update data and so on.
379
- *
380
- * Call this when your plugin is being uninstalled, or if you want to
381
- * clear the update cache.
382
- */
383
- public function resetUpdateState() {
384
- delete_site_option($this->optionName);
385
- }
386
-
387
- /**
388
- * Intercept plugins_api() calls that request information about our plugin and
389
- * use the configured API endpoint to satisfy them.
390
- *
391
- * @see plugins_api()
392
- *
393
- * @param mixed $result
394
- * @param string $action
395
- * @param array|object $args
396
- * @return mixed
397
- */
398
- public function injectInfo($result, $action = null, $args = null){
399
- $relevant = ($action == 'plugin_information') && isset($args->slug) && (
400
- ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
401
- );
402
- if ( !$relevant ){
403
- return $result;
404
- }
405
-
406
- $pluginInfo = $this->requestInfo();
407
- $pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo);
408
- if ($pluginInfo){
409
- return $pluginInfo->toWpFormat();
410
- }
411
-
412
- return $result;
413
- }
414
-
415
- /**
416
- * Insert the latest update (if any) into the update list maintained by WP.
417
- *
418
- * @param StdClass $updates Update list.
419
- * @return StdClass Modified update list.
420
- */
421
- public function injectUpdate($updates){
422
- //Is there an update to insert?
423
- $update = $this->getUpdate();
424
-
425
- //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
426
- //is usually different from the main plugin file so the update wouldn't show up properly anyway.
427
- if ( $this->isUnknownMuPlugin() ) {
428
- $update = null;
429
- }
430
-
431
- if ( !empty($update) ) {
432
- //Let plugins filter the update info before it's passed on to WordPress.
433
- $update = apply_filters('puc_pre_inject_update-' . $this->slug, $update);
434
- $updates = $this->addUpdateToList($updates, $update);
435
- } else {
436
- //Clean up any stale update info.
437
- $updates = $this->removeUpdateFromList($updates);
438
- }
439
-
440
- return $updates;
441
- }
442
-
443
- /**
444
- * @param StdClass|null $updates
445
- * @param PluginUpdate_3_0 $updateToAdd
446
- * @return StdClass
447
- */
448
- private function addUpdateToList($updates, $updateToAdd) {
449
- if ( !is_object($updates) ) {
450
- $updates = new StdClass();
451
- $updates->response = array();
452
- }
453
-
454
- $wpUpdate = $updateToAdd->toWpFormat();
455
- $pluginFile = $this->pluginFile;
456
-
457
- if ( $this->isMuPlugin() ) {
458
- //WP does not support automatic update installation for mu-plugins, but we can still display a notice.
459
- $wpUpdate->package = null;
460
- $pluginFile = $this->muPluginFile;
461
- }
462
- $updates->response[$pluginFile] = $wpUpdate;
463
- return $updates;
464
- }
465
-
466
- /**
467
- * @param StdClass|null $updates
468
- * @return StdClass|null
469
- */
470
- private function removeUpdateFromList($updates) {
471
- if ( isset($updates, $updates->response) ) {
472
- unset($updates->response[$this->pluginFile]);
473
- if ( !empty($this->muPluginFile) ) {
474
- unset($updates->response[$this->muPluginFile]);
475
- }
476
- }
477
- return $updates;
478
- }
479
-
480
- /**
481
- * Rename the update directory to match the existing plugin directory.
482
- *
483
- * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
484
- * exactly one directory, and that the directory name will be the same as the directory where
485
- * the plugin/theme is currently installed.
486
- *
487
- * GitHub and other repositories provide ZIP downloads, but they often use directory names like
488
- * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
489
- *
490
- * This is a hook callback. Don't call it from a plugin.
491
- *
492
- * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource.
493
- * @param string $remoteSource WordPress has extracted the update to this directory.
494
- * @param WP_Upgrader $upgrader
495
- * @return string|WP_Error
496
- */
497
- public function fixDirectoryName($source, $remoteSource, $upgrader) {
498
- global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
499
-
500
- //Basic sanity checks.
501
- if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
502
- return $source;
503
- }
504
-
505
- //If WordPress is upgrading anything other than our plugin, leave the directory name unchanged.
506
- if ( !$this->isPluginBeingUpgraded($upgrader) ) {
507
- return $source;
508
- }
509
-
510
- //Rename the source to match the existing plugin directory.
511
- $pluginDirectoryName = dirname($this->pluginFile);
512
- if ( $pluginDirectoryName === '.' ) {
513
- return $source;
514
- }
515
- $correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/';
516
- if ( $source !== $correctedSource ) {
517
- //The update archive should contain a single directory that contains the rest of plugin files. Otherwise,
518
- //WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename
519
- //$remoteSource because that would break WordPress code that cleans up temporary files after update.
520
- if ( $this->isBadDirectoryStructure($remoteSource) ) {
521
- return new WP_Error(
522
- 'puc-incorrect-directory-structure',
523
- sprintf(
524
- 'The directory structure of the update is incorrect. All plugin files should be inside ' .
525
- 'a directory named <span class="code">%s</span>, not at the root of the ZIP file.',
526
- htmlentities($this->slug)
527
- )
528
- );
529
- }
530
-
531
- /** @var WP_Upgrader_Skin $upgrader->skin */
532
- $upgrader->skin->feedback(sprintf(
533
- 'Renaming %s to %s&#8230;',
534
- '<span class="code">' . basename($source) . '</span>',
535
- '<span class="code">' . $pluginDirectoryName . '</span>'
536
- ));
537
-
538
- if ( $wp_filesystem->move($source, $correctedSource, true) ) {
539
- $upgrader->skin->feedback('Plugin directory successfully renamed.');
540
- return $correctedSource;
541
- } else {
542
- return new WP_Error(
543
- 'puc-rename-failed',
544
- 'Unable to rename the update to match the existing plugin directory.'
545
- );
546
- }
547
- }
548
-
549
- return $source;
550
- }
551
-
552
- /**
553
- * Check for incorrect update directory structure. An update must contain a single directory,
554
- * all other files should be inside that directory.
555
- *
556
- * @param string $remoteSource Directory path.
557
- * @return bool
558
- */
559
- private function isBadDirectoryStructure($remoteSource) {
560
- global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */
561
-
562
- $sourceFiles = $wp_filesystem->dirlist($remoteSource);
563
- if ( is_array($sourceFiles) ) {
564
- $sourceFiles = array_keys($sourceFiles);
565
- $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
566
- return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
567
- }
568
-
569
- //Assume it's fine.
570
- return false;
571
- }
572
-
573
- /**
574
- * Is there and update being installed RIGHT NOW, for this specific plugin?
575
- *
576
- * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
577
- * @return bool
578
- */
579
- public function isPluginBeingUpgraded($upgrader = null) {
580
- return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
581
- }
582
-
583
- /**
584
- * Get the details of the currently available update, if any.
585
- *
586
- * If no updates are available, or if the last known update version is below or equal
587
- * to the currently installed version, this method will return NULL.
588
- *
589
- * Uses cached update data. To retrieve update information straight from
590
- * the metadata URL, call requestUpdate() instead.
591
- *
592
- * @return PluginUpdate_3_0|null
593
- */
594
- public function getUpdate() {
595
- $state = $this->getUpdateState(); /** @var StdClass $state */
596
-
597
- //Is there an update available insert?
598
- if ( !empty($state) && isset($state->update) && !empty($state->update) ){
599
- $update = $state->update;
600
- //Check if the update is actually newer than the currently installed version.
601
- $installedVersion = $this->getInstalledVersion();
602
- if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
603
- $update->filename = $this->pluginFile;
604
- return $update;
605
- }
606
- }
607
- return null;
608
- }
609
-
610
- /**
611
- * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
612
- * the new link will appear after the "Visit plugin site" link.
613
- *
614
- * You can change the link text by using the "puc_manual_check_link-$slug" filter.
615
- * Returning an empty string from the filter will disable the link.
616
- *
617
- * @param array $pluginMeta Array of meta links.
618
- * @param string $pluginFile
619
- * @return array
620
- */
621
- public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
622
- $isRelevant = ($pluginFile == $this->pluginFile)
623
- || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
624
-
625
- if ( $isRelevant && current_user_can('update_plugins') ) {
626
- $linkUrl = wp_nonce_url(
627
- add_query_arg(
628
- array(
629
- 'puc_check_for_updates' => 1,
630
- 'puc_slug' => $this->slug,
631
- ),
632
- self_admin_url('plugins.php')
633
- ),
634
- 'puc_check_for_updates'
635
- );
636
-
637
- $linkText = apply_filters('puc_manual_check_link-' . $this->slug, __('Check for updates', 'plugin-update-checker'));
638
- if ( !empty($linkText) ) {
639
- $pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
640
- }
641
- }
642
- return $pluginMeta;
643
- }
644
-
645
- /**
646
- * Check for updates when the user clicks the "Check for updates" link.
647
- * @see self::addCheckForUpdatesLink()
648
- *
649
- * @return void
650
- */
651
- public function handleManualCheck() {
652
- $shouldCheck =
653
- isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
654
- && $_GET['puc_slug'] == $this->slug
655
- && current_user_can('update_plugins')
656
- && check_admin_referer('puc_check_for_updates');
657
-
658
- if ( $shouldCheck ) {
659
- $update = $this->checkForUpdates();
660
- $status = ($update === null) ? 'no_update' : 'update_available';
661
- wp_redirect(add_query_arg(
662
- array(
663
- 'puc_update_check_result' => $status,
664
- 'puc_slug' => $this->slug,
665
- ),
666
- self_admin_url('plugins.php')
667
- ));
668
- }
669
- }
670
-
671
- /**
672
- * Display the results of a manual update check.
673
- * @see self::handleManualCheck()
674
- *
675
- * You can change the result message by using the "puc_manual_check_message-$slug" filter.
676
- */
677
- public function displayManualCheckResult() {
678
- if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
679
- $status = strval($_GET['puc_update_check_result']);
680
- if ( $status == 'no_update' ) {
681
- $message = __('This plugin is up to date.', 'plugin-update-checker');
682
- } else if ( $status == 'update_available' ) {
683
- $message = __('A new version of this plugin is available.', 'plugin-update-checker');
684
- } else {
685
- $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
686
- }
687
- printf(
688
- '<div class="updated notice is-dismissible"><p>%s</p></div>',
689
- apply_filters('puc_manual_check_message-' . $this->slug, $message, $status)
690
- );
691
- }
692
- }
693
-
694
- /**
695
- * Check if the plugin file is inside the mu-plugins directory.
696
- *
697
- * @return bool
698
- */
699
- protected function isMuPlugin() {
700
- static $cachedResult = null;
701
-
702
- if ( $cachedResult === null ) {
703
- //Convert both paths to the canonical form before comparison.
704
- $muPluginDir = realpath(WPMU_PLUGIN_DIR);
705
- $pluginPath = realpath($this->pluginAbsolutePath);
706
-
707
- $cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
708
- }
709
-
710
- return $cachedResult;
711
- }
712
-
713
- /**
714
- * MU plugins are partially supported, but only when we know which file in mu-plugins
715
- * corresponds to this plugin.
716
- *
717
- * @return bool
718
- */
719
- protected function isUnknownMuPlugin() {
720
- return empty($this->muPluginFile) && $this->isMuPlugin();
721
- }
722
-
723
- /**
724
- * Clear the cached plugin version. This method can be set up as a filter (hook) and will
725
- * return the filter argument unmodified.
726
- *
727
- * @param mixed $filterArgument
728
- * @return mixed
729
- */
730
- public function clearCachedVersion($filterArgument = null) {
731
- $this->cachedInstalledVersion = null;
732
- return $filterArgument;
733
- }
734
-
735
- /**
736
- * Register a callback for filtering query arguments.
737
- *
738
- * The callback function should take one argument - an associative array of query arguments.
739
- * It should return a modified array of query arguments.
740
- *
741
- * @uses add_filter() This method is a convenience wrapper for add_filter().
742
- *
743
- * @param callable $callback
744
- * @return void
745
- */
746
- public function addQueryArgFilter($callback){
747
- add_filter('puc_request_info_query_args-'.$this->slug, $callback);
748
- }
749
-
750
- /**
751
- * Register a callback for filtering arguments passed to wp_remote_get().
752
- *
753
- * The callback function should take one argument - an associative array of arguments -
754
- * and return a modified array or arguments. See the WP documentation on wp_remote_get()
755
- * for details on what arguments are available and how they work.
756
- *
757
- * @uses add_filter() This method is a convenience wrapper for add_filter().
758
- *
759
- * @param callable $callback
760
- * @return void
761
- */
762
- public function addHttpRequestArgFilter($callback){
763
- add_filter('puc_request_info_options-'.$this->slug, $callback);
764
- }
765
-
766
- /**
767
- * Register a callback for filtering the plugin info retrieved from the external API.
768
- *
769
- * The callback function should take two arguments. If the plugin info was retrieved
770
- * successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
771
- * it will be NULL. The second argument will be the corresponding return value of
772
- * wp_remote_get (see WP docs for details).
773
- *
774
- * The callback function should return a new or modified instance of PluginInfo or NULL.
775
- *
776
- * @uses add_filter() This method is a convenience wrapper for add_filter().
777
- *
778
- * @param callable $callback
779
- * @return void
780
- */
781
- public function addResultFilter($callback){
782
- add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2);
783
- }
784
-
785
- /**
786
- * Register a callback for one of the update checker filters.
787
- *
788
- * Identical to add_filter(), except it automatically adds the "puc_" prefix
789
- * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result"
790
- * becomes "puc_request_info_result-your_plugin_slug".
791
- *
792
- * @param string $tag
793
- * @param callable $callback
794
- * @param int $priority
795
- * @param int $acceptedArgs
796
- */
797
- public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
798
- add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs);
799
- }
800
-
801
- /**
802
- * Initialize the update checker Debug Bar plugin/add-on thingy.
803
- */
804
- public function initDebugBarPanel() {
805
- $debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php';
806
- if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) {
807
- /** @noinspection PhpIncludeInspection */
808
- require_once $debugBarPlugin;
809
- $this->debugBarPlugin = new PucDebugBarPlugin($this);
810
- }
811
- }
812
-
813
- /**
814
- * Trigger a PHP error, but only when $debugMode is enabled.
815
- *
816
- * @param string $message
817
- * @param int $errorType
818
- */
819
- protected function triggerError($message, $errorType) {
820
- if ( $this->debugMode ) {
821
- trigger_error($message, $errorType);
822
- }
823
- }
824
- }
825
-
826
- endif;
827
-
828
- if ( !class_exists('PluginInfo_3_0', false) ):
829
-
830
- /**
831
- * A container class for holding and transforming various plugin metadata.
832
- *
833
- * @author Janis Elsts
834
- * @copyright 2016
835
- * @version 3.0
836
- * @access public
837
- */
838
- class PluginInfo_3_0 {
839
- //Most fields map directly to the contents of the plugin's info.json file.
840
- //See the relevant docs for a description of their meaning.
841
- public $name;
842
- public $slug;
843
- public $version;
844
- public $homepage;
845
- public $sections;
846
- public $banners;
847
- public $download_url;
848
-
849
- public $author;
850
- public $author_homepage;
851
-
852
- public $requires;
853
- public $tested;
854
- public $upgrade_notice;
855
-
856
- public $rating;
857
- public $num_ratings;
858
- public $downloaded;
859
- public $active_installs;
860
- public $last_updated;
861
-
862
- public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
863
-
864
- public $filename; //Plugin filename relative to the plugins directory.
865
-
866
- /**
867
- * Create a new instance of PluginInfo from JSON-encoded plugin info
868
- * returned by an external update API.
869
- *
870
- * @param string $json Valid JSON string representing plugin info.
871
- * @return PluginInfo_3_0|null New instance of PluginInfo, or NULL on error.
872
- */
873
- public static function fromJson($json){
874
- /** @var StdClass $apiResponse */
875
- $apiResponse = json_decode($json);
876
- if ( empty($apiResponse) || !is_object($apiResponse) ){
877
- trigger_error(
878
- "Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/",
879
- E_USER_NOTICE
880
- );
881
- return null;
882
- }
883
-
884
- $valid = self::validateMetadata($apiResponse);
885
- if ( is_wp_error($valid) ){
886
- trigger_error($valid->get_error_message(), E_USER_NOTICE);
887
- return null;
888
- }
889
-
890
- $info = new self();
891
- foreach(get_object_vars($apiResponse) as $key => $value){
892
- $info->$key = $value;
893
- }
894
-
895
- //json_decode decodes assoc. arrays as objects. We want it as an array.
896
- $info->sections = (array)$info->sections;
897
-
898
- return $info;
899
- }
900
-
901
- /**
902
- * Very, very basic validation.
903
- *
904
- * @param StdClass $apiResponse
905
- * @return bool|WP_Error
906
- */
907
- protected static function validateMetadata($apiResponse) {
908
- if (
909
- !isset($apiResponse->name, $apiResponse->version)
910
- || empty($apiResponse->name)
911
- || empty($apiResponse->version)
912
- ) {
913
- return new WP_Error(
914
- 'puc-invalid-metadata',
915
- "The plugin metadata file does not contain the required 'name' and/or 'version' keys."
916
- );
917
- }
918
- return true;
919
- }
920
-
921
-
922
- /**
923
- * Transform plugin info into the format used by the native WordPress.org API
924
- *
925
- * @return object
926
- */
927
- public function toWpFormat(){
928
- $info = new StdClass;
929
-
930
- //The custom update API is built so that many fields have the same name and format
931
- //as those returned by the native WordPress.org API. These can be assigned directly.
932
- $sameFormat = array(
933
- 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
934
- 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
935
- );
936
- foreach($sameFormat as $field){
937
- if ( isset($this->$field) ) {
938
- $info->$field = $this->$field;
939
- } else {
940
- $info->$field = null;
941
- }
942
- }
943
-
944
- //Other fields need to be renamed and/or transformed.
945
- $info->download_link = $this->download_url;
946
- $info->author = $this->getFormattedAuthor();
947
- $info->sections = array_merge(array('description' => ''), $this->sections);
948
-
949
- if ( !empty($this->banners) ) {
950
- //WP expects an array with two keys: "high" and "low". Both are optional.
951
- //Docs: https://wordpress.org/plugins/about/faq/#banners
952
- $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
953
- $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
954
- }
955
-
956
- return $info;
957
- }
958
-
959
- protected function getFormattedAuthor() {
960
- if ( !empty($this->author_homepage) ){
961
- return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
962
- }
963
- return $this->author;
964
- }
965
- }
966
-
967
- endif;
968
-
969
- if ( !class_exists('PluginUpdate_3_0', false) ):
970
-
971
- /**
972
- * A simple container class for holding information about an available update.
973
- *
974
- * @author Janis Elsts
975
- * @copyright 2016
976
- * @version 3.0
977
- * @access public
978
- */
979
- class PluginUpdate_3_0 {
980
- public $id = 0;
981
- public $slug;
982
- public $version;
983
- public $homepage;
984
- public $download_url;
985
- public $upgrade_notice;
986
- public $filename; //Plugin filename relative to the plugins directory.
987
-
988
- private static $fields = array('id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice', 'filename');
989
-
990
- /**
991
- * Create a new instance of PluginUpdate from its JSON-encoded representation.
992
- *
993
- * @param string $json
994
- * @return PluginUpdate_3_0|null
995
- */
996
- public static function fromJson($json){
997
- //Since update-related information is simply a subset of the full plugin info,
998
- //we can parse the update JSON as if it was a plugin info string, then copy over
999
- //the parts that we care about.
1000
- $pluginInfo = PluginInfo_3_0::fromJson($json);
1001
- if ( $pluginInfo != null ) {
1002
- return self::fromPluginInfo($pluginInfo);
1003
- } else {
1004
- return null;
1005
- }
1006
- }
1007
-
1008
- /**
1009
- * Create a new instance of PluginUpdate based on an instance of PluginInfo.
1010
- * Basically, this just copies a subset of fields from one object to another.
1011
- *
1012
- * @param PluginInfo_3_0 $info
1013
- * @return PluginUpdate_3_0
1014
- */
1015
- public static function fromPluginInfo($info){
1016
- return self::fromObject($info);
1017
- }
1018
-
1019
- /**
1020
- * Create a new instance of PluginUpdate by copying the necessary fields from
1021
- * another object.
1022
- *
1023
- * @param StdClass|PluginInfo_3_0|PluginUpdate_3_0 $object The source object.
1024
- * @return PluginUpdate_3_0 The new copy.
1025
- */
1026
- public static function fromObject($object) {
1027
- $update = new self();
1028
- $fields = self::$fields;
1029
- if (!empty($object->slug)) $fields = apply_filters('puc_retain_fields-'.$object->slug, $fields);
1030
- foreach($fields as $field){
1031
- if (property_exists($object, $field)) {
1032
- $update->$field = $object->$field;
1033
- }
1034
- }
1035
- return $update;
1036
- }
1037
-
1038
- /**
1039
- * Create an instance of StdClass that can later be converted back to
1040
- * a PluginUpdate. Useful for serialization and caching, as it avoids
1041
- * the "incomplete object" problem if the cached value is loaded before
1042
- * this class.
1043
- *
1044
- * @return StdClass
1045
- */
1046
- public function toStdClass() {
1047
- $object = new StdClass();
1048
- $fields = self::$fields;
1049
- if (!empty($this->slug)) $fields = apply_filters('puc_retain_fields-'.$this->slug, $fields);
1050
- foreach($fields as $field){
1051
- if (property_exists($this, $field)) {
1052
- $object->$field = $this->$field;
1053
- }
1054
- }
1055
- return $object;
1056
- }
1057
-
1058
-
1059
- /**
1060
- * Transform the update into the format used by WordPress native plugin API.
1061
- *
1062
- * @return object
1063
- */
1064
- public function toWpFormat(){
1065
- $update = new StdClass;
1066
-
1067
- $update->id = $this->id;
1068
- $update->slug = $this->slug;
1069
- $update->new_version = $this->version;
1070
- $update->url = $this->homepage;
1071
- $update->package = $this->download_url;
1072
- $update->plugin = $this->filename;
1073
-
1074
- if ( !empty($this->upgrade_notice) ){
1075
- $update->upgrade_notice = $this->upgrade_notice;
1076
- }
1077
-
1078
- return $update;
1079
- }
1080
- }
1081
-
1082
- endif;
1083
-
1084
- if ( !class_exists('PucScheduler_3_0', false) ):
1085
-
1086
- /**
1087
- * The scheduler decides when and how often to check for updates.
1088
- * It calls @see PluginUpdateChecker::checkForUpdates() to perform the actual checks.
1089
- *
1090
- * @version 3.0
1091
- */
1092
- class PucScheduler_3_0 {
1093
- public $checkPeriod = 12; //How often to check for updates (in hours).
1094
- public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
1095
- public $throttledCheckPeriod = 72;
1096
-
1097
- /**
1098
- * @var PluginUpdateChecker_3_0
1099
- */
1100
- protected $updateChecker;
1101
-
1102
- private $cronHook = null;
1103
-
1104
- /**
1105
- * Scheduler constructor.
1106
- *
1107
- * @param PluginUpdateChecker_3_0 $updateChecker
1108
- * @param int $checkPeriod How often to check for updates (in hours).
1109
- */
1110
- public function __construct($updateChecker, $checkPeriod) {
1111
- $this->updateChecker = $updateChecker;
1112
- $this->checkPeriod = $checkPeriod;
1113
-
1114
- //Set up the periodic update checks
1115
- $this->cronHook = 'check_plugin_updates-' . $this->updateChecker->slug;
1116
- if ( $this->checkPeriod > 0 ){
1117
-
1118
- //Trigger the check via Cron.
1119
- //Try to use one of the default schedules if possible as it's less likely to conflict
1120
- //with other plugins and their custom schedules.
1121
- $defaultSchedules = array(
1122
- 1 => 'hourly',
1123
- 12 => 'twicedaily',
1124
- 24 => 'daily',
1125
- );
1126
- if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
1127
- $scheduleName = $defaultSchedules[$this->checkPeriod];
1128
- } else {
1129
- //Use a custom cron schedule.
1130
- $scheduleName = 'every' . $this->checkPeriod . 'hours';
1131
- add_filter('cron_schedules', array($this, '_addCustomSchedule'));
1132
- }
1133
-
1134
- if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
1135
- wp_schedule_event(time(), $scheduleName, $this->cronHook);
1136
- }
1137
- add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
1138
-
1139
- register_deactivation_hook($this->updateChecker->pluginFile, array($this, '_removeUpdaterCron'));
1140
-
1141
- //In case Cron is disabled or unreliable, we also manually trigger
1142
- //the periodic checks while the user is browsing the Dashboard.
1143
- add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
1144
-
1145
- //Like WordPress itself, we check more often on certain pages.
1146
- /** @see wp_update_plugins */
1147
- add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
1148
- add_action('load-plugins.php', array($this, 'maybeCheckForUpdates'));
1149
- add_action('load-update.php', array($this, 'maybeCheckForUpdates'));
1150
- //This hook fires after a bulk update is complete.
1151
- add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);
1152
-
1153
- } else {
1154
- //Periodic checks are disabled.
1155
- wp_clear_scheduled_hook($this->cronHook);
1156
- }
1157
- }
1158
-
1159
- /**
1160
- * Check for updates if the configured check interval has already elapsed.
1161
- * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
1162
- *
1163
- * You can override the default behaviour by using the "puc_check_now-$slug" filter.
1164
- * The filter callback will be passed three parameters:
1165
- * - Current decision. TRUE = check updates now, FALSE = don't check now.
1166
- * - Last check time as a Unix timestamp.
1167
- * - Configured check period in hours.
1168
- * Return TRUE to check for updates immediately, or FALSE to cancel.
1169
- *
1170
- * This method is declared public because it's a hook callback. Calling it directly is not recommended.
1171
- */
1172
- public function maybeCheckForUpdates(){
1173
- if ( empty($this->checkPeriod) ){
1174
- return;
1175
- }
1176
-
1177
- $currentFilter = current_filter();
1178
- if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
1179
- //Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
1180
- $timeout = 60;
1181
- } else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) {
1182
- //Also check more often on the "Plugins" page and /wp-admin/update.php.
1183
- $timeout = 3600;
1184
- } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
1185
- //Check less frequently if it's already known that an update is available.
1186
- $timeout = $this->throttledCheckPeriod * 3600;
1187
- } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
1188
- //WordPress cron schedules are not exact, so lets do an update check even
1189
- //if slightly less than $checkPeriod hours have elapsed since the last check.
1190
- $cronFuzziness = 20 * 60;
1191
- $timeout = $this->checkPeriod * 3600 - $cronFuzziness;
1192
- } else {
1193
- $timeout = $this->checkPeriod * 3600;
1194
- }
1195
-
1196
- $state = $this->updateChecker->getUpdateState();
1197
- $shouldCheck =
1198
- empty($state) ||
1199
- !isset($state->lastCheck) ||
1200
- ( (time() - $state->lastCheck) >= $timeout );
1201
-
1202
- //Let plugin authors substitute their own algorithm.
1203
- $shouldCheck = apply_filters(
1204
- 'puc_check_now-' . $this->updateChecker->slug,
1205
- $shouldCheck,
1206
- (!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0,
1207
- $this->checkPeriod
1208
- );
1209
-
1210
- if ( $shouldCheck ) {
1211
- $this->updateChecker->checkForUpdates();
1212
- }
1213
- }
1214
-
1215
- /**
1216
- * Add our custom schedule to the array of Cron schedules used by WP.
1217
- *
1218
- * @param array $schedules
1219
- * @return array
1220
- */
1221
- public function _addCustomSchedule($schedules){
1222
- if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
1223
- $scheduleName = 'every' . $this->checkPeriod . 'hours';
1224
- $schedules[$scheduleName] = array(
1225
- 'interval' => $this->checkPeriod * 3600,
1226
- 'display' => sprintf('Every %d hours', $this->checkPeriod),
1227
- );
1228
- }
1229
- return $schedules;
1230
- }
1231
-
1232
- /**
1233
- * Remove the scheduled cron event that the library uses to check for updates.
1234
- *
1235
- * @return void
1236
- */
1237
- public function _removeUpdaterCron(){
1238
- wp_clear_scheduled_hook($this->cronHook);
1239
- }
1240
-
1241
- /**
1242
- * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
1243
- *
1244
- * @return string
1245
- */
1246
- public function getCronHookName() {
1247
- return $this->cronHook;
1248
- }
1249
- }
1250
-
1251
- endif;
1252
-
1253
-
1254
- if ( !class_exists('PucUpgraderStatus_3_0', false) ):
1255
-
1256
- /**
1257
- * A utility class that helps figure out which plugin WordPress is upgrading.
1258
- *
1259
- * It may seem strange to have an separate class just for that, but the task is surprisingly complicated.
1260
- * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
1261
- * This class uses a few workarounds and heuristics to get the file name.
1262
- */
1263
- class PucUpgraderStatus_3_0 {
1264
- private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress.
1265
-
1266
- public function __construct() {
1267
- //Keep track of which plugin WordPress is currently upgrading.
1268
- add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2);
1269
- add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
1270
- add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1);
1271
- add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1);
1272
- }
1273
-
1274
- /**
1275
- * Is there and update being installed RIGHT NOW, for a specific plugin?
1276
- *
1277
- * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
1278
- * and upgrader implementations are liable to change without notice.
1279
- *
1280
- * @param string $pluginFile The plugin to check.
1281
- * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
1282
- * @return bool True if the plugin identified by $pluginFile is being upgraded.
1283
- */
1284
- public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
1285
- if ( isset($upgrader) ) {
1286
- $upgradedPluginFile = $this->getPluginBeingUpgradedBy($upgrader);
1287
- if ( !empty($upgradedPluginFile) ) {
1288
- $this->upgradedPluginFile = $upgradedPluginFile;
1289
- }
1290
- }
1291
- return ( !empty($this->upgradedPluginFile) && ($this->upgradedPluginFile === $pluginFile) );
1292
- }
1293
-
1294
- /**
1295
- * Get the file name of the plugin that's currently being upgraded.
1296
- *
1297
- * @param Plugin_Upgrader|WP_Upgrader $upgrader
1298
- * @return string|null
1299
- */
1300
- private function getPluginBeingUpgradedBy($upgrader) {
1301
- if ( !isset($upgrader, $upgrader->skin) ) {
1302
- return null;
1303
- }
1304
-
1305
- //Figure out which plugin is being upgraded.
1306
- $pluginFile = null;
1307
- $skin = $upgrader->skin;
1308
- if ( $skin instanceof Plugin_Upgrader_Skin ) {
1309
- if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
1310
- $pluginFile = $skin->plugin;
1311
- }
1312
- } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
1313
- //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
1314
- //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
1315
- //do is compare those headers to the headers of installed plugins.
1316
- $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
1317
- }
1318
-
1319
- return $pluginFile;
1320
- }
1321
-
1322
- /**
1323
- * Identify an installed plugin based on its headers.
1324
- *
1325
- * @param array $searchHeaders The plugin file header to look for.
1326
- * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
1327
- */
1328
- private function identifyPluginByHeaders($searchHeaders) {
1329
- if ( !function_exists('get_plugins') ){
1330
- /** @noinspection PhpIncludeInspection */
1331
- require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
1332
- }
1333
-
1334
- $installedPlugins = get_plugins();
1335
- $matches = array();
1336
- foreach($installedPlugins as $pluginBasename => $headers) {
1337
- $diff1 = array_diff_assoc($headers, $searchHeaders);
1338
- $diff2 = array_diff_assoc($searchHeaders, $headers);
1339
- if ( empty($diff1) && empty($diff2) ) {
1340
- $matches[] = $pluginBasename;
1341
- }
1342
- }
1343
-
1344
- //It's possible (though very unlikely) that there could be two plugins with identical
1345
- //headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
1346
- if ( count($matches) !== 1 ) {
1347
- return null;
1348
- }
1349
-
1350
- return reset($matches);
1351
- }
1352
-
1353
- /**
1354
- * @access private
1355
- *
1356
- * @param mixed $input
1357
- * @param array $hookExtra
1358
- * @return mixed Returns $input unaltered.
1359
- */
1360
- public function setUpgradedPlugin($input, $hookExtra) {
1361
- if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) {
1362
- $this->upgradedPluginFile = $hookExtra['plugin'];
1363
- } else {
1364
- $this->upgradedPluginFile = null;
1365
- }
1366
- return $input;
1367
- }
1368
-
1369
- /**
1370
- * @access private
1371
- *
1372
- * @param array $options
1373
- * @return array
1374
- */
1375
- public function setUpgradedPluginFromOptions($options) {
1376
- if (isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin'])) {
1377
- $this->upgradedPluginFile = $options['hook_extra']['plugin'];
1378
- } else {
1379
- $this->upgradedPluginFile = null;
1380
- }
1381
- return $options;
1382
- }
1383
-
1384
- /**
1385
- * @access private
1386
- *
1387
- * @param mixed $input
1388
- * @return mixed Returns $input unaltered.
1389
- */
1390
- public function clearUpgradedPlugin($input = null) {
1391
- $this->upgradedPluginFile = null;
1392
- return $input;
1393
- }
1394
- }
1395
-
1396
- endif;
1397
-
1398
-
1399
- if ( !class_exists('PucFactory', false) ):
1400
-
1401
- /**
1402
- * A factory that builds instances of other classes from this library.
1403
- *
1404
- * When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 1.2
1405
- * and 1.3), this factory will always use the latest available version. Register class
1406
- * versions by calling {@link PucFactory::addVersion()}.
1407
- *
1408
- * At the moment it can only build instances of the PluginUpdateChecker class. Other classes
1409
- * are intended mainly for internal use and refer directly to specific implementations. If you
1410
- * want to instantiate one of them anyway, you can use {@link PucFactory::getLatestClassVersion()}
1411
- * to get the class name and then create it with <code>new $class(...)</code>.
1412
- */
1413
- class PucFactory {
1414
- protected static $classVersions = array();
1415
- protected static $sorted = false;
1416
-
1417
- /**
1418
- * Create a new instance of PluginUpdateChecker.
1419
- *
1420
- * @see PluginUpdateChecker::__construct()
1421
- *
1422
- * @param $metadataUrl
1423
- * @param $pluginFile
1424
- * @param string $slug
1425
- * @param int $checkPeriod
1426
- * @param string $optionName
1427
- * @param string $muPluginFile
1428
- * @return PluginUpdateChecker_3_0
1429
- */
1430
- public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
1431
- $class = self::getLatestClassVersion('PluginUpdateChecker');
1432
- return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
1433
- }
1434
-
1435
- /**
1436
- * Get the specific class name for the latest available version of a class.
1437
- *
1438
- * @param string $class
1439
- * @return string|null
1440
- */
1441
- public static function getLatestClassVersion($class) {
1442
- if ( !self::$sorted ) {
1443
- self::sortVersions();
1444
- }
1445
-
1446
- if ( isset(self::$classVersions[$class]) ) {
1447
- return reset(self::$classVersions[$class]);
1448
- } else {
1449
- return null;
1450
- }
1451
- }
1452
-
1453
- /**
1454
- * Sort available class versions in descending order (i.e. newest first).
1455
- */
1456
- protected static function sortVersions() {
1457
- foreach ( self::$classVersions as $class => $versions ) {
1458
- uksort($versions, array(__CLASS__, 'compareVersions'));
1459
- self::$classVersions[$class] = $versions;
1460
- }
1461
- self::$sorted = true;
1462
- }
1463
-
1464
- protected static function compareVersions($a, $b) {
1465
- return -version_compare($a, $b);
1466
- }
1467
-
1468
- /**
1469
- * Register a version of a class.
1470
- *
1471
- * @access private This method is only for internal use by the library.
1472
- *
1473
- * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
1474
- * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
1475
- * @param string $version Version number, e.g. '1.2'.
1476
- */
1477
- public static function addVersion($generalClass, $versionedClass, $version) {
1478
- if ( !isset(self::$classVersions[$generalClass]) ) {
1479
- self::$classVersions[$generalClass] = array();
1480
- }
1481
- self::$classVersions[$generalClass][$version] = $versionedClass;
1482
- self::$sorted = false;
1483
- }
1484
- }
1485
-
1486
- endif;
1487
-
1488
- require_once(dirname(__FILE__) . '/github-checker.php');
1489
-
1490
- //Register classes defined in this file with the factory.
1491
- PucFactory::addVersion('PluginUpdateChecker', 'PluginUpdateChecker_3_0', '3.0');
1492
- PucFactory::addVersion('PluginUpdate', 'PluginUpdate_3_0', '3.0');
1493
- PucFactory::addVersion('PluginInfo', 'PluginInfo_3_0', '3.0');
1494
- PucFactory::addVersion('PucGitHubChecker', 'PucGitHubChecker_3_0', '3.0');
1
+ <?php
2
+ /**
3
+ * Plugin Update Checker Library 4.2
4
+ * http://w-shadow.com/
5
+ *
6
+ * Copyright 2017 Janis Elsts
7
+ * Released under the MIT license. See license.txt for details.
8
+ */
9
+
10
+ require dirname(__FILE__) . '/Puc/v4/Factory.php';
11
+ require dirname(__FILE__) . '/Puc/v4p2/Autoloader.php';
12
+ new Puc_v4p2_Autoloader();
13
+
14
+ //Register classes defined in this file with the factory.
15
+ Puc_v4_Factory::addVersion('Plugin_UpdateChecker', 'Puc_v4p2_Plugin_UpdateChecker', '4.2');
16
+ Puc_v4_Factory::addVersion('Theme_UpdateChecker', 'Puc_v4p2_Theme_UpdateChecker', '4.2');
17
+
18
+ Puc_v4_Factory::addVersion('Vcs_PluginUpdateChecker', 'Puc_v4p2_Vcs_PluginUpdateChecker', '4.2');
19
+ Puc_v4_Factory::addVersion('Vcs_ThemeUpdateChecker', 'Puc_v4p2_Vcs_ThemeUpdateChecker', '4.2');
20
+
21
+ Puc_v4_Factory::addVersion('GitHubApi', 'Puc_v4p2_Vcs_GitHubApi', '4.2');
22
+ Puc_v4_Factory::addVersion('BitBucketApi', 'Puc_v4p2_Vcs_BitBucketApi', '4.2');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
admin/update-checker/vendor/Parsedown.php CHANGED
@@ -17,7 +17,7 @@ class Parsedown
17
  {
18
  # ~
19
 
20
- const version = '1.5.0';
21
 
22
  # ~
23
 
@@ -107,12 +107,6 @@ class Parsedown
107
 
108
  # ~
109
 
110
- protected $DefinitionTypes = array(
111
- '[' => array('Reference'),
112
- );
113
-
114
- # ~
115
-
116
  protected $unmarkedBlockTypes = array(
117
  'Code',
118
  );
@@ -121,7 +115,7 @@ class Parsedown
121
  # Blocks
122
  #
123
 
124
- private function lines(array $lines)
125
  {
126
  $CurrentBlock = null;
127
 
@@ -169,7 +163,7 @@ class Parsedown
169
 
170
  # ~
171
 
172
- if (isset($CurrentBlock['incomplete']))
173
  {
174
  $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
175
 
@@ -181,12 +175,10 @@ class Parsedown
181
  }
182
  else
183
  {
184
- if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
185
  {
186
  $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
187
  }
188
-
189
- unset($CurrentBlock['incomplete']);
190
  }
191
  }
192
 
@@ -224,9 +216,9 @@ class Parsedown
224
  $Block['identified'] = true;
225
  }
226
 
227
- if (method_exists($this, 'block'.$blockType.'Continue'))
228
  {
229
- $Block['incomplete'] = true;
230
  }
231
 
232
  $CurrentBlock = $Block;
@@ -253,7 +245,7 @@ class Parsedown
253
 
254
  # ~
255
 
256
- if (isset($CurrentBlock['incomplete']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
257
  {
258
  $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
259
  }
@@ -286,6 +278,16 @@ class Parsedown
286
  return $markup;
287
  }
288
 
 
 
 
 
 
 
 
 
 
 
289
  #
290
  # Code
291
 
@@ -394,16 +396,16 @@ class Parsedown
394
 
395
  protected function blockFencedCode($Line)
396
  {
397
- if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
398
  {
399
  $Element = array(
400
  'name' => 'code',
401
  'text' => '',
402
  );
403
 
404
- if (isset($matches[2]))
405
  {
406
- $class = 'language-'.$matches[2];
407
 
408
  $Element['attributes'] = array(
409
  'class' => $class,
@@ -673,7 +675,9 @@ class Parsedown
673
 
674
  if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
675
  {
676
- if (in_array($matches[1], $this->textLevelElements))
 
 
677
  {
678
  return;
679
  }
@@ -736,8 +740,6 @@ class Parsedown
736
  {
737
  $Block['closed'] = true;
738
  }
739
-
740
- $Block['markup'] .= $matches[1];
741
  }
742
 
743
  if (isset($Block['interrupted']))
@@ -989,15 +991,13 @@ class Parsedown
989
  {
990
  $markup = '';
991
 
992
- $unexaminedText = $text;
993
 
994
- $markerPosition = 0;
995
-
996
- while ($excerpt = strpbrk($unexaminedText, $this->inlineMarkerList))
997
  {
998
  $marker = $excerpt[0];
999
 
1000
- $markerPosition += strpos($unexaminedText, $marker);
1001
 
1002
  $Excerpt = array('text' => $excerpt, 'context' => $text);
1003
 
@@ -1010,34 +1010,42 @@ class Parsedown
1010
  continue;
1011
  }
1012
 
1013
- if (isset($Inline['position']) and $Inline['position'] > $markerPosition) # position is ahead of marker
 
 
1014
  {
1015
  continue;
1016
  }
1017
 
 
 
1018
  if ( ! isset($Inline['position']))
1019
  {
1020
  $Inline['position'] = $markerPosition;
1021
  }
1022
 
 
1023
  $unmarkedText = substr($text, 0, $Inline['position']);
1024
 
 
1025
  $markup .= $this->unmarkedText($unmarkedText);
1026
 
 
1027
  $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
1028
 
 
1029
  $text = substr($text, $Inline['position'] + $Inline['extent']);
1030
 
1031
- $unexaminedText = $text;
1032
-
1033
- $markerPosition = 0;
1034
-
1035
  continue 2;
1036
  }
1037
 
1038
- $unexaminedText = substr($excerpt, 1);
1039
 
1040
- $markerPosition ++;
 
 
 
 
1041
  }
1042
 
1043
  $markup .= $this->unmarkedText($text);
@@ -1199,7 +1207,7 @@ class Parsedown
1199
  return;
1200
  }
1201
 
1202
- if (preg_match('/^[(]((?:[^ (]|[(][^ )]+[)])+)(?:[ ]+("[^"]+"|\'[^\']+\'))?[)]/', $remainder, $matches))
1203
  {
1204
  $Element['attributes']['href'] = $matches[1];
1205
 
@@ -1214,7 +1222,7 @@ class Parsedown
1214
  {
1215
  if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
1216
  {
1217
- $definition = $matches[1] ? $matches[1] : $Element['text'];
1218
  $definition = strtolower($definition);
1219
 
1220
  $extent += strlen($matches[0]);
@@ -1360,11 +1368,6 @@ class Parsedown
1360
  }
1361
  }
1362
 
1363
- #
1364
- # ~
1365
-
1366
- protected $unmarkedInlineTypes = array("\n" => 'Break', '://' => 'Url');
1367
-
1368
  # ~
1369
 
1370
  protected function unmarkedText($text)
@@ -1409,7 +1412,7 @@ class Parsedown
1409
 
1410
  if (isset($Element['handler']))
1411
  {
1412
- $markup .= $this->$Element['handler']($Element['text']);
1413
  }
1414
  else
1415
  {
@@ -1483,7 +1486,7 @@ class Parsedown
1483
  return self::$instances[$name];
1484
  }
1485
 
1486
- $instance = new self();
1487
 
1488
  self::$instances[$name] = $instance;
1489
 
@@ -1532,4 +1535,4 @@ class Parsedown
1532
  'wbr', 'span',
1533
  'time',
1534
  );
1535
- }
17
  {
18
  # ~
19
 
20
+ const version = '1.6.0';
21
 
22
  # ~
23
 
107
 
108
  # ~
109
 
 
 
 
 
 
 
110
  protected $unmarkedBlockTypes = array(
111
  'Code',
112
  );
115
  # Blocks
116
  #
117
 
118
+ protected function lines(array $lines)
119
  {
120
  $CurrentBlock = null;
121
 
163
 
164
  # ~
165
 
166
+ if (isset($CurrentBlock['continuable']))
167
  {
168
  $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
169
 
175
  }
176
  else
177
  {
178
+ if ($this->isBlockCompletable($CurrentBlock['type']))
179
  {
180
  $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
181
  }
 
 
182
  }
183
  }
184
 
216
  $Block['identified'] = true;
217
  }
218
 
219
+ if ($this->isBlockContinuable($blockType))
220
  {
221
+ $Block['continuable'] = true;
222
  }
223
 
224
  $CurrentBlock = $Block;
245
 
246
  # ~
247
 
248
+ if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
249
  {
250
  $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
251
  }
278
  return $markup;
279
  }
280
 
281
+ protected function isBlockContinuable($Type)
282
+ {
283
+ return method_exists($this, 'block'.$Type.'Continue');
284
+ }
285
+
286
+ protected function isBlockCompletable($Type)
287
+ {
288
+ return method_exists($this, 'block'.$Type.'Complete');
289
+ }
290
+
291
  #
292
  # Code
293
 
396
 
397
  protected function blockFencedCode($Line)
398
  {
399
+ if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
400
  {
401
  $Element = array(
402
  'name' => 'code',
403
  'text' => '',
404
  );
405
 
406
+ if (isset($matches[1]))
407
  {
408
+ $class = 'language-'.$matches[1];
409
 
410
  $Element['attributes'] = array(
411
  'class' => $class,
675
 
676
  if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
677
  {
678
+ $element = strtolower($matches[1]);
679
+
680
+ if (in_array($element, $this->textLevelElements))
681
  {
682
  return;
683
  }
740
  {
741
  $Block['closed'] = true;
742
  }
 
 
743
  }
744
 
745
  if (isset($Block['interrupted']))
991
  {
992
  $markup = '';
993
 
994
+ # $excerpt is based on the first occurrence of a marker
995
 
996
+ while ($excerpt = strpbrk($text, $this->inlineMarkerList))
 
 
997
  {
998
  $marker = $excerpt[0];
999
 
1000
+ $markerPosition = strpos($text, $marker);
1001
 
1002
  $Excerpt = array('text' => $excerpt, 'context' => $text);
1003
 
1010
  continue;
1011
  }
1012
 
1013
+ # makes sure that the inline belongs to "our" marker
1014
+
1015
+ if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
1016
  {
1017
  continue;
1018
  }
1019
 
1020
+ # sets a default inline position
1021
+
1022
  if ( ! isset($Inline['position']))
1023
  {
1024
  $Inline['position'] = $markerPosition;
1025
  }
1026
 
1027
+ # the text that comes before the inline
1028
  $unmarkedText = substr($text, 0, $Inline['position']);
1029
 
1030
+ # compile the unmarked text
1031
  $markup .= $this->unmarkedText($unmarkedText);
1032
 
1033
+ # compile the inline
1034
  $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
1035
 
1036
+ # remove the examined text
1037
  $text = substr($text, $Inline['position'] + $Inline['extent']);
1038
 
 
 
 
 
1039
  continue 2;
1040
  }
1041
 
1042
+ # the marker does not belong to an inline
1043
 
1044
+ $unmarkedText = substr($text, 0, $markerPosition + 1);
1045
+
1046
+ $markup .= $this->unmarkedText($unmarkedText);
1047
+
1048
+ $text = substr($text, $markerPosition + 1);
1049
  }
1050
 
1051
  $markup .= $this->unmarkedText($text);
1207
  return;
1208
  }
1209
 
1210
+ if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches))
1211
  {
1212
  $Element['attributes']['href'] = $matches[1];
1213
 
1222
  {
1223
  if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
1224
  {
1225
+ $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
1226
  $definition = strtolower($definition);
1227
 
1228
  $extent += strlen($matches[0]);
1368
  }
1369
  }
1370
 
 
 
 
 
 
1371
  # ~
1372
 
1373
  protected function unmarkedText($text)
1412
 
1413
  if (isset($Element['handler']))
1414
  {
1415
+ $markup .= $this->{$Element['handler']}($Element['text']);
1416
  }
1417
  else
1418
  {
1486
  return self::$instances[$name];
1487
  }
1488
 
1489
+ $instance = new static();
1490
 
1491
  self::$instances[$name] = $instance;
1492
 
1535
  'wbr', 'span',
1536
  'time',
1537
  );
1538
+ }
admin/update-checker/vendor/readme-parser.php CHANGED
@@ -1,14 +1,16 @@
1
  <?php
2
 
 
 
3
  /**
4
  * This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
5
  * It uses Parsedown instead of the "Markdown Extra" parser.
6
  */
7
 
8
- Class PucReadmeParser {
9
 
10
  function __construct() {
11
- // This space intentially blank
12
  }
13
 
14
  function parse_readme( $file ) {
@@ -120,7 +122,7 @@ Class PucReadmeParser {
120
 
121
  $sections = array();
122
  for ( $i=1; $i <= count($_sections); $i +=2 ) {
123
- $_sections[$i] = preg_replace('/^[\s]*=[\s]+(.+?)[\s]+=/m', '<h4>$1</h4>', $_sections[$i]);
124
  $_sections[$i] = $this->filter_text( $_sections[$i], true );
125
  $title = $this->sanitize_text( $_sections[$i-1] );
126
  $sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $_sections[$i]);
@@ -238,7 +240,8 @@ Class PucReadmeParser {
238
 
239
  if ( $markdown ) { // Parse markdown.
240
  if ( !class_exists('Parsedown', false) ) {
241
- require_once(dirname(__FILE__) . '/Parsedown.php');
 
242
  }
243
  $instance = Parsedown::instance();
244
  $text = $instance->text($text);
@@ -328,4 +331,4 @@ Class PucReadmeParser {
328
 
329
  } // end class
330
 
331
- Class Automattic_Readme extends PucReadmeParser {}
1
  <?php
2
 
3
+ if ( !class_exists('PucReadmeParser', false) ):
4
+
5
  /**
6
  * This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
7
  * It uses Parsedown instead of the "Markdown Extra" parser.
8
  */
9
 
10
+ class PucReadmeParser {
11
 
12
  function __construct() {
13
+ // This space intentionally blank
14
  }
15
 
16
  function parse_readme( $file ) {
122
 
123
  $sections = array();
124
  for ( $i=1; $i <= count($_sections); $i +=2 ) {
125
+ $_sections[$i] = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1<h4>$2</h4>', $_sections[$i]);
126
  $_sections[$i] = $this->filter_text( $_sections[$i], true );
127
  $title = $this->sanitize_text( $_sections[$i-1] );
128
  $sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $_sections[$i]);
240
 
241
  if ( $markdown ) { // Parse markdown.
242
  if ( !class_exists('Parsedown', false) ) {
243
+ /** @noinspection PhpIncludeInspection */
244
+ require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
245
  }
246
  $instance = Parsedown::instance();
247
  $text = $instance->text($text);
331
 
332
  } // end class
333
 
334
+ endif;
admin/view/wp-slimstat-db.php CHANGED
@@ -145,7 +145,6 @@ class wp_slimstat_db {
145
  // Hidden Filters
146
  if ( wp_slimstat::$settings[ 'restrict_authors_view' ] == 'yes' && !current_user_can( 'manage_options' ) && !empty( $GLOBALS[ 'current_user' ]->user_login ) ) {
147
  $filters_array[ 'author' ] = 'author equals ' . $GLOBALS[ 'current_user' ]->user_login;
148
- self::$hidden_filters[ 'author' ] = 1;
149
  }
150
 
151
  if ( !empty( $filters_array ) ) {
@@ -166,6 +165,7 @@ class wp_slimstat_db {
166
 
167
  // Normalize the filters
168
  self::$filters_normalized = self::get_filters_normalized( $filters_raw );
 
169
  }
170
  // end init
171
 
@@ -555,7 +555,6 @@ class wp_slimstat_db {
555
  );
556
 
557
  $filters_normalized[ 'utime' ][ 'start' ] = $filters_normalized[ 'utime' ][ 'end' ] - ( intval( wp_slimstat::$settings[ 'posts_column_day_interval' ] ) * 86400 );
558
- $filters_normalized[ 'date' ][ 'interval' ] = wp_slimstat::$settings[ 'posts_column_day_interval' ];
559
  $filters_normalized[ 'utime' ][ 'type' ] = 'interval';
560
 
561
  if ( isset( $filters_normalized[ 'date' ][ 'interval' ] ) ) {
@@ -725,7 +724,8 @@ class wp_slimstat_db {
725
 
726
  case 'interval':
727
  $group_by = array( 'MONTH', 'DAY', 'j' );
728
- $values_in_interval = array( abs( self::$filters_normalized[ 'date' ][ 'interval' ] - 1 ), abs( self::$filters_normalized[ 'date' ][ 'interval' ] - 1 ), 0, 86400 );
 
729
  break;
730
 
731
  default:
@@ -792,11 +792,11 @@ class wp_slimstat_db {
792
  foreach ( $results as $i => $a_result ) {
793
  $index = !empty( self::$filters_normalized[ 'date' ][ 'interval' ] ) ? floor( ( $a_result['dt'] - self::$filters_normalized[ 'utime' ][ 'start' ] ) / 86400 ) : gmdate( $group_by[ 2 ], $a_result[ 'dt' ] );
794
 
795
- if ( empty( self::$filters_normalized[ 'date' ][ 'interval' ] ) && gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $a_result[ 'dt' ] ) == gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $previous[ 'start' ] ) ){
796
  $output[ 'previous' ][ 'first_metric' ][ $index ] = intval( $a_result[ 'first_metric' ] );
797
  $output[ 'previous' ][ 'second_metric' ][ $index ] = intval( $a_result[ 'second_metric' ] );
798
  }
799
- if ( !empty( self::$filters_normalized[ 'date' ][ 'interval' ] ) || gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $a_result[ 'dt' ] ) == gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], self::$filters_normalized[ 'utime' ][ 'start' ] ) ){
800
  $output[ 'current' ][ 'first_metric' ][ $index ] = intval( $a_result[ 'first_metric' ] );
801
  $output[ 'current' ][ 'second_metric' ][ $index ] = intval( $a_result[ 'second_metric' ] );
802
  }
145
  // Hidden Filters
146
  if ( wp_slimstat::$settings[ 'restrict_authors_view' ] == 'yes' && !current_user_can( 'manage_options' ) && !empty( $GLOBALS[ 'current_user' ]->user_login ) ) {
147
  $filters_array[ 'author' ] = 'author equals ' . $GLOBALS[ 'current_user' ]->user_login;
 
148
  }
149
 
150
  if ( !empty( $filters_array ) ) {
165
 
166
  // Normalize the filters
167
  self::$filters_normalized = self::get_filters_normalized( $filters_raw );
168
+
169
  }
170
  // end init
171
 
555
  );
556
 
557
  $filters_normalized[ 'utime' ][ 'start' ] = $filters_normalized[ 'utime' ][ 'end' ] - ( intval( wp_slimstat::$settings[ 'posts_column_day_interval' ] ) * 86400 );
 
558
  $filters_normalized[ 'utime' ][ 'type' ] = 'interval';
559
 
560
  if ( isset( $filters_normalized[ 'date' ][ 'interval' ] ) ) {
724
 
725
  case 'interval':
726
  $group_by = array( 'MONTH', 'DAY', 'j' );
727
+ $default_interval = empty( self::$filters_normalized[ 'date' ][ 'interval' ] ) ? intval( wp_slimstat::$settings[ 'posts_column_day_interval' ] ) : self::$filters_normalized[ 'date' ][ 'interval' ];
728
+ $values_in_interval = array( abs( $default_interval - 1 ), abs( $default_interval - 1 ), 0, 86400 );
729
  break;
730
 
731
  default:
792
  foreach ( $results as $i => $a_result ) {
793
  $index = !empty( self::$filters_normalized[ 'date' ][ 'interval' ] ) ? floor( ( $a_result['dt'] - self::$filters_normalized[ 'utime' ][ 'start' ] ) / 86400 ) : gmdate( $group_by[ 2 ], $a_result[ 'dt' ] );
794
 
795
+ if ( !empty( $previous[ 'start' ] ) && gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $a_result[ 'dt' ] ) == gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $previous[ 'start' ] ) ) {
796
  $output[ 'previous' ][ 'first_metric' ][ $index ] = intval( $a_result[ 'first_metric' ] );
797
  $output[ 'previous' ][ 'second_metric' ][ $index ] = intval( $a_result[ 'second_metric' ] );
798
  }
799
+ if ( empty( $previous[ 'start' ] ) || gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], $a_result[ 'dt' ] ) == gmdate( self::$filters_normalized[ 'utime' ][ 'type' ], self::$filters_normalized[ 'utime' ][ 'start' ] ) ) {
800
  $output[ 'current' ][ 'first_metric' ][ $index ] = intval( $a_result[ 'first_metric' ] );
801
  $output[ 'current' ][ 'second_metric' ][ $index ] = intval( $a_result[ 'second_metric' ] );
802
  }
admin/view/wp-slimstat-reports.php CHANGED
@@ -6,9 +6,6 @@ class wp_slimstat_reports {
6
  public static $reports_info = array();
7
  public static $user_reports = array();
8
 
9
- // Hidden filters are not displayed to the user, but are applied to the reports
10
- public static $hidden_filters = array();
11
-
12
  // Useful data for the reports
13
  protected static $pageviews = 0;
14
 
@@ -1942,31 +1939,29 @@ class wp_slimstat_reports {
1942
  /**
1943
  * Generate the HTML that lists all the filters currently used
1944
  */
1945
- public static function get_filters_html($_filters_array = array()){
1946
  $filters_html = '';
1947
 
1948
- // Don't display direction and limit results
1949
- $filters_dropdown = array_diff_key($_filters_array, self::$hidden_filters);
1950
-
1951
- if (!empty($filters_dropdown)){
1952
- foreach($filters_dropdown as $a_filter_label => $a_filter_details){
1953
- if (!array_key_exists($a_filter_label, wp_slimstat_db::$columns_names) || strpos($a_filter_label, 'no_filter') !== false){
1954
  continue;
1955
  }
1956
 
1957
- $a_filter_value_no_slashes = htmlentities(str_replace('\\','', $a_filter_details[1]), ENT_QUOTES, 'UTF-8');
1958
- $filters_html .= "<li>".strtolower(wp_slimstat_db::$columns_names[$a_filter_label][ 0 ]).' '.__(str_replace('_', ' ', $a_filter_details[0]),'wp-slimstat')." $a_filter_value_no_slashes <a class='slimstat-remove-filter slimstat-font-cancel' title='".htmlentities(__('Remove filter for','wp-slimstat'), ENT_QUOTES, 'UTF-8').' '.wp_slimstat_db::$columns_names[ $a_filter_label ][ 0 ]."' href='".self::fs_url("$a_filter_label equals ")."'></a></li>";
1959
  }
1960
  }
1961
- if (!empty($filters_html)){
1962
- $filters_html = "<ul class='slimstat-filter-list'>$filters_html</ul><a href='#' id='slimstat-save-filter' class='slimstat-filter-action-button button-secondary noslimstat' data-filter-array='".htmlentities(serialize($_filters_array), ENT_QUOTES, 'UTF-8')."'>".__('Save','wp-slimstat')."</a>";
 
1963
  }
1964
- if(count($filters_dropdown) > 1){
1965
- $filters_html .= '<a href="'.self::fs_url().'" id="slimstat-remove-all-filters" class="button-secondary slimstat-filter-action-button noslimstat">'.__('Reset All','wp-slimstat').'</a>';
 
1966
  }
1967
- $filters_html .= '';
1968
 
1969
- return ($filters_html != "<span class='filters-title'>".__('Current filters:','wp-slimstat').'</span> ')?$filters_html:'';
1970
  }
1971
 
1972
  public static function fs_url( $_filters = '' ) {
6
  public static $reports_info = array();
7
  public static $user_reports = array();
8
 
 
 
 
9
  // Useful data for the reports
10
  protected static $pageviews = 0;
11
 
1939
  /**
1940
  * Generate the HTML that lists all the filters currently used
1941
  */
1942
+ public static function get_filters_html( $_filters_array = array() ) {
1943
  $filters_html = '';
1944
 
1945
+ if ( !empty( $_filters_array ) ) {
1946
+ foreach( $_filters_array as $a_filter_label => $a_filter_details ) {
1947
+ if ( !array_key_exists( $a_filter_label, wp_slimstat_db::$columns_names ) || strpos( $a_filter_label, 'no_filter' ) !== false ) {
 
 
 
1948
  continue;
1949
  }
1950
 
1951
+ $a_filter_value_no_slashes = htmlentities( str_replace( '\\','', $a_filter_details[ 1 ] ), ENT_QUOTES, 'UTF-8' );
1952
+ $filters_html .= '<li>' . strtolower( wp_slimstat_db::$columns_names[ $a_filter_label ][ 0 ] ) . ' ' . __( str_replace( '_', ' ', $a_filter_details[ 0 ] ), 'wp-slimstat' ) . " $a_filter_value_no_slashes <a class='slimstat-remove-filter slimstat-font-cancel' title='" . htmlentities( __( 'Remove filter for', 'wp-slimstat' ), ENT_QUOTES, 'UTF-8' ) . ' ' . wp_slimstat_db::$columns_names[ $a_filter_label ][ 0 ] . "' href='" . self::fs_url( "$a_filter_label equals " ) . "'></a></li>";
1953
  }
1954
  }
1955
+
1956
+ if ( !empty( $filters_html ) ) {
1957
+ $filters_html = "<ul class='slimstat-filter-list'>$filters_html</ul><a href='#' id='slimstat-save-filter' class='slimstat-filter-action-button button-secondary noslimstat' data-filter-array='" . htmlentities( serialize( $_filters_array ), ENT_QUOTES, 'UTF-8' ) . "'>" . __( 'Save', 'wp-slimstat' ) . '</a>';
1958
  }
1959
+
1960
+ if ( count( $_filters_array ) > 1 ) {
1961
+ $filters_html .= '<a href="' . self::fs_url() . '" id="slimstat-remove-all-filters" class="button-secondary slimstat-filter-action-button noslimstat">' . __( 'Reset All', 'wp-slimstat' ) . '</a>';
1962
  }
 
1963
 
1964
+ return $filters_html;
1965
  }
1966
 
1967
  public static function fs_url( $_filters = '' ) {
admin/wp-slimstat-admin.php CHANGED
@@ -11,7 +11,7 @@ class wp_slimstat_admin {
11
  * Init -- Sets things up.
12
  */
13
  public static function init() {
14
- self::$admin_notice = "This has been an incredible year so far for our team. To celebrate all the great achievements, we've decided to launch our Summer Madness Discounts season. From June to September we are <strong>discounting by 50%</strong> all our <a href='http://www.wp-slimstat.com/addons/' target='_blank'>premium add-ons</a>. Including the bundles! No special codes are required: all discounts are automatically applied during checkout. Extend Slimstat with features like Excel exports, email reports, heatmaps and more, for just a fraction of the price you would normally pay. Not only: if you purchased a premium add-on in April or May, you are eligible for getting back FIFTY PERCENT of what you paid in discounts on future purchases. <strong>ON TOP</strong> of the Summer Madness Discount. Stack both to get basically free add-ons for your website! Please <a href='http://support.wp-slimstat.com' target='_blank'>contact us</a> to get your personal RollBack coupon today or for any questions you might have regarding this promo!";
15
 
16
  // "As those who have been using Slimstat for a while know, we never stop doing our good share of research and development to imrpove this plugin. One request that has been sitting on our wishlist for a while is to make our geolocation functionality more accurate, and track not just a user's Country of origin, but possibly his State (where applicable) and city. In order to geolocate visitors, our code has been leveraging a third-party data file provided by <a href='https://www.maxmind.com/en/home' target='_blank'>MaxMind.com</a>. A while ago, they launched a new data format, which improves performance and offers a way to determine the city of origin. However, the new library required a higher version of PHP, and up until now we had preferred allowing more people to use our plugin, over the chance of offering this feature. Now, we found a way to get the best of both worlds: by customizing their PHP library, we were able to make it work with PHP 5.3! Which means that soon Slimstat will be able to tell you your visitors' city of origin right out of the box. Please contact us if you would like to test this feature in advance."
17
 
@@ -668,12 +668,10 @@ class wp_slimstat_admin {
668
  public static function add_dashboard_widgets() {
669
 
670
  // If this user is whitelisted, we use the minimum capability
671
- if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false ) {
 
672
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_view' ];
673
  }
674
- else {
675
- $minimum_capability = 'read';
676
- }
677
 
678
  if ( !current_user_can( $minimum_capability ) ) {
679
  return;
@@ -769,7 +767,7 @@ class wp_slimstat_admin {
769
  if ( is_network_admin() ) {
770
  $minimum_capability = 'manage_network';
771
  }
772
- else if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false ) {
773
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_view' ];
774
  }
775
 
@@ -811,13 +809,13 @@ class wp_slimstat_admin {
811
  public static function wp_slimstat_adminbar(){
812
  // If this user is whitelisted, we use the minimum capability
813
  $minimum_capability_view = 'read';
814
- if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false ) {
815
  $minimum_capability_view = wp_slimstat::$settings[ 'capability_can_view' ];
816
  }
817
 
818
  // If this user is whitelisted, we use the minimum capability
819
  $minimum_capability_config = 'read';
820
- if ( ( strpos( wp_slimstat::$settings[ 'can_admin' ], $GLOBALS[ 'current_user' ]->user_login ) === false) && $GLOBALS[ 'current_user' ]->user_login != 'slimstatadmin' ) {
821
  $minimum_capability_config = wp_slimstat::$settings[ 'capability_can_admin' ];
822
  }
823
 
@@ -870,7 +868,7 @@ class wp_slimstat_admin {
870
 
871
  // If this user is whitelisted, we use the minimum capability
872
  $minimum_capability = 'read';
873
- if ( ( strpos( wp_slimstat::$settings[ 'can_admin' ], $GLOBALS[ 'current_user' ]->user_login ) === false ) && ( $GLOBALS[ 'current_user' ]->user_login != 'slimstatadmin' ) ) {
874
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_admin' ];
875
  }
876
 
11
  * Init -- Sets things up.
12
  */
13
  public static function init() {
14
+ self::$admin_notice = "After WordPress rolled out their official REST API, we had received a few requests asking to add support for this feature to Slimstat. In an age where headless applications are all the rage, and given that WordPress has reached a stable state in implementing this functionality, we decided that it was time for us to move forward on this project. Starting with Slimstat 4.7, you can now access your metrics from any external application. Just follow these <a href='https://slimstat.freshdesk.com/solution/articles/12000033661-slimstat-rest-api' target='_blank'>simple steps</a> to get started (or contact our support team). Our REST API implementation is still experimental, so please do not hesitate to report any issues or concerns you might have. Also, don't forget that our Summer Madness Discount promotion continues. Get your <a href='http://www.wp-slimstat.com/addons/' target='_blank'>favorite Slimstat add-ons</a> (including the bundles) and pay only half the original price. Note that prices at checkout already factor in the discount; you don't need any special code or cryptic URL to participate!";
15
 
16
  // "As those who have been using Slimstat for a while know, we never stop doing our good share of research and development to imrpove this plugin. One request that has been sitting on our wishlist for a while is to make our geolocation functionality more accurate, and track not just a user's Country of origin, but possibly his State (where applicable) and city. In order to geolocate visitors, our code has been leveraging a third-party data file provided by <a href='https://www.maxmind.com/en/home' target='_blank'>MaxMind.com</a>. A while ago, they launched a new data format, which improves performance and offers a way to determine the city of origin. However, the new library required a higher version of PHP, and up until now we had preferred allowing more people to use our plugin, over the chance of offering this feature. Now, we found a way to get the best of both worlds: by customizing their PHP library, we were able to make it work with PHP 5.3! Which means that soon Slimstat will be able to tell you your visitors' city of origin right out of the box. Please contact us if you would like to test this feature in advance."
17
 
668
  public static function add_dashboard_widgets() {
669
 
670
  // If this user is whitelisted, we use the minimum capability
671
+ $minimum_capability = 'read';
672
+ if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false && !empty( wp_slimstat::$settings[ 'capability_can_view' ] ) ) {
673
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_view' ];
674
  }
 
 
 
675
 
676
  if ( !current_user_can( $minimum_capability ) ) {
677
  return;
767
  if ( is_network_admin() ) {
768
  $minimum_capability = 'manage_network';
769
  }
770
+ else if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false && !empty( wp_slimstat::$settings[ 'capability_can_view' ] ) ) {
771
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_view' ];
772
  }
773
 
809
  public static function wp_slimstat_adminbar(){
810
  // If this user is whitelisted, we use the minimum capability
811
  $minimum_capability_view = 'read';
812
+ if ( strpos( wp_slimstat::$settings[ 'can_view' ], $GLOBALS[ 'current_user' ]->user_login) === false && !empty( wp_slimstat::$settings[ 'capability_can_view' ] ) ) {
813
  $minimum_capability_view = wp_slimstat::$settings[ 'capability_can_view' ];
814
  }
815
 
816
  // If this user is whitelisted, we use the minimum capability
817
  $minimum_capability_config = 'read';
818
+ if ( ( strpos( wp_slimstat::$settings[ 'can_admin' ], $GLOBALS[ 'current_user' ]->user_login ) === false) && $GLOBALS[ 'current_user' ]->user_login != 'slimstatadmin' && !empty( wp_slimstat::$settings[ 'capability_can_admin' ] ) ) {
819
  $minimum_capability_config = wp_slimstat::$settings[ 'capability_can_admin' ];
820
  }
821
 
868
 
869
  // If this user is whitelisted, we use the minimum capability
870
  $minimum_capability = 'read';
871
+ if ( ( strpos( wp_slimstat::$settings[ 'can_admin' ], $GLOBALS[ 'current_user' ]->user_login ) === false ) && ( $GLOBALS[ 'current_user' ]->user_login != 'slimstatadmin' ) && !empty( wp_slimstat::$settings[ 'capability_can_admin' ] ) ) {
872
  $minimum_capability = wp_slimstat::$settings[ 'capability_can_admin' ];
873
  }
874
 
maxmind.php CHANGED
@@ -1,10 +1,10 @@
1
  <?php
2
 
3
- class maxmind_geolite2 {
4
  public static $upload_dir = '';
5
  public static $maxmind_path = '';
6
 
7
- public function get_geolocation_info( $_ip = '' ) {
8
 
9
  self::$upload_dir = wp_upload_dir();
10
  self::$upload_dir = self::$upload_dir[ 'basedir' ];
@@ -18,7 +18,7 @@ class maxmind_geolite2 {
18
 
19
  self::$maxmind_path = self::$upload_dir . '/GeoLite2-City.mmdb';
20
 
21
- $reader = new Reader( self::$maxmind_path );
22
  $record = $reader->get( $_ip );
23
 
24
  if ( !empty( $record[ 'city' ][ 'names' ][ 'en' ] ) ) {
@@ -35,8 +35,7 @@ class maxmind_geolite2 {
35
  * Instances of this class provide a reader for the MaxMind DB format. IP
36
  * addresses can be looked up using the <code>get</code> method.
37
  */
38
- class Reader
39
- {
40
  private static $DATA_SECTION_SEPARATOR_SIZE = 16;
41
  private static $METADATA_START_MARKER = "\xAB\xCD\xEFMaxMind.com";
42
  private static $METADATA_START_MARKER_LENGTH = 14;
@@ -49,7 +48,7 @@ class Reader
49
  private $metadata;
50
 
51
  /**
52
- * Constructs a Reader for the MaxMind DB format. The file passed to it must
53
  * be a valid MaxMind DB file such as a GeoIp2 database file.
54
  *
55
  * @param string $database
@@ -86,10 +85,10 @@ class Reader
86
  }
87
 
88
  $start = $this->findMetadataStart($database);
89
- $metadataDecoder = new Decoder($this->fileHandle, $start);
90
  list($metadataArray) = $metadataDecoder->decode($start);
91
- $this->metadata = new Metadata($metadataArray);
92
- $this->decoder = new Decoder(
93
  $this->fileHandle,
94
  $this->metadata->searchTreeSize + self::$DATA_SECTION_SEPARATOR_SIZE
95
  );
@@ -210,22 +209,22 @@ class Reader
210
  // XXX - probably could condense this.
211
  switch ($this->metadata->recordSize) {
212
  case 24:
213
- $bytes = Util::read($this->fileHandle, $baseOffset + $index * 3, 3);
214
  list(, $node) = unpack('N', "\x00" . $bytes);
215
  return $node;
216
  case 28:
217
- $middleByte = Util::read($this->fileHandle, $baseOffset + 3, 1);
218
  list(, $middle) = unpack('C', $middleByte);
219
  if ($index == 0) {
220
  $middle = (0xF0 & $middle) >> 4;
221
  } else {
222
  $middle = 0x0F & $middle;
223
  }
224
- $bytes = Util::read($this->fileHandle, $baseOffset + $index * 4, 3);
225
  list(, $node) = unpack('N', chr($middle) . $bytes);
226
  return $node;
227
  case 32:
228
- $bytes = Util::read($this->fileHandle, $baseOffset + $index * 4, 4);
229
  list(, $node) = unpack('N', $bytes);
230
  return $node;
231
  default:
@@ -322,9 +321,7 @@ class Reader
322
  }
323
  }
324
 
325
- class Decoder
326
- {
327
-
328
  private $fileStream;
329
  private $pointerBase;
330
  // This is only used for unit testing
@@ -367,7 +364,7 @@ class Decoder
367
  {
368
  list(, $ctrlByte) = unpack(
369
  'C',
370
- Util::read($this->fileStream, $offset, 1)
371
  );
372
  $offset++;
373
 
@@ -392,7 +389,7 @@ class Decoder
392
  if ($type == 'extended') {
393
  list(, $nextByte) = unpack(
394
  'C',
395
- Util::read($this->fileStream, $offset, 1)
396
  );
397
 
398
  $typeNum = $nextByte + 7;
@@ -427,7 +424,7 @@ class Decoder
427
  }
428
 
429
  $newOffset = $offset + $size;
430
- $bytes = Util::read($this->fileStream, $offset, $size);
431
  switch ($type) {
432
  case 'utf8_string':
433
  return array($this->decodeString($bytes), $newOffset);
@@ -526,7 +523,7 @@ class Decoder
526
  {
527
  $pointerSize = (($ctrlByte >> 3) & 0x3) + 1;
528
 
529
- $buffer = Util::read($this->fileStream, $offset, $pointerSize);
530
  $offset = $offset + $pointerSize;
531
 
532
  $packed = $pointerSize == 4
@@ -592,7 +589,7 @@ class Decoder
592
  {
593
  $size = $ctrlByte & 0x1f;
594
  $bytesToRead = $size < 29 ? 0 : $size - 28;
595
- $bytes = Util::read($this->fileStream, $offset, $bytesToRead);
596
  $decoded = $this->decodeUint($bytes);
597
 
598
  if ($size == 29) {
@@ -669,8 +666,7 @@ class InvalidDatabaseException extends \Exception
669
  * values will be a description in that language as a UTF-8 string. May be
670
  * undefined for some databases.
671
  */
672
- class Metadata
673
- {
674
  private $binaryFormatMajorVersion;
675
  private $binaryFormatMinorVersion;
676
  private $buildEpoch;
@@ -683,8 +679,7 @@ class Metadata
683
  private $recordSize;
684
  private $searchTreeSize;
685
 
686
- public function __construct($metadata)
687
- {
688
  $this->binaryFormatMajorVersion =
689
  $metadata['binary_format_major_version'];
690
  $this->binaryFormatMinorVersion =
@@ -700,26 +695,23 @@ class Metadata
700
  $this->searchTreeSize = $this->nodeCount * $this->nodeByteSize;
701
  }
702
 
703
- public function __get($var)
704
- {
705
  return $this->$var;
706
  }
707
  }
708
 
709
- class Util
710
- {
711
- public static function read($stream, $offset, $numberOfBytes)
712
- {
713
- if ($numberOfBytes == 0) {
714
  return '';
715
  }
716
- if (fseek($stream, $offset) == 0) {
717
- $value = fread($stream, $numberOfBytes);
718
 
719
  // We check that the number of bytes read is equal to the number
720
  // asked for. We use ftell as getting the length of $value is
721
  // much slower.
722
- if (ftell($stream) - $offset === $numberOfBytes) {
723
  return $value;
724
  }
725
  }
1
  <?php
2
 
3
+ class maxmind_geolite2_connector {
4
  public static $upload_dir = '';
5
  public static $maxmind_path = '';
6
 
7
+ public static function get_geolocation_info( $_ip = '' ) {
8
 
9
  self::$upload_dir = wp_upload_dir();
10
  self::$upload_dir = self::$upload_dir[ 'basedir' ];
18
 
19
  self::$maxmind_path = self::$upload_dir . '/GeoLite2-City.mmdb';
20
 
21
+ $reader = new MaxMindReader( self::$maxmind_path );
22
  $record = $reader->get( $_ip );
23
 
24
  if ( !empty( $record[ 'city' ][ 'names' ][ 'en' ] ) ) {
35
  * Instances of this class provide a reader for the MaxMind DB format. IP
36
  * addresses can be looked up using the <code>get</code> method.
37
  */
38
+ class MaxMindReader {
 
39
  private static $DATA_SECTION_SEPARATOR_SIZE = 16;
40
  private static $METADATA_START_MARKER = "\xAB\xCD\xEFMaxMind.com";
41
  private static $METADATA_START_MARKER_LENGTH = 14;
48
  private $metadata;
49
 
50
  /**
51
+ * Constructs a MaxMindReader for the MaxMind DB format. The file passed to it must
52
  * be a valid MaxMind DB file such as a GeoIp2 database file.
53
  *
54
  * @param string $database
85
  }
86
 
87
  $start = $this->findMetadataStart($database);
88
+ $metadataDecoder = new MaxMindDecoder($this->fileHandle, $start);
89
  list($metadataArray) = $metadataDecoder->decode($start);
90
+ $this->metadata = new MaxMindMetadata($metadataArray);
91
+ $this->decoder = new MaxMindDecoder(
92
  $this->fileHandle,
93
  $this->metadata->searchTreeSize + self::$DATA_SECTION_SEPARATOR_SIZE
94
  );
209
  // XXX - probably could condense this.
210
  switch ($this->metadata->recordSize) {
211
  case 24:
212
+ $bytes = MaxMindUtil::read($this->fileHandle, $baseOffset + $index * 3, 3);
213
  list(, $node) = unpack('N', "\x00" . $bytes);
214
  return $node;
215
  case 28:
216
+ $middleByte = MaxMindUtil::read($this->fileHandle, $baseOffset + 3, 1);
217
  list(, $middle) = unpack('C', $middleByte);
218
  if ($index == 0) {
219
  $middle = (0xF0 & $middle) >> 4;
220
  } else {
221
  $middle = 0x0F & $middle;
222
  }
223
+ $bytes = MaxMindUtil::read($this->fileHandle, $baseOffset + $index * 4, 3);
224
  list(, $node) = unpack('N', chr($middle) . $bytes);
225
  return $node;
226
  case 32:
227
+ $bytes = MaxMindUtil::read($this->fileHandle, $baseOffset + $index * 4, 4);
228
  list(, $node) = unpack('N', $bytes);
229
  return $node;
230
  default:
321
  }
322
  }
323
 
324
+ class MaxMindDecoder {
 
 
325
  private $fileStream;
326
  private $pointerBase;
327
  // This is only used for unit testing
364
  {
365
  list(, $ctrlByte) = unpack(
366
  'C',
367
+ MaxMindUtil::read($this->fileStream, $offset, 1)
368
  );
369
  $offset++;
370
 
389
  if ($type == 'extended') {
390
  list(, $nextByte) = unpack(
391
  'C',
392
+ MaxMindUtil::read($this->fileStream, $offset, 1)
393
  );
394
 
395
  $typeNum = $nextByte + 7;
424
  }
425
 
426
  $newOffset = $offset + $size;
427
+ $bytes = MaxMindUtil::read($this->fileStream, $offset, $size);
428
  switch ($type) {
429
  case 'utf8_string':
430
  return array($this->decodeString($bytes), $newOffset);
523
  {
524
  $pointerSize = (($ctrlByte >> 3) & 0x3) + 1;
525
 
526
+ $buffer = MaxMindUtil::read($this->fileStream, $offset, $pointerSize);
527
  $offset = $offset + $pointerSize;
528
 
529
  $packed = $pointerSize == 4
589
  {
590
  $size = $ctrlByte & 0x1f;
591
  $bytesToRead = $size < 29 ? 0 : $size - 28;
592
+ $bytes = MaxMindUtil::read($this->fileStream, $offset, $bytesToRead);
593
  $decoded = $this->decodeUint($bytes);
594
 
595
  if ($size == 29) {
666
  * values will be a description in that language as a UTF-8 string. May be
667
  * undefined for some databases.
668
  */
669
+ class MaxMindDecoder {
 
670
  private $binaryFormatMajorVersion;
671
  private $binaryFormatMinorVersion;
672
  private $buildEpoch;
679
  private $recordSize;
680
  private $searchTreeSize;
681
 
682
+ public function __construct($metadata) {
 
683
  $this->binaryFormatMajorVersion =
684
  $metadata['binary_format_major_version'];
685
  $this->binaryFormatMinorVersion =
695
  $this->searchTreeSize = $this->nodeCount * $this->nodeByteSize;
696
  }
697
 
698
+ public function __get($var) {
 
699
  return $this->$var;
700
  }
701
  }
702
 
703
+ class MaxMindUtil {
704
+ public static function read( $stream, $offset, $numberOfBytes ) {
705
+ if ( $numberOfBytes == 0 ) {
 
 
706
  return '';
707
  }
708
+ if ( fseek( $stream, $offset ) == 0 ) {
709
+ $value = fread( $stream, $numberOfBytes );
710
 
711
  // We check that the number of bytes read is equal to the number
712
  // asked for. We use ftell as getting the length of $value is
713
  // much slower.
714
+ if ( ftell( $stream ) - $offset === $numberOfBytes ) {
715
  return $value;
716
  }
717
  }
readme.txt CHANGED
@@ -4,8 +4,8 @@ Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_i
4
  Tags: analytics, statistics, counter, tracking, reports, wassup, geolocation, online users, spider, tracker, pageviews, stats, maxmind, statistics, statpress, power stats, hit
5
  Text Domain: wp-slimstat
6
  Requires at least: 3.8
7
- Tested up to: 4.8
8
- Stable tag: 4.6.9.1
9
 
10
  == Description ==
11
  The leading web analytics plugin for WordPress. Track returning customers and registered users, monitor Javascript events, detect intrusions, analyze email campaigns. Thousands of WordPress sites are already using it.
@@ -71,10 +71,19 @@ Our knowledge base is available on our [support center](http://docs.wp-slimstat.
71
  5. **Responsive layout** - Keep an eye on your reports on the go
72
 
73
  == Changelog ==
 
 
 
 
 
 
 
 
74
  = 4.6.9.1 =
75
  * [New] You can now customize the "past days" interval to be used as the default time range to calculate your metrics, which was previously fixed to 30 days.
76
  * [Fix] The Overview chart was not working as expected for some users, because of a bug in one of the revised SQL queries.
77
  * [Fix] The pageview count on the Edit Posts/Pages screens was also affected by the same bug mentioned here above.
 
78
 
79
  = 4.6.9 =
80
  * [New] Added operating systems to the column you can use to blacklist certain pageviews. Please refer to [this page](https://slimstat.freshdesk.com/solution/articles/12000031504-what-are-the-operating-system-codes-used-by-slimstat-) to learn more about what codes Slimstat uses to represent operating systems internally.
4
  Tags: analytics, statistics, counter, tracking, reports, wassup, geolocation, online users, spider, tracker, pageviews, stats, maxmind, statistics, statpress, power stats, hit
5
  Text Domain: wp-slimstat
6
  Requires at least: 3.8
7
+ Tested up to: 4.8.2
8
+ Stable tag: 4.7
9
 
10
  == Description ==
11
  The leading web analytics plugin for WordPress. Track returning customers and registered users, monitor Javascript events, detect intrusions, analyze email campaigns. Thousands of WordPress sites are already using it.
71
  5. **Responsive layout** - Keep an eye on your reports on the go
72
 
73
  == Changelog ==
74
+ = 4.7 =
75
+ * [New] After receiving a few requests to implement a REST API within Slimstat, and given that WordPress now offers a mature and stable interface for extending its built-in REST API, we decided to finally move forward and implement this feature. Please refer to our [online knowledge base](https://slimstat.freshdesk.com/solution/articles/12000033661-slimstat-rest-api) to learn more about how to use it.
76
+ * [Update] The [Add-on Update Checker library](https://github.com/YahnisElsts/plugin-update-checker) has been updated to version 4.2, to solve an incompatibility issue with PHP 7.0 (thank you, [Sasa](https://wordpress.org/support/topic/possible-incompatibility-with-php-7-0/) and Per).
77
+ * [Update] Bootstrap Switch (which we use on our Settings panels) has been updated to version 3.3.4.
78
+ * [Fix] Apparently, there was an issue where our XMLHttpRequest didn't send the cookie for Cross-Origin URLs (thank you, Sasa).
79
+ * [Fix] Solved issue with pagination, triggered when certain long time ranges were being selected.
80
+ * [Fix] The autorefresh countdown timer was not working as expected if Async Mode was enabled (thank you, [scruffy1 and service4](https://wordpress.org/support/topic/odd-visitors-activity-heading)).
81
+
82
  = 4.6.9.1 =
83
  * [New] You can now customize the "past days" interval to be used as the default time range to calculate your metrics, which was previously fixed to 30 days.
84
  * [Fix] The Overview chart was not working as expected for some users, because of a bug in one of the revised SQL queries.
85
  * [Fix] The pageview count on the Edit Posts/Pages screens was also affected by the same bug mentioned here above.
86
+ * [Fix] A PHP warning of undefined variable $hidden_filters was being logged and/or displayed under certain circumstances.
87
 
88
  = 4.6.9 =
89
  * [New] Added operating systems to the column you can use to blacklist certain pageviews. Please refer to [this page](https://slimstat.freshdesk.com/solution/articles/12000031504-what-are-the-operating-system-codes-used-by-slimstat-) to learn more about what codes Slimstat uses to represent operating systems internally.
wp-slimstat.js CHANGED
@@ -222,6 +222,7 @@ var SlimStat = {
222
  request.open( "POST", SlimStatParams.ajaxurl, true );
223
  request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
224
  request.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );
 
225
  request.send( slimstat_data_with_client_info );
226
 
227
  request.onreadystatechange = function() {
222
  request.open( "POST", SlimStatParams.ajaxurl, true );
223
  request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
224
  request.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );
225
+ request.withCredentials = true;
226
  request.send( slimstat_data_with_client_info );
227
 
228
  request.onreadystatechange = function() {
wp-slimstat.min.js CHANGED
@@ -1 +1 @@
1
- var SlimStat={_id:void 0!==SlimStatParams.id?SlimStatParams.id:"-1.0",_base64_key_str:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_plugins:{acrobat:{substrings:["Adobe","Acrobat"],active_x_strings:["AcroPDF.PDF","PDF.PDFCtrl.5"]},pdfviewer:{substrings:["PDF"],active_x_strings:["AcroPDF.PDF"]},flash:{substrings:["Shockwave","Flash"],active_x_strings:["ShockwaveFlash.ShockwaveFlash"]},mediaplayer:{substrings:["Windows Media"],active_x_strings:["WMPlayer.OCX"]},quicktime:{substrings:["QuickTime"],active_x_strings:["QuickTime.QuickTime"]},silverlight:{substrings:["Silverlight"],active_x_strings:["AgControl.AgControl"]}},_utf8_encode:function(a){var b,c,d="";for(a=a.replace(/\r\n/g,"\n"),b=0;b<a.length;b++)c=a.charCodeAt(b),c<128?d+=String.fromCharCode(c):c>127&&c<2048?(d+=String.fromCharCode(c>>6|192),d+=String.fromCharCode(63&c|128)):(d+=String.fromCharCode(c>>12|224),d+=String.fromCharCode(c>>6&63|128),d+=String.fromCharCode(63&c|128));return d},_base64_encode:function(a){var b,c,d,e,f,g,h,i="",j=0;for(a=SlimStat._utf8_encode(a);j<a.length;)b=a.charCodeAt(j++),c=a.charCodeAt(j++),d=a.charCodeAt(j++),e=b>>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),i=i+SlimStat._base64_key_str.charAt(e)+SlimStat._base64_key_str.charAt(f)+SlimStat._base64_key_str.charAt(g)+SlimStat._base64_key_str.charAt(h);return i},_detect_single_plugin_not_ie:function(a){var c,d,e,f;for(e in navigator.plugins){c=""+navigator.plugins[e].name+navigator.plugins[e].description,d=0;for(f in SlimStat._plugins[a].substrings)-1!=c.indexOf(SlimStat._plugins[a].substrings[f])&&d++;if(d==SlimStat._plugins[a].substrings.length)return!0}return!1},_detect_single_plugin_ie:function(a){var b="",c=!1;for(b in SlimStat._plugins[a].active_x_strings)try{new ActiveXObject(SlimStat._plugins[a].active_x_strings[b]),c=!0}catch(a){}return c},_detect_single_plugin:function(a){return navigator.plugins.length?this.detect=SlimStat._detect_single_plugin_not_ie:this.detect=SlimStat._detect_single_plugin_ie,this.detect(a)},detect_plugins:function(){var a,b=[];for(a in SlimStat._plugins)SlimStat._detect_single_plugin(a)&&b.push(a);return"function"==typeof navigator.javaEnabled&&navigator.javaEnabled()&&b.push("java"),b.join(",")},get_page_performance:function(){return slim_performance=window.performance||window.mozPerformance||window.msPerformance||window.webkitPerformance||{},void 0===slim_performance.timing?0:slim_performance.timing.loadEventEnd-slim_performance.timing.responseEnd},get_server_latency:function(){return slim_performance=window.performance||window.mozPerformance||window.msPerformance||window.webkitPerformance||{},void 0===slim_performance.timing?0:slim_performance.timing.responseEnd-slim_performance.timing.connectEnd},add_event:function(a,b,c){a&&a.addEventListener?a.addEventListener(b,c,!1):a&&a.attachEvent?(a["e"+b+c]=c,a[b+c]=function(){a["e"+b+c](window.event)},a.attachEvent("on"+b,a[b+c])):a["on"+b]=a["e"+b+c]},in_array:function(a,b){for(var c=0;c<b.length;c++)if(b[c].trim()==a)return!0;return!1},in_array_substring:function(a,b){for(var c=0;c<b.length;c++)if(-1!=a.indexOf(b[c].trim()))return!0;return!1},send_to_server:function(a,b){if(void 0===SlimStatParams.ajaxurl||void 0===a)return!1;if(void 0===b&&(b=!0),slimstat_data_with_client_info=a+"&sw="+screen.width+"&sh="+screen.height+"&bw="+window.innerWidth+"&bh="+window.innerHeight+"&sl="+SlimStat.get_server_latency()+"&pp="+SlimStat.get_page_performance()+"&pl="+SlimStat.detect_plugins(),b&&navigator.sendBeacon)navigator.sendBeacon(SlimStatParams.ajaxurl,slimstat_data_with_client_info);else{try{window.XMLHttpRequest?request=new XMLHttpRequest:window.ActiveXObject&&(request=new ActiveXObject("Microsoft.XMLHTTP"))}catch(a){return!1}if(request)return request.open("POST",SlimStatParams.ajaxurl,!0),request.setRequestHeader("Content-type","application/x-www-form-urlencoded"),request.setRequestHeader("X-Requested-With","XMLHttpRequest"),request.send(slimstat_data_with_client_info),request.onreadystatechange=function(){4==request.readyState&&(parsed_id=parseInt(request.responseText),!isNaN(parsed_id)&&parsed_id>0&&(SlimStat._id=request.responseText))},!0}return!1},ss_track:function(a,b,c,d){if(a=a||window.event,b=void 0===b?0:parseInt(b),note_array=[],void 0===d&&(d=!0),parsed_id=parseInt(SlimStat._id),isNaN(parsed_id)||parsed_id<=0)return!1;if(node=void 0!==a.target?a.target:void 0!==a.srcElement&&a.srcElement,!node)return!1;switch(3==node.nodeType&&(node=node.parentNode),parent_node=node.parentNode,resource_url="",node.nodeName){case"FORM":void 0!==node.action&&node.action&&(resource_url=node.action);break;case"INPUT":for(;"undefined"!=typeof parent_node&&"FORM"!=parent_node.nodeName&&"BODY"!=parent_node.nodeName;)parent_node=parent_node.parentNode;if(void 0!==parent_node.action&&parent_node.action){resource_url=parent_node.action;break}default:if("A"!=node.nodeName)for(;void 0!==node.parentNode&&null!=node.parentNode&&"A"!=node.nodeName&&"BODY"!=node.nodeName;)node=node.parentNode;void 0!==node.hash&&node.hash&&node.hostname==location.hostname?resource_url=node.hash:void 0!==node.href&&-1==node.href.indexOf("javascript:")&&(resource_url=node.href),"function"==typeof node.getAttribute&&(void 0!==node.getAttribute("title")&&node.getAttribute("title")&&note_array.push("Title:"+node.getAttribute("title")),void 0!==node.getAttribute("id")&&node.getAttribute("id")&&note_array.push("ID:"+node.getAttribute("id")))}return pos_x=-1,pos_y=-1,position="",void 0!==a.pageX&&void 0!==a.pageY?(pos_x=a.pageX,pos_y=a.pageY):void 0!==a.clientX&&void 0!==a.clientY&&void 0!==document.body.scrollLeft&&void 0!==document.documentElement.scrollLeft&&void 0!==document.body.scrollTop&&void 0!==document.documentElement.scrollTop&&(pos_x=a.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,pos_y=a.clientY+document.body.scrollTop+document.documentElement.scrollTop),pos_x>0&&pos_y>0&&(position=pos_x+","+pos_y),event_description=a.type,"keypress"==a.type?event_description+="; keypress:"+String.fromCharCode(parseInt(a.which)):"click"==a.type&&(event_description+="; which:"+a.which),void 0!==c&&c&&note_array.push(c),note_string=SlimStat._base64_encode(note_array.join(", ")),requested_op="add",1==b?resource_url=resource_url.substring(resource_url.indexOf(location.hostname)+location.hostname.length):0!=b&&2!=b||(requested_op="update"),SlimStat.send_to_server("action=slimtrack&op="+requested_op+"&id="+SlimStat._id+"&ty="+b+"&ref="+SlimStat._base64_encode(document.referrer)+"&res="+SlimStat._base64_encode(resource_url)+"&pos="+position+"&des="+SlimStat._base64_encode(event_description)+"&no="+note_string,d),!0}};"function"!=typeof String.prototype.trim&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),SlimStat.add_event(window,"load",function(){all_links=document.getElementsByTagName("a");for(var a=void 0!==SlimStatParams.extensions_to_track&&SlimStatParams.extensions_to_track?SlimStatParams.extensions_to_track.split(","):[],b=void 0!==SlimStatParams.outbound_classes_rel_href_to_not_track&&SlimStatParams.outbound_classes_rel_href_to_not_track?SlimStatParams.outbound_classes_rel_href_to_not_track.split(","):[],c=0;c<all_links.length;c++){if(linktype=all_links[c].href&&(all_links[c].hostname==location.hostname||-1==all_links[c].href.indexOf("://"))||-1==all_links[c].href.indexOf("javascript:")?2:0,tracking=1,b.length>0){if(1==tracking){classes_current_link=void 0!==all_links[c].className&&all_links[c].className?all_links[c].className.split(" "):[];for(var d=0;d<classes_current_link.length;d++)if(SlimStat.in_array_substring(classes_current_link[d],b)){tracking=0;break}}1==tracking&&void 0!==all_links[c].attributes.rel&&all_links[c].attributes.rel.value&&SlimStat.in_array_substring(all_links[c].attributes.rel.value,b)&&(tracking=0),1==tracking&&void 0!==all_links[c].href&&all_links[c].href&&SlimStat.in_array_substring(all_links[c].href,b)&&(tracking=0)}extension_current_link=all_links[c].pathname.split(/[?#]/)[0].split(".").pop().replace(/[\/\-]/g,""),2==linktype&&a.length>0&&SlimStat.in_array(extension_current_link,a)&&(tracking=1,linktype=1),all_links[c].setAttribute("data-slimstat",(linktype<<1)+tracking),SlimStat.add_event(all_links[c],"click",function(a){link_info=parseInt(this.getAttribute("data-slimstat")),isNaN(link_info)&&(link_info=0),!0&link_info&&SlimStat.ss_track(a,link_info>>1,"")})}});var slimstat_data="",use_beacon=!0;void 0!==SlimStatParams.id&&parseInt(SlimStatParams.id)>0?slimstat_data="action=slimtrack&op=update&id="+SlimStatParams.id:void 0!==SlimStatParams.ci&&(slimstat_data="action=slimtrack&op=add&id="+SlimStatParams.ci+"&ref="+SlimStat._base64_encode(document.referrer)+"&res="+SlimStat._base64_encode(window.location.href),use_beacon=!1),slimstat_data.length>0&&SlimStat.add_event(window,"load",function(){setTimeout(function(){SlimStat.send_to_server(slimstat_data,"")},0)});
1
+ var SlimStat={_id:void 0!==SlimStatParams.id?SlimStatParams.id:"-1.0",_base64_key_str:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_plugins:{acrobat:{substrings:["Adobe","Acrobat"],active_x_strings:["AcroPDF.PDF","PDF.PDFCtrl.5"]},pdfviewer:{substrings:["PDF"],active_x_strings:["AcroPDF.PDF"]},flash:{substrings:["Shockwave","Flash"],active_x_strings:["ShockwaveFlash.ShockwaveFlash"]},mediaplayer:{substrings:["Windows Media"],active_x_strings:["WMPlayer.OCX"]},quicktime:{substrings:["QuickTime"],active_x_strings:["QuickTime.QuickTime"]},silverlight:{substrings:["Silverlight"],active_x_strings:["AgControl.AgControl"]}},_utf8_encode:function(e){var t,n,i="";for(e=e.replace(/\r\n/g,"\n"),t=0;t<e.length;t++)(n=e.charCodeAt(t))<128?i+=String.fromCharCode(n):n>127&&n<2048?(i+=String.fromCharCode(n>>6|192),i+=String.fromCharCode(63&n|128)):(i+=String.fromCharCode(n>>12|224),i+=String.fromCharCode(n>>6&63|128),i+=String.fromCharCode(63&n|128));return i},_base64_encode:function(e){var t,n,i,r,a,o,s,l="",d=0;for(e=SlimStat._utf8_encode(e);d<e.length;)r=(t=e.charCodeAt(d++))>>2,a=(3&t)<<4|(n=e.charCodeAt(d++))>>4,o=(15&n)<<2|(i=e.charCodeAt(d++))>>6,s=63&i,isNaN(n)?o=s=64:isNaN(i)&&(s=64),l=l+SlimStat._base64_key_str.charAt(r)+SlimStat._base64_key_str.charAt(a)+SlimStat._base64_key_str.charAt(o)+SlimStat._base64_key_str.charAt(s);return l},_detect_single_plugin_not_ie:function(e){var t,n,i,r;for(i in navigator.plugins){t=""+navigator.plugins[i].name+navigator.plugins[i].description,n=0;for(r in SlimStat._plugins[e].substrings)-1!=t.indexOf(SlimStat._plugins[e].substrings[r])&&n++;if(n==SlimStat._plugins[e].substrings.length)return!0}return!1},_detect_single_plugin_ie:function(e){var t="",n=!1;for(t in SlimStat._plugins[e].active_x_strings)try{new ActiveXObject(SlimStat._plugins[e].active_x_strings[t]),n=!0}catch(e){}return n},_detect_single_plugin:function(e){return navigator.plugins.length?this.detect=SlimStat._detect_single_plugin_not_ie:this.detect=SlimStat._detect_single_plugin_ie,this.detect(e)},detect_plugins:function(){var e,t=[];for(e in SlimStat._plugins)SlimStat._detect_single_plugin(e)&&t.push(e);return"function"==typeof navigator.javaEnabled&&navigator.javaEnabled()&&t.push("java"),t.join(",")},get_page_performance:function(){return slim_performance=window.performance||window.mozPerformance||window.msPerformance||window.webkitPerformance||{},void 0===slim_performance.timing?0:slim_performance.timing.loadEventEnd-slim_performance.timing.responseEnd},get_server_latency:function(){return slim_performance=window.performance||window.mozPerformance||window.msPerformance||window.webkitPerformance||{},void 0===slim_performance.timing?0:slim_performance.timing.responseEnd-slim_performance.timing.connectEnd},add_event:function(e,t,n){e&&e.addEventListener?e.addEventListener(t,n,!1):e&&e.attachEvent?(e["e"+t+n]=n,e[t+n]=function(){e["e"+t+n](window.event)},e.attachEvent("on"+t,e[t+n])):e["on"+t]=e["e"+t+n]},in_array:function(e,t){for(var n=0;n<t.length;n++)if(t[n].trim()==e)return!0;return!1},in_array_substring:function(e,t){for(var n=0;n<t.length;n++)if(-1!=e.indexOf(t[n].trim()))return!0;return!1},send_to_server:function(e,t){if(void 0===SlimStatParams.ajaxurl||void 0===e)return!1;if(void 0===t&&(t=!0),slimstat_data_with_client_info=e+"&sw="+screen.width+"&sh="+screen.height+"&bw="+window.innerWidth+"&bh="+window.innerHeight+"&sl="+SlimStat.get_server_latency()+"&pp="+SlimStat.get_page_performance()+"&pl="+SlimStat.detect_plugins(),t&&navigator.sendBeacon)navigator.sendBeacon(SlimStatParams.ajaxurl,slimstat_data_with_client_info);else{try{window.XMLHttpRequest?request=new XMLHttpRequest:window.ActiveXObject&&(request=new ActiveXObject("Microsoft.XMLHTTP"))}catch(e){return!1}if(request)return request.open("POST",SlimStatParams.ajaxurl,!0),request.setRequestHeader("Content-type","application/x-www-form-urlencoded"),request.setRequestHeader("X-Requested-With","XMLHttpRequest"),request.withCredentials=!0,request.send(slimstat_data_with_client_info),request.onreadystatechange=function(){4==request.readyState&&(parsed_id=parseInt(request.responseText),!isNaN(parsed_id)&&parsed_id>0&&(SlimStat._id=request.responseText))},!0}return!1},ss_track:function(e,t,n,i){if(e=e||window.event,t=void 0===t?0:parseInt(t),note_array=[],void 0===i&&(i=!0),parsed_id=parseInt(SlimStat._id),isNaN(parsed_id)||parsed_id<=0)return!1;if(node=void 0!==e.target?e.target:void 0!==e.srcElement&&e.srcElement,!node)return!1;switch(3==node.nodeType&&(node=node.parentNode),parent_node=node.parentNode,resource_url="",node.nodeName){case"FORM":void 0!==node.action&&node.action&&(resource_url=node.action);break;case"INPUT":for(;"undefined"!=typeof parent_node&&"FORM"!=parent_node.nodeName&&"BODY"!=parent_node.nodeName;)parent_node=parent_node.parentNode;if(void 0!==parent_node.action&&parent_node.action){resource_url=parent_node.action;break}default:if("A"!=node.nodeName)for(;void 0!==node.parentNode&&null!=node.parentNode&&"A"!=node.nodeName&&"BODY"!=node.nodeName;)node=node.parentNode;void 0!==node.hash&&node.hash&&node.hostname==location.hostname?resource_url=node.hash:void 0!==node.href&&-1==node.href.indexOf("javascript:")&&(resource_url=node.href),"function"==typeof node.getAttribute&&(void 0!==node.getAttribute("title")&&node.getAttribute("title")&&note_array.push("Title:"+node.getAttribute("title")),void 0!==node.getAttribute("id")&&node.getAttribute("id")&&note_array.push("ID:"+node.getAttribute("id")))}return pos_x=-1,pos_y=-1,position="",void 0!==e.pageX&&void 0!==e.pageY?(pos_x=e.pageX,pos_y=e.pageY):void 0!==e.clientX&&void 0!==e.clientY&&void 0!==document.body.scrollLeft&&void 0!==document.documentElement.scrollLeft&&void 0!==document.body.scrollTop&&void 0!==document.documentElement.scrollTop&&(pos_x=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,pos_y=e.clientY+document.body.scrollTop+document.documentElement.scrollTop),pos_x>0&&pos_y>0&&(position=pos_x+","+pos_y),event_description=e.type,"keypress"==e.type?event_description+="; keypress:"+String.fromCharCode(parseInt(e.which)):"click"==e.type&&(event_description+="; which:"+e.which),void 0!==n&&n&&note_array.push(n),note_string=SlimStat._base64_encode(note_array.join(", ")),requested_op="add",1==t?resource_url=resource_url.substring(resource_url.indexOf(location.hostname)+location.hostname.length):0!=t&&2!=t||(requested_op="update"),SlimStat.send_to_server("action=slimtrack&op="+requested_op+"&id="+SlimStat._id+"&ty="+t+"&ref="+SlimStat._base64_encode(document.referrer)+"&res="+SlimStat._base64_encode(resource_url)+"&pos="+position+"&des="+SlimStat._base64_encode(event_description)+"&no="+note_string,i),!0}};"function"!=typeof String.prototype.trim&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),SlimStat.add_event(window,"load",function(){all_links=document.getElementsByTagName("a");for(var e=void 0!==SlimStatParams.extensions_to_track&&SlimStatParams.extensions_to_track?SlimStatParams.extensions_to_track.split(","):[],t=void 0!==SlimStatParams.outbound_classes_rel_href_to_not_track&&SlimStatParams.outbound_classes_rel_href_to_not_track?SlimStatParams.outbound_classes_rel_href_to_not_track.split(","):[],n=0;n<all_links.length;n++){if(linktype=all_links[n].href&&(all_links[n].hostname==location.hostname||-1==all_links[n].href.indexOf("://"))||-1==all_links[n].href.indexOf("javascript:")?2:0,tracking=1,t.length>0){if(1==tracking){classes_current_link=void 0!==all_links[n].className&&all_links[n].className?all_links[n].className.split(" "):[];for(var i=0;i<classes_current_link.length;i++)if(SlimStat.in_array_substring(classes_current_link[i],t)){tracking=0;break}}1==tracking&&void 0!==all_links[n].attributes.rel&&all_links[n].attributes.rel.value&&SlimStat.in_array_substring(all_links[n].attributes.rel.value,t)&&(tracking=0),1==tracking&&void 0!==all_links[n].href&&all_links[n].href&&SlimStat.in_array_substring(all_links[n].href,t)&&(tracking=0)}extension_current_link=all_links[n].pathname.split(/[?#]/)[0].split(".").pop().replace(/[\/\-]/g,""),2==linktype&&e.length>0&&SlimStat.in_array(extension_current_link,e)&&(tracking=1,linktype=1),all_links[n].setAttribute("data-slimstat",(linktype<<1)+tracking),SlimStat.add_event(all_links[n],"click",function(e){link_info=parseInt(this.getAttribute("data-slimstat")),isNaN(link_info)&&(link_info=0),!0&link_info&&SlimStat.ss_track(e,link_info>>1,"")})}});var slimstat_data="",use_beacon=!0;void 0!==SlimStatParams.id&&parseInt(SlimStatParams.id)>0?slimstat_data="action=slimtrack&op=update&id="+SlimStatParams.id:void 0!==SlimStatParams.ci&&(slimstat_data="action=slimtrack&op=add&id="+SlimStatParams.ci+"&ref="+SlimStat._base64_encode(document.referrer)+"&res="+SlimStat._base64_encode(window.location.href),use_beacon=!1),slimstat_data.length>0&&SlimStat.add_event(window,"load",function(){setTimeout(function(){SlimStat.send_to_server(slimstat_data,"")},0)});
wp-slimstat.php CHANGED
@@ -3,7 +3,7 @@
3
  Plugin Name: Slimstat Analytics
4
  Plugin URI: http://wordpress.org/plugins/wp-slimstat/
5
  Description: The leading web analytics plugin for WordPress
6
- Version: 4.6.9.1
7
  Author: Jason Crouse
8
  Author URI: http://www.wp-slimstat.com/
9
  Text Domain: wp-slimstat
@@ -15,7 +15,7 @@ if ( !empty( wp_slimstat::$settings ) ) {
15
  }
16
 
17
  class wp_slimstat {
18
- public static $version = '4.6.9.1';
19
  public static $settings = array();
20
  public static $options = array(); // To be removed, here just for backward compatibility
21
 
@@ -126,6 +126,9 @@ class wp_slimstat {
126
 
127
  // Update the options before shutting down
128
  add_action( 'shutdown', array( __CLASS__, 'slimstat_save_options' ), 100 );
 
 
 
129
  }
130
  // end init
131
 
@@ -1416,6 +1419,95 @@ class wp_slimstat {
1416
  return $output;
1417
  }
1418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1419
  /**
1420
  * Converts a series of comma separated values into an array
1421
  */
@@ -1520,6 +1612,7 @@ class wp_slimstat {
1520
  'restrict_authors_view' => 'yes',
1521
  'capability_can_view' => 'activate_plugins',
1522
  'can_view' => '',
 
1523
  'capability_can_admin' => 'activate_plugins',
1524
  'can_admin' => '',
1525
 
@@ -1670,8 +1763,11 @@ class wp_slimstat {
1670
  foreach ( self::$update_checker as $a_slug ) {
1671
  $a_clean_slug = str_replace( array( 'wp_slimstat_', '_' ), array( '', '-' ), $a_slug );
1672
  if ( !empty( self::$settings[ 'addon_licenses' ][ 'wp-slimstat-' . $a_clean_slug ] ) ) {
 
 
1673
  include_once( plugin_dir_path( __FILE__ ) . 'admin/update-checker/plugin-update-checker.php' );
1674
- $update_checker_objects[] = PucFactory::buildUpdateChecker( 'http://www.wp-slimstat.com/update-checker/?slug=' . $a_clean_slug . '&key=' . urlencode( wp_slimstat::$settings[ 'addon_licenses' ][ 'wp-slimstat-' . $a_clean_slug ] ), dirname( dirname( __FILE__ ) ) . '/wp-slimstat-' . $a_clean_slug . '/index.php', 'wp-slimstat-' . $a_clean_slug );
 
1675
  }
1676
  }
1677
  }
3
  Plugin Name: Slimstat Analytics
4
  Plugin URI: http://wordpress.org/plugins/wp-slimstat/
5
  Description: The leading web analytics plugin for WordPress
6
+ Version: 4.7
7
  Author: Jason Crouse
8
  Author URI: http://www.wp-slimstat.com/
9
  Text Domain: wp-slimstat
15
  }
16
 
17
  class wp_slimstat {
18
+ public static $version = '4.7';
19
  public static $settings = array();
20
  public static $options = array(); // To be removed, here just for backward compatibility
21
 
126
 
127
  // Update the options before shutting down
128
  add_action( 'shutdown', array( __CLASS__, 'slimstat_save_options' ), 100 );
129
+
130
+ // REST API Support
131
+ add_action( 'rest_api_init', array( __CLASS__, 'register_rest_route' ) );
132
  }
133
  // end init
134
 
1419
  return $output;
1420
  }
1421
 
1422
+ public static function rest_api_response( $_request = array() ) {
1423
+ $filters = '';
1424
+ if ( !empty( $_request[ 'filters' ] ) ) {
1425
+ $filters = $_request[ 'filters' ];
1426
+ }
1427
+
1428
+ if ( empty( $_request[ 'dimension' ] ) ) {
1429
+ return new WP_Error( 'rest_invalid', esc_html__( 'The dimension parameter is required. Please review your request and try again.', 'wp-slimstat' ), array( 'status' => 400 ) );
1430
+ }
1431
+
1432
+ if ( empty( $_request[ 'function' ] ) ) {
1433
+ return new WP_Error( 'rest_invalid', esc_html__( 'The function parameter is required. Please review your request and try again.', 'wp-slimstat' ), array( 'status' => 400 ) );
1434
+ }
1435
+
1436
+ include_once( dirname(__FILE__) . '/admin/view/wp-slimstat-db.php' );
1437
+ wp_slimstat_db::init( $filters );
1438
+
1439
+ $response = array(
1440
+ 'function' => htmlentities( $_request[ 'function' ], ENT_QUOTES, 'UTF-8' ),
1441
+ 'dimension' => htmlentities( $_request[ 'dimension' ], ENT_QUOTES, 'UTF-8' ),
1442
+
1443
+ 'data' => 0
1444
+ );
1445
+
1446
+ switch( $_request[ 'function' ] ) {
1447
+ case 'count':
1448
+ case 'count-all':
1449
+ $response[ 'data' ] = wp_slimstat_db::count_records( $_request[ 'dimension' ], '', strpos( $_request[ 'function' ], '-all') === false );
1450
+ break;
1451
+
1452
+ case 'recent':
1453
+ case 'recent-all':
1454
+ case 'top':
1455
+ case 'top-all':
1456
+ $function = 'get_' . str_replace( '-all', '', $_request[ 'function' ] );
1457
+
1458
+ // Retrieve the data
1459
+ $response[ 'data' ] = array_values( wp_slimstat_db::$function( $_request[ 'dimension' ], '', '', strpos( $_request[ 'function' ], '-all' ) === false ) );
1460
+ break;
1461
+
1462
+ default:
1463
+ // This should never happen, because of the 'enum' condition for this parameter. But never say never...
1464
+ $response[ 'data' ] = new WP_Error( 'rest_invalid', esc_html__( 'Valid function values are count, count-all, recent, recent-all, top and top-all. Please review your request and try again.', 'wp-slimstat' ), array( 'status' => 400 ) );
1465
+ break;
1466
+ }
1467
+
1468
+ return rest_ensure_response( $response );
1469
+ }
1470
+
1471
+ public static function rest_api_authorization( $_request = array() ) {
1472
+ if ( empty( $_request[ 'token' ] ) ) {
1473
+ return new WP_Error( 'rest_invalid', esc_html__( 'Please specify a valid token in order to access this REST API.', 'wp-slimstat' ), array( 'status' => 400 ) );
1474
+ }
1475
+
1476
+ if ( !in_array( $_request[ 'token' ], self::string_to_array( self::$settings['rest_api_tokens'] ) ) ) {
1477
+ return false;
1478
+ }
1479
+
1480
+ return true;
1481
+ }
1482
+
1483
+ public static function register_rest_route() {
1484
+ register_rest_route( 'slimstat/v1', '/get', array(
1485
+ 'methods' => WP_REST_Server::READABLE,
1486
+ 'callback' => array( __CLASS__, 'rest_api_response' ),
1487
+ 'permission_callback' => array( __CLASS__, 'rest_api_authorization' ),
1488
+ 'args' => array(
1489
+ 'token' => array(
1490
+ 'description' => __( 'You will need to specify a valid token to be able to query the data. Tokens are defined in Slimstat > Settings > Access Control.', 'wp-slimstat' ),
1491
+ 'type' => 'string'
1492
+ ),
1493
+ 'function' => array(
1494
+ 'description' => __( 'This parameter specifies the type of QUERY for the dimension. Valid values are: count, count-all, recent, recent-all, top and top-all.', 'wp-slimstat' ),
1495
+ 'type' => 'string',
1496
+ 'enum' => array( 'count', 'count-all', 'recent', 'recent-all', 'top', 'top-all' )
1497
+ ),
1498
+ 'dimension' => array(
1499
+ 'description' => __( 'This parameter indicates what dimension to return: * (all data), ip, resource, browser, operating system, etc. You can only specify one dimension at a time.', 'wp-slimstat' ),
1500
+ 'type' => 'string',
1501
+ 'enum' => array( '*', 'id', 'ip', 'username', 'country', 'referer', 'resource', 'searchterms', 'browser', 'platform', 'language', 'resolution', 'content_type', 'content_id', 'outbound_resource' )
1502
+ ),
1503
+ 'filters' => array(
1504
+ 'description' => __( 'This parameter is used to filter a given dimension (resources, browsers, operating systems, etc) so that it satisfies certain conditions (i.e.: browser contains Chrome). Please make sure to urlencode this value, and to use the usual filter format: browser contains Chrome&&&referer contains slim (encoded: browser%20contains%20Chrome%26%26%26referer%20contains%20slim)', 'wp-slimstat' ),
1505
+ 'type' => 'string'
1506
+ )
1507
+ )
1508
+ ) );
1509
+ }
1510
+
1511
  /**
1512
  * Converts a series of comma separated values into an array
1513
  */
1612
  'restrict_authors_view' => 'yes',
1613
  'capability_can_view' => 'activate_plugins',
1614
  'can_view' => '',
1615
+ 'rest_api_tokens' => wp_hash( uniqid( time() - 3600, true ) ),
1616
  'capability_can_admin' => 'activate_plugins',
1617
  'can_admin' => '',
1618
 
1763
  foreach ( self::$update_checker as $a_slug ) {
1764
  $a_clean_slug = str_replace( array( 'wp_slimstat_', '_' ), array( '', '-' ), $a_slug );
1765
  if ( !empty( self::$settings[ 'addon_licenses' ][ 'wp-slimstat-' . $a_clean_slug ] ) ) {
1766
+
1767
+ // This is only included if add-ons are installed
1768
  include_once( plugin_dir_path( __FILE__ ) . 'admin/update-checker/plugin-update-checker.php' );
1769
+
1770
+ $update_checker_objects[] = Puc_v4_Factory::buildUpdateChecker( 'http://www.wp-slimstat.com/update-checker/?slug=' . $a_clean_slug . '&key=' . urlencode( self::$settings[ 'addon_licenses' ][ 'wp-slimstat-' . $a_clean_slug ] ), dirname( dirname( __FILE__ ) ) . '/wp-slimstat-' . $a_clean_slug . '/index.php', 'wp-slimstat-' . $a_clean_slug );
1771
  }
1772
  }
1773
  }