updates.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  1. /**
  2. * Functions for ajaxified updates, deletions and installs inside the WordPress admin.
  3. *
  4. * @version 4.2.0
  5. *
  6. * @package WordPress
  7. * @subpackage Administration
  8. */
  9. /* global pagenow */
  10. /**
  11. * @param {jQuery} $ jQuery object.
  12. * @param {object} wp WP object.
  13. * @param {object} settings WP Updates settings.
  14. * @param {string} settings.ajax_nonce AJAX nonce.
  15. * @param {object} settings.l10n Translation strings.
  16. * @param {object=} settings.plugins Base names of plugins in their different states.
  17. * @param {Array} settings.plugins.all Base names of all plugins.
  18. * @param {Array} settings.plugins.active Base names of active plugins.
  19. * @param {Array} settings.plugins.inactive Base names of inactive plugins.
  20. * @param {Array} settings.plugins.upgrade Base names of plugins with updates available.
  21. * @param {Array} settings.plugins.recently_activated Base names of recently activated plugins.
  22. * @param {object=} settings.themes Plugin/theme status information or null.
  23. * @param {number} settings.themes.all Amount of all themes.
  24. * @param {number} settings.themes.upgrade Amount of themes with updates available.
  25. * @param {number} settings.themes.disabled Amount of disabled themes.
  26. * @param {object=} settings.totals Combined information for available update counts.
  27. * @param {number} settings.totals.count Holds the amount of available updates.
  28. */
  29. (function( $, wp, settings ) {
  30. var $document = $( document );
  31. wp = wp || {};
  32. /**
  33. * The WP Updates object.
  34. *
  35. * @since 4.2.0
  36. *
  37. * @type {object}
  38. */
  39. wp.updates = {};
  40. /**
  41. * User nonce for ajax calls.
  42. *
  43. * @since 4.2.0
  44. *
  45. * @type {string}
  46. */
  47. wp.updates.ajaxNonce = settings.ajax_nonce;
  48. /**
  49. * Localized strings.
  50. *
  51. * @since 4.2.0
  52. *
  53. * @type {object}
  54. */
  55. wp.updates.l10n = settings.l10n;
  56. /**
  57. * Current search term.
  58. *
  59. * @since 4.6.0
  60. *
  61. * @type {string}
  62. */
  63. wp.updates.searchTerm = '';
  64. /**
  65. * Whether filesystem credentials need to be requested from the user.
  66. *
  67. * @since 4.2.0
  68. *
  69. * @type {bool}
  70. */
  71. wp.updates.shouldRequestFilesystemCredentials = false;
  72. /**
  73. * Filesystem credentials to be packaged along with the request.
  74. *
  75. * @since 4.2.0
  76. * @since 4.6.0 Added `available` property to indicate whether credentials have been provided.
  77. *
  78. * @type {object} filesystemCredentials Holds filesystem credentials.
  79. * @type {object} filesystemCredentials.ftp Holds FTP credentials.
  80. * @type {string} filesystemCredentials.ftp.host FTP host. Default empty string.
  81. * @type {string} filesystemCredentials.ftp.username FTP user name. Default empty string.
  82. * @type {string} filesystemCredentials.ftp.password FTP password. Default empty string.
  83. * @type {string} filesystemCredentials.ftp.connectionType Type of FTP connection. 'ssh', 'ftp', or 'ftps'.
  84. * Default empty string.
  85. * @type {object} filesystemCredentials.ssh Holds SSH credentials.
  86. * @type {string} filesystemCredentials.ssh.publicKey The public key. Default empty string.
  87. * @type {string} filesystemCredentials.ssh.privateKey The private key. Default empty string.
  88. * @type {string} filesystemCredentials.fsNonce Filesystem credentials form nonce.
  89. * @type {bool} filesystemCredentials.available Whether filesystem credentials have been provided.
  90. * Default 'false'.
  91. */
  92. wp.updates.filesystemCredentials = {
  93. ftp: {
  94. host: '',
  95. username: '',
  96. password: '',
  97. connectionType: ''
  98. },
  99. ssh: {
  100. publicKey: '',
  101. privateKey: ''
  102. },
  103. fsNonce: '',
  104. available: false
  105. };
  106. /**
  107. * Whether we're waiting for an Ajax request to complete.
  108. *
  109. * @since 4.2.0
  110. * @since 4.6.0 More accurately named `ajaxLocked`.
  111. *
  112. * @type {bool}
  113. */
  114. wp.updates.ajaxLocked = false;
  115. /**
  116. * Admin notice template.
  117. *
  118. * @since 4.6.0
  119. *
  120. * @type {function} A function that lazily-compiles the template requested.
  121. */
  122. wp.updates.adminNotice = wp.template( 'wp-updates-admin-notice' );
  123. /**
  124. * Update queue.
  125. *
  126. * If the user tries to update a plugin while an update is
  127. * already happening, it can be placed in this queue to perform later.
  128. *
  129. * @since 4.2.0
  130. * @since 4.6.0 More accurately named `queue`.
  131. *
  132. * @type {Array.object}
  133. */
  134. wp.updates.queue = [];
  135. /**
  136. * Holds a jQuery reference to return focus to when exiting the request credentials modal.
  137. *
  138. * @since 4.2.0
  139. *
  140. * @type {jQuery}
  141. */
  142. wp.updates.$elToReturnFocusToFromCredentialsModal = undefined;
  143. /**
  144. * Adds or updates an admin notice.
  145. *
  146. * @since 4.6.0
  147. *
  148. * @param {object} data
  149. * @param {*=} data.selector Optional. Selector of an element to be replaced with the admin notice.
  150. * @param {string=} data.id Optional. Unique id that will be used as the notice's id attribute.
  151. * @param {string=} data.className Optional. Class names that will be used in the admin notice.
  152. * @param {string=} data.message Optional. The message displayed in the notice.
  153. * @param {number=} data.successes Optional. The amount of successful operations.
  154. * @param {number=} data.errors Optional. The amount of failed operations.
  155. * @param {Array=} data.errorMessages Optional. Error messages of failed operations.
  156. *
  157. */
  158. wp.updates.addAdminNotice = function( data ) {
  159. var $notice = $( data.selector ), $adminNotice;
  160. delete data.selector;
  161. $adminNotice = wp.updates.adminNotice( data );
  162. // Check if this admin notice already exists.
  163. if ( ! $notice.length ) {
  164. $notice = $( '#' + data.id );
  165. }
  166. if ( $notice.length ) {
  167. $notice.replaceWith( $adminNotice );
  168. } else {
  169. if ( 'customize' === pagenow ) {
  170. $( '.customize-themes-notifications' ).append( $adminNotice );
  171. } else {
  172. $( '.wrap' ).find( '> h1' ).after( $adminNotice );
  173. }
  174. }
  175. $document.trigger( 'wp-updates-notice-added' );
  176. };
  177. /**
  178. * Handles Ajax requests to WordPress.
  179. *
  180. * @since 4.6.0
  181. *
  182. * @param {string} action The type of Ajax request ('update-plugin', 'install-theme', etc).
  183. * @param {object} data Data that needs to be passed to the ajax callback.
  184. * @return {$.promise} A jQuery promise that represents the request,
  185. * decorated with an abort() method.
  186. */
  187. wp.updates.ajax = function( action, data ) {
  188. var options = {};
  189. if ( wp.updates.ajaxLocked ) {
  190. wp.updates.queue.push( {
  191. action: action,
  192. data: data
  193. } );
  194. // Return a Deferred object so callbacks can always be registered.
  195. return $.Deferred();
  196. }
  197. wp.updates.ajaxLocked = true;
  198. if ( data.success ) {
  199. options.success = data.success;
  200. delete data.success;
  201. }
  202. if ( data.error ) {
  203. options.error = data.error;
  204. delete data.error;
  205. }
  206. options.data = _.extend( data, {
  207. action: action,
  208. _ajax_nonce: wp.updates.ajaxNonce,
  209. _fs_nonce: wp.updates.filesystemCredentials.fsNonce,
  210. username: wp.updates.filesystemCredentials.ftp.username,
  211. password: wp.updates.filesystemCredentials.ftp.password,
  212. hostname: wp.updates.filesystemCredentials.ftp.hostname,
  213. connection_type: wp.updates.filesystemCredentials.ftp.connectionType,
  214. public_key: wp.updates.filesystemCredentials.ssh.publicKey,
  215. private_key: wp.updates.filesystemCredentials.ssh.privateKey
  216. } );
  217. return wp.ajax.send( options ).always( wp.updates.ajaxAlways );
  218. };
  219. /**
  220. * Actions performed after every Ajax request.
  221. *
  222. * @since 4.6.0
  223. *
  224. * @param {object} response
  225. * @param {array=} response.debug Optional. Debug information.
  226. * @param {string=} response.errorCode Optional. Error code for an error that occurred.
  227. */
  228. wp.updates.ajaxAlways = function( response ) {
  229. if ( ! response.errorCode || 'unable_to_connect_to_filesystem' !== response.errorCode ) {
  230. wp.updates.ajaxLocked = false;
  231. wp.updates.queueChecker();
  232. }
  233. if ( 'undefined' !== typeof response.debug && window.console && window.console.log ) {
  234. _.map( response.debug, function( message ) {
  235. window.console.log( $( '<p />' ).html( message ).text() );
  236. } );
  237. }
  238. };
  239. /**
  240. * Refreshes update counts everywhere on the screen.
  241. *
  242. * @since 4.7.0
  243. */
  244. wp.updates.refreshCount = function() {
  245. var $adminBarUpdates = $( '#wp-admin-bar-updates' ),
  246. $dashboardNavMenuUpdateCount = $( 'a[href="update-core.php"] .update-plugins' ),
  247. $pluginsNavMenuUpdateCount = $( 'a[href="plugins.php"] .update-plugins' ),
  248. $appearanceNavMenuUpdateCount = $( 'a[href="themes.php"] .update-plugins' ),
  249. itemCount;
  250. $adminBarUpdates.find( '.ab-item' ).removeAttr( 'title' );
  251. $adminBarUpdates.find( '.ab-label' ).text( settings.totals.counts.total );
  252. // Remove the update count from the toolbar if it's zero.
  253. if ( 0 === settings.totals.counts.total ) {
  254. $adminBarUpdates.find( '.ab-label' ).parents( 'li' ).remove();
  255. }
  256. // Update the "Updates" menu item.
  257. $dashboardNavMenuUpdateCount.each( function( index, element ) {
  258. element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.total );
  259. } );
  260. if ( settings.totals.counts.total > 0 ) {
  261. $dashboardNavMenuUpdateCount.find( '.update-count' ).text( settings.totals.counts.total );
  262. } else {
  263. $dashboardNavMenuUpdateCount.remove();
  264. }
  265. // Update the "Plugins" menu item.
  266. $pluginsNavMenuUpdateCount.each( function( index, element ) {
  267. element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.plugins );
  268. } );
  269. if ( settings.totals.counts.total > 0 ) {
  270. $pluginsNavMenuUpdateCount.find( '.plugin-count' ).text( settings.totals.counts.plugins );
  271. } else {
  272. $pluginsNavMenuUpdateCount.remove();
  273. }
  274. // Update the "Appearance" menu item.
  275. $appearanceNavMenuUpdateCount.each( function( index, element ) {
  276. element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.themes );
  277. } );
  278. if ( settings.totals.counts.total > 0 ) {
  279. $appearanceNavMenuUpdateCount.find( '.theme-count' ).text( settings.totals.counts.themes );
  280. } else {
  281. $appearanceNavMenuUpdateCount.remove();
  282. }
  283. // Update list table filter navigation.
  284. if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
  285. itemCount = settings.totals.counts.plugins;
  286. } else if ( 'themes' === pagenow || 'themes-network' === pagenow ) {
  287. itemCount = settings.totals.counts.themes;
  288. }
  289. if ( itemCount > 0 ) {
  290. $( '.subsubsub .upgrade .count' ).text( '(' + itemCount + ')' );
  291. } else {
  292. $( '.subsubsub .upgrade' ).remove();
  293. $( '.subsubsub li:last' ).html( function() { return $( this ).children(); } );
  294. }
  295. };
  296. /**
  297. * Decrements the update counts throughout the various menus.
  298. *
  299. * This includes the toolbar, the "Updates" menu item and the menu items
  300. * for plugins and themes.
  301. *
  302. * @since 3.9.0
  303. *
  304. * @param {string} type The type of item that was updated or deleted.
  305. * Can be 'plugin', 'theme'.
  306. */
  307. wp.updates.decrementCount = function( type ) {
  308. settings.totals.counts.total = Math.max( --settings.totals.counts.total, 0 );
  309. if ( 'plugin' === type ) {
  310. settings.totals.counts.plugins = Math.max( --settings.totals.counts.plugins, 0 );
  311. } else if ( 'theme' === type ) {
  312. settings.totals.counts.themes = Math.max( --settings.totals.counts.themes, 0 );
  313. }
  314. wp.updates.refreshCount( type );
  315. };
  316. /**
  317. * Sends an Ajax request to the server to update a plugin.
  318. *
  319. * @since 4.2.0
  320. * @since 4.6.0 More accurately named `updatePlugin`.
  321. *
  322. * @param {object} args Arguments.
  323. * @param {string} args.plugin Plugin basename.
  324. * @param {string} args.slug Plugin slug.
  325. * @param {updatePluginSuccess=} args.success Optional. Success callback. Default: wp.updates.updatePluginSuccess
  326. * @param {updatePluginError=} args.error Optional. Error callback. Default: wp.updates.updatePluginError
  327. * @return {$.promise} A jQuery promise that represents the request,
  328. * decorated with an abort() method.
  329. */
  330. wp.updates.updatePlugin = function( args ) {
  331. var $updateRow, $card, $message, message;
  332. args = _.extend( {
  333. success: wp.updates.updatePluginSuccess,
  334. error: wp.updates.updatePluginError
  335. }, args );
  336. if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
  337. $updateRow = $( 'tr[data-plugin="' + args.plugin + '"]' );
  338. $message = $updateRow.find( '.update-message' ).removeClass( 'notice-error' ).addClass( 'updating-message notice-warning' ).find( 'p' );
  339. message = wp.updates.l10n.pluginUpdatingLabel.replace( '%s', $updateRow.find( '.plugin-title strong' ).text() );
  340. } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) {
  341. $card = $( '.plugin-card-' + args.slug );
  342. $message = $card.find( '.update-now' ).addClass( 'updating-message' );
  343. message = wp.updates.l10n.pluginUpdatingLabel.replace( '%s', $message.data( 'name' ) );
  344. // Remove previous error messages, if any.
  345. $card.removeClass( 'plugin-card-update-failed' ).find( '.notice.notice-error' ).remove();
  346. }
  347. if ( $message.html() !== wp.updates.l10n.updating ) {
  348. $message.data( 'originaltext', $message.html() );
  349. }
  350. $message
  351. .attr( 'aria-label', message )
  352. .text( wp.updates.l10n.updating );
  353. $document.trigger( 'wp-plugin-updating', args );
  354. return wp.updates.ajax( 'update-plugin', args );
  355. };
  356. /**
  357. * Updates the UI appropriately after a successful plugin update.
  358. *
  359. * @since 4.2.0
  360. * @since 4.6.0 More accurately named `updatePluginSuccess`.
  361. *
  362. * @typedef {object} updatePluginSuccess
  363. * @param {object} response Response from the server.
  364. * @param {string} response.slug Slug of the plugin to be updated.
  365. * @param {string} response.plugin Basename of the plugin to be updated.
  366. * @param {string} response.pluginName Name of the plugin to be updated.
  367. * @param {string} response.oldVersion Old version of the plugin.
  368. * @param {string} response.newVersion New version of the plugin.
  369. */
  370. wp.updates.updatePluginSuccess = function( response ) {
  371. var $pluginRow, $updateMessage, newText;
  372. if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
  373. $pluginRow = $( 'tr[data-plugin="' + response.plugin + '"]' )
  374. .removeClass( 'update' )
  375. .addClass( 'updated' );
  376. $updateMessage = $pluginRow.find( '.update-message' )
  377. .removeClass( 'updating-message notice-warning' )
  378. .addClass( 'updated-message notice-success' ).find( 'p' );
  379. // Update the version number in the row.
  380. newText = $pluginRow.find( '.plugin-version-author-uri' ).html().replace( response.oldVersion, response.newVersion );
  381. $pluginRow.find( '.plugin-version-author-uri' ).html( newText );
  382. } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) {
  383. $updateMessage = $( '.plugin-card-' + response.slug ).find( '.update-now' )
  384. .removeClass( 'updating-message' )
  385. .addClass( 'button-disabled updated-message' );
  386. }
  387. $updateMessage
  388. .attr( 'aria-label', wp.updates.l10n.pluginUpdatedLabel.replace( '%s', response.pluginName ) )
  389. .text( wp.updates.l10n.pluginUpdated );
  390. wp.a11y.speak( wp.updates.l10n.updatedMsg, 'polite' );
  391. wp.updates.decrementCount( 'plugin' );
  392. $document.trigger( 'wp-plugin-update-success', response );
  393. };
  394. /**
  395. * Updates the UI appropriately after a failed plugin update.
  396. *
  397. * @since 4.2.0
  398. * @since 4.6.0 More accurately named `updatePluginError`.
  399. *
  400. * @typedef {object} updatePluginError
  401. * @param {object} response Response from the server.
  402. * @param {string} response.slug Slug of the plugin to be updated.
  403. * @param {string} response.plugin Basename of the plugin to be updated.
  404. * @param {string=} response.pluginName Optional. Name of the plugin to be updated.
  405. * @param {string} response.errorCode Error code for the error that occurred.
  406. * @param {string} response.errorMessage The error that occurred.
  407. */
  408. wp.updates.updatePluginError = function( response ) {
  409. var $card, $message, errorMessage;
  410. if ( ! wp.updates.isValidResponse( response, 'update' ) ) {
  411. return;
  412. }
  413. if ( wp.updates.maybeHandleCredentialError( response, 'update-plugin' ) ) {
  414. return;
  415. }
  416. errorMessage = wp.updates.l10n.updateFailed.replace( '%s', response.errorMessage );
  417. if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
  418. if ( response.plugin ) {
  419. $message = $( 'tr[data-plugin="' + response.plugin + '"]' ).find( '.update-message' );
  420. } else {
  421. $message = $( 'tr[data-slug="' + response.slug + '"]' ).find( '.update-message' );
  422. }
  423. $message.removeClass( 'updating-message notice-warning' ).addClass( 'notice-error' ).find( 'p' ).html( errorMessage );
  424. if ( response.pluginName ) {
  425. $message.find( 'p' )
  426. .attr( 'aria-label', wp.updates.l10n.pluginUpdateFailedLabel.replace( '%s', response.pluginName ) );
  427. } else {
  428. $message.find( 'p' ).removeAttr( 'aria-label' );
  429. }
  430. } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) {
  431. $card = $( '.plugin-card-' + response.slug )
  432. .addClass( 'plugin-card-update-failed' )
  433. .append( wp.updates.adminNotice( {
  434. className: 'update-message notice-error notice-alt is-dismissible',
  435. message: errorMessage
  436. } ) );
  437. $card.find( '.update-now' )
  438. .text( wp.updates.l10n.updateFailedShort ).removeClass( 'updating-message' );
  439. if ( response.pluginName ) {
  440. $card.find( '.update-now' )
  441. .attr( 'aria-label', wp.updates.l10n.pluginUpdateFailedLabel.replace( '%s', response.pluginName ) );
  442. } else {
  443. $card.find( '.update-now' ).removeAttr( 'aria-label' );
  444. }
  445. $card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() {
  446. // Use same delay as the total duration of the notice fadeTo + slideUp animation.
  447. setTimeout( function() {
  448. $card
  449. .removeClass( 'plugin-card-update-failed' )
  450. .find( '.column-name a' ).focus();
  451. $card.find( '.update-now' )
  452. .attr( 'aria-label', false )
  453. .text( wp.updates.l10n.updateNow );
  454. }, 200 );
  455. } );
  456. }
  457. wp.a11y.speak( errorMessage, 'assertive' );
  458. $document.trigger( 'wp-plugin-update-error', response );
  459. };
  460. /**
  461. * Sends an Ajax request to the server to install a plugin.
  462. *
  463. * @since 4.6.0
  464. *
  465. * @param {object} args Arguments.
  466. * @param {string} args.slug Plugin identifier in the WordPress.org Plugin repository.
  467. * @param {installPluginSuccess=} args.success Optional. Success callback. Default: wp.updates.installPluginSuccess
  468. * @param {installPluginError=} args.error Optional. Error callback. Default: wp.updates.installPluginError
  469. * @return {$.promise} A jQuery promise that represents the request,
  470. * decorated with an abort() method.
  471. */
  472. wp.updates.installPlugin = function( args ) {
  473. var $card = $( '.plugin-card-' + args.slug ),
  474. $message = $card.find( '.install-now' );
  475. args = _.extend( {
  476. success: wp.updates.installPluginSuccess,
  477. error: wp.updates.installPluginError
  478. }, args );
  479. if ( 'import' === pagenow ) {
  480. $message = $( '[data-slug="' + args.slug + '"]' );
  481. }
  482. if ( $message.html() !== wp.updates.l10n.installing ) {
  483. $message.data( 'originaltext', $message.html() );
  484. }
  485. $message
  486. .addClass( 'updating-message' )
  487. .attr( 'aria-label', wp.updates.l10n.pluginInstallingLabel.replace( '%s', $message.data( 'name' ) ) )
  488. .text( wp.updates.l10n.installing );
  489. wp.a11y.speak( wp.updates.l10n.installingMsg, 'polite' );
  490. // Remove previous error messages, if any.
  491. $card.removeClass( 'plugin-card-install-failed' ).find( '.notice.notice-error' ).remove();
  492. $document.trigger( 'wp-plugin-installing', args );
  493. return wp.updates.ajax( 'install-plugin', args );
  494. };
  495. /**
  496. * Updates the UI appropriately after a successful plugin install.
  497. *
  498. * @since 4.6.0
  499. *
  500. * @typedef {object} installPluginSuccess
  501. * @param {object} response Response from the server.
  502. * @param {string} response.slug Slug of the installed plugin.
  503. * @param {string} response.pluginName Name of the installed plugin.
  504. * @param {string} response.activateUrl URL to activate the just installed plugin.
  505. */
  506. wp.updates.installPluginSuccess = function( response ) {
  507. var $message = $( '.plugin-card-' + response.slug ).find( '.install-now' );
  508. $message
  509. .removeClass( 'updating-message' )
  510. .addClass( 'updated-message installed' )
  511. .attr( 'aria-label', wp.updates.l10n.pluginInstalledLabel.replace( '%s', response.pluginName ) )
  512. .text( wp.updates.l10n.pluginInstalled );
  513. if ( $message.hasClass( 'button-primary' ) ) {
  514. $message.addClass( 'button-primary-disabled' );
  515. } else {
  516. $message.addClass( 'button-disabled' );
  517. }
  518. wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' );
  519. $document.trigger( 'wp-plugin-install-success', response );
  520. if ( response.activateUrl ) {
  521. setTimeout( function() {
  522. // Transform the 'Install' button into an 'Activate' button.
  523. $message.removeClass( 'install-now installed button-primary-disabled button-secondary-disabled button-disabled updated-message' )
  524. .addClass( 'activate-now' )
  525. .attr( 'href', response.activateUrl )
  526. .attr( 'aria-label', wp.updates.l10n.activatePluginLabel.replace( '%s', response.pluginName ) )
  527. .text( response.activateLabel || wp.updates.l10n.activatePlugin );
  528. }, 1000 );
  529. }
  530. };
  531. /**
  532. * Updates the UI appropriately after a failed plugin install.
  533. *
  534. * @since 4.6.0
  535. *
  536. * @typedef {object} installPluginError
  537. * @param {object} response Response from the server.
  538. * @param {string} response.slug Slug of the plugin to be installed.
  539. * @param {string=} response.pluginName Optional. Name of the plugin to be installed.
  540. * @param {string} response.errorCode Error code for the error that occurred.
  541. * @param {string} response.errorMessage The error that occurred.
  542. */
  543. wp.updates.installPluginError = function( response ) {
  544. var $card = $( '.plugin-card-' + response.slug ),
  545. $button = $card.find( '.install-now' ),
  546. errorMessage;
  547. if ( ! wp.updates.isValidResponse( response, 'install' ) ) {
  548. return;
  549. }
  550. if ( wp.updates.maybeHandleCredentialError( response, 'install-plugin' ) ) {
  551. return;
  552. }
  553. errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage );
  554. $card
  555. .addClass( 'plugin-card-update-failed' )
  556. .append( '<div class="notice notice-error notice-alt is-dismissible"><p>' + errorMessage + '</p></div>' );
  557. $card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() {
  558. // Use same delay as the total duration of the notice fadeTo + slideUp animation.
  559. setTimeout( function() {
  560. $card
  561. .removeClass( 'plugin-card-update-failed' )
  562. .find( '.column-name a' ).focus();
  563. }, 200 );
  564. } );
  565. $button
  566. .removeClass( 'updating-message' ).addClass( 'button-disabled' )
  567. .attr( 'aria-label', wp.updates.l10n.pluginInstallFailedLabel.replace( '%s', $button.data( 'name' ) ) )
  568. .text( wp.updates.l10n.installFailedShort );
  569. wp.a11y.speak( errorMessage, 'assertive' );
  570. $document.trigger( 'wp-plugin-install-error', response );
  571. };
  572. /**
  573. * Updates the UI appropriately after a successful importer install.
  574. *
  575. * @since 4.6.0
  576. *
  577. * @typedef {object} installImporterSuccess
  578. * @param {object} response Response from the server.
  579. * @param {string} response.slug Slug of the installed plugin.
  580. * @param {string} response.pluginName Name of the installed plugin.
  581. * @param {string} response.activateUrl URL to activate the just installed plugin.
  582. */
  583. wp.updates.installImporterSuccess = function( response ) {
  584. wp.updates.addAdminNotice( {
  585. id: 'install-success',
  586. className: 'notice-success is-dismissible',
  587. message: wp.updates.l10n.importerInstalledMsg.replace( '%s', response.activateUrl + '&from=import' )
  588. } );
  589. $( '[data-slug="' + response.slug + '"]' )
  590. .removeClass( 'install-now updating-message' )
  591. .addClass( 'activate-now' )
  592. .attr({
  593. 'href': response.activateUrl + '&from=import',
  594. 'aria-label': wp.updates.l10n.activateImporterLabel.replace( '%s', response.pluginName )
  595. })
  596. .text( wp.updates.l10n.activateImporter );
  597. wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' );
  598. $document.trigger( 'wp-importer-install-success', response );
  599. };
  600. /**
  601. * Updates the UI appropriately after a failed importer install.
  602. *
  603. * @since 4.6.0
  604. *
  605. * @typedef {object} installImporterError
  606. * @param {object} response Response from the server.
  607. * @param {string} response.slug Slug of the plugin to be installed.
  608. * @param {string=} response.pluginName Optional. Name of the plugin to be installed.
  609. * @param {string} response.errorCode Error code for the error that occurred.
  610. * @param {string} response.errorMessage The error that occurred.
  611. */
  612. wp.updates.installImporterError = function( response ) {
  613. var errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage ),
  614. $installLink = $( '[data-slug="' + response.slug + '"]' ),
  615. pluginName = $installLink.data( 'name' );
  616. if ( ! wp.updates.isValidResponse( response, 'install' ) ) {
  617. return;
  618. }
  619. if ( wp.updates.maybeHandleCredentialError( response, 'install-plugin' ) ) {
  620. return;
  621. }
  622. wp.updates.addAdminNotice( {
  623. id: response.errorCode,
  624. className: 'notice-error is-dismissible',
  625. message: errorMessage
  626. } );
  627. $installLink
  628. .removeClass( 'updating-message' )
  629. .text( wp.updates.l10n.installNow )
  630. .attr( 'aria-label', wp.updates.l10n.installNowLabel.replace( '%s', pluginName ) );
  631. wp.a11y.speak( errorMessage, 'assertive' );
  632. $document.trigger( 'wp-importer-install-error', response );
  633. };
  634. /**
  635. * Sends an Ajax request to the server to delete a plugin.
  636. *
  637. * @since 4.6.0
  638. *
  639. * @param {object} args Arguments.
  640. * @param {string} args.plugin Basename of the plugin to be deleted.
  641. * @param {string} args.slug Slug of the plugin to be deleted.
  642. * @param {deletePluginSuccess=} args.success Optional. Success callback. Default: wp.updates.deletePluginSuccess
  643. * @param {deletePluginError=} args.error Optional. Error callback. Default: wp.updates.deletePluginError
  644. * @return {$.promise} A jQuery promise that represents the request,
  645. * decorated with an abort() method.
  646. */
  647. wp.updates.deletePlugin = function( args ) {
  648. var $link = $( '[data-plugin="' + args.plugin + '"]' ).find( '.row-actions a.delete' );
  649. args = _.extend( {
  650. success: wp.updates.deletePluginSuccess,
  651. error: wp.updates.deletePluginError
  652. }, args );
  653. if ( $link.html() !== wp.updates.l10n.deleting ) {
  654. $link
  655. .data( 'originaltext', $link.html() )
  656. .text( wp.updates.l10n.deleting );
  657. }
  658. wp.a11y.speak( wp.updates.l10n.deleting, 'polite' );
  659. $document.trigger( 'wp-plugin-deleting', args );
  660. return wp.updates.ajax( 'delete-plugin', args );
  661. };
  662. /**
  663. * Updates the UI appropriately after a successful plugin deletion.
  664. *
  665. * @since 4.6.0
  666. *
  667. * @typedef {object} deletePluginSuccess
  668. * @param {object} response Response from the server.
  669. * @param {string} response.slug Slug of the plugin that was deleted.
  670. * @param {string} response.plugin Base name of the plugin that was deleted.
  671. * @param {string} response.pluginName Name of the plugin that was deleted.
  672. */
  673. wp.updates.deletePluginSuccess = function( response ) {
  674. // Removes the plugin and updates rows.
  675. $( '[data-plugin="' + response.plugin + '"]' ).css( { backgroundColor: '#faafaa' } ).fadeOut( 350, function() {
  676. var $form = $( '#bulk-action-form' ),
  677. $views = $( '.subsubsub' ),
  678. $pluginRow = $( this ),
  679. columnCount = $form.find( 'thead th:not(.hidden), thead td' ).length,
  680. pluginDeletedRow = wp.template( 'item-deleted-row' ),
  681. /** @type {object} plugins Base names of plugins in their different states. */
  682. plugins = settings.plugins;
  683. // Add a success message after deleting a plugin.
  684. if ( ! $pluginRow.hasClass( 'plugin-update-tr' ) ) {
  685. $pluginRow.after(
  686. pluginDeletedRow( {
  687. slug: response.slug,
  688. plugin: response.plugin,
  689. colspan: columnCount,
  690. name: response.pluginName
  691. } )
  692. );
  693. }
  694. $pluginRow.remove();
  695. // Remove plugin from update count.
  696. if ( -1 !== _.indexOf( plugins.upgrade, response.plugin ) ) {
  697. plugins.upgrade = _.without( plugins.upgrade, response.plugin );
  698. wp.updates.decrementCount( 'plugin' );
  699. }
  700. // Remove from views.
  701. if ( -1 !== _.indexOf( plugins.inactive, response.plugin ) ) {
  702. plugins.inactive = _.without( plugins.inactive, response.plugin );
  703. if ( plugins.inactive.length ) {
  704. $views.find( '.inactive .count' ).text( '(' + plugins.inactive.length + ')' );
  705. } else {
  706. $views.find( '.inactive' ).remove();
  707. }
  708. }
  709. if ( -1 !== _.indexOf( plugins.active, response.plugin ) ) {
  710. plugins.active = _.without( plugins.active, response.plugin );
  711. if ( plugins.active.length ) {
  712. $views.find( '.active .count' ).text( '(' + plugins.active.length + ')' );
  713. } else {
  714. $views.find( '.active' ).remove();
  715. }
  716. }
  717. if ( -1 !== _.indexOf( plugins.recently_activated, response.plugin ) ) {
  718. plugins.recently_activated = _.without( plugins.recently_activated, response.plugin );
  719. if ( plugins.recently_activated.length ) {
  720. $views.find( '.recently_activated .count' ).text( '(' + plugins.recently_activated.length + ')' );
  721. } else {
  722. $views.find( '.recently_activated' ).remove();
  723. }
  724. }
  725. plugins.all = _.without( plugins.all, response.plugin );
  726. if ( plugins.all.length ) {
  727. $views.find( '.all .count' ).text( '(' + plugins.all.length + ')' );
  728. } else {
  729. $form.find( '.tablenav' ).css( { visibility: 'hidden' } );
  730. $views.find( '.all' ).remove();
  731. if ( ! $form.find( 'tr.no-items' ).length ) {
  732. $form.find( '#the-list' ).append( '<tr class="no-items"><td class="colspanchange" colspan="' + columnCount + '">' + wp.updates.l10n.noPlugins + '</td></tr>' );
  733. }
  734. }
  735. } );
  736. wp.a11y.speak( wp.updates.l10n.pluginDeleted, 'polite' );
  737. $document.trigger( 'wp-plugin-delete-success', response );
  738. };
  739. /**
  740. * Updates the UI appropriately after a failed plugin deletion.
  741. *
  742. * @since 4.6.0
  743. *
  744. * @typedef {object} deletePluginError
  745. * @param {object} response Response from the server.
  746. * @param {string} response.slug Slug of the plugin to be deleted.
  747. * @param {string} response.plugin Base name of the plugin to be deleted
  748. * @param {string=} response.pluginName Optional. Name of the plugin to be deleted.
  749. * @param {string} response.errorCode Error code for the error that occurred.
  750. * @param {string} response.errorMessage The error that occurred.
  751. */
  752. wp.updates.deletePluginError = function( response ) {
  753. var $plugin, $pluginUpdateRow,
  754. pluginUpdateRow = wp.template( 'item-update-row' ),
  755. noticeContent = wp.updates.adminNotice( {
  756. className: 'update-message notice-error notice-alt',
  757. message: response.errorMessage
  758. } );
  759. if ( response.plugin ) {
  760. $plugin = $( 'tr.inactive[data-plugin="' + response.plugin + '"]' );
  761. $pluginUpdateRow = $plugin.siblings( '[data-plugin="' + response.plugin + '"]' );
  762. } else {
  763. $plugin = $( 'tr.inactive[data-slug="' + response.slug + '"]' );
  764. $pluginUpdateRow = $plugin.siblings( '[data-slug="' + response.slug + '"]' );
  765. }
  766. if ( ! wp.updates.isValidResponse( response, 'delete' ) ) {
  767. return;
  768. }
  769. if ( wp.updates.maybeHandleCredentialError( response, 'delete-plugin' ) ) {
  770. return;
  771. }
  772. // Add a plugin update row if it doesn't exist yet.
  773. if ( ! $pluginUpdateRow.length ) {
  774. $plugin.addClass( 'update' ).after(
  775. pluginUpdateRow( {
  776. slug: response.slug,
  777. plugin: response.plugin || response.slug,
  778. colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length,
  779. content: noticeContent
  780. } )
  781. );
  782. } else {
  783. // Remove previous error messages, if any.
  784. $pluginUpdateRow.find( '.notice-error' ).remove();
  785. $pluginUpdateRow.find( '.plugin-update' ).append( noticeContent );
  786. }
  787. $document.trigger( 'wp-plugin-delete-error', response );
  788. };
  789. /**
  790. * Sends an Ajax request to the server to update a theme.
  791. *
  792. * @since 4.6.0
  793. *
  794. * @param {object} args Arguments.
  795. * @param {string} args.slug Theme stylesheet.
  796. * @param {updateThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.updateThemeSuccess
  797. * @param {updateThemeError=} args.error Optional. Error callback. Default: wp.updates.updateThemeError
  798. * @return {$.promise} A jQuery promise that represents the request,
  799. * decorated with an abort() method.
  800. */
  801. wp.updates.updateTheme = function( args ) {
  802. var $notice;
  803. args = _.extend( {
  804. success: wp.updates.updateThemeSuccess,
  805. error: wp.updates.updateThemeError
  806. }, args );
  807. if ( 'themes-network' === pagenow ) {
  808. $notice = $( '[data-slug="' + args.slug + '"]' ).find( '.update-message' ).removeClass( 'notice-error' ).addClass( 'updating-message notice-warning' ).find( 'p' );
  809. } else if ( 'customize' === pagenow ) {
  810. // Update the theme details UI.
  811. $notice = $( '[data-slug="' + args.slug + '"].notice' ).removeClass( 'notice-large' );
  812. $notice.find( 'h3' ).remove();
  813. // Add the top-level UI, and update both.
  814. $notice = $notice.add( $( '#customize-control-installed_theme_' + args.slug ).find( '.update-message' ) );
  815. $notice = $notice.addClass( 'updating-message' ).find( 'p' );
  816. } else {
  817. $notice = $( '#update-theme' ).closest( '.notice' ).removeClass( 'notice-large' );
  818. $notice.find( 'h3' ).remove();
  819. $notice = $notice.add( $( '[data-slug="' + args.slug + '"]' ).find( '.update-message' ) );
  820. $notice = $notice.addClass( 'updating-message' ).find( 'p' );
  821. }
  822. if ( $notice.html() !== wp.updates.l10n.updating ) {
  823. $notice.data( 'originaltext', $notice.html() );
  824. }
  825. wp.a11y.speak( wp.updates.l10n.updatingMsg, 'polite' );
  826. $notice.text( wp.updates.l10n.updating );
  827. $document.trigger( 'wp-theme-updating', args );
  828. return wp.updates.ajax( 'update-theme', args );
  829. };
  830. /**
  831. * Updates the UI appropriately after a successful theme update.
  832. *
  833. * @since 4.6.0
  834. *
  835. * @typedef {object} updateThemeSuccess
  836. * @param {object} response
  837. * @param {string} response.slug Slug of the theme to be updated.
  838. * @param {object} response.theme Updated theme.
  839. * @param {string} response.oldVersion Old version of the theme.
  840. * @param {string} response.newVersion New version of the theme.
  841. */
  842. wp.updates.updateThemeSuccess = function( response ) {
  843. var isModalOpen = $( 'body.modal-open' ).length,
  844. $theme = $( '[data-slug="' + response.slug + '"]' ),
  845. updatedMessage = {
  846. className: 'updated-message notice-success notice-alt',
  847. message: wp.updates.l10n.themeUpdated
  848. },
  849. $notice, newText;
  850. if ( 'customize' === pagenow ) {
  851. $theme = $( '.updating-message' ).siblings( '.theme-name' );
  852. if ( $theme.length ) {
  853. // Update the version number in the row.
  854. newText = $theme.html().replace( response.oldVersion, response.newVersion );
  855. $theme.html( newText );
  856. }
  857. $notice = $( '.theme-info .notice' ).add( wp.customize.control( 'installed_theme_' + response.slug ).container.find( '.theme' ).find( '.update-message' ) );
  858. } else if ( 'themes-network' === pagenow ) {
  859. $notice = $theme.find( '.update-message' );
  860. // Update the version number in the row.
  861. newText = $theme.find( '.theme-version-author-uri' ).html().replace( response.oldVersion, response.newVersion );
  862. $theme.find( '.theme-version-author-uri' ).html( newText );
  863. } else {
  864. $notice = $( '.theme-info .notice' ).add( $theme.find( '.update-message' ) );
  865. // Focus on Customize button after updating.
  866. if ( isModalOpen ) {
  867. $( '.load-customize:visible' ).focus();
  868. } else {
  869. $theme.find( '.load-customize' ).focus();
  870. }
  871. }
  872. wp.updates.addAdminNotice( _.extend( { selector: $notice }, updatedMessage ) );
  873. wp.a11y.speak( wp.updates.l10n.updatedMsg, 'polite' );
  874. wp.updates.decrementCount( 'theme' );
  875. $document.trigger( 'wp-theme-update-success', response );
  876. // Show updated message after modal re-rendered.
  877. if ( isModalOpen && 'customize' !== pagenow ) {
  878. $( '.theme-info .theme-author' ).after( wp.updates.adminNotice( updatedMessage ) );
  879. }
  880. };
  881. /**
  882. * Updates the UI appropriately after a failed theme update.
  883. *
  884. * @since 4.6.0
  885. *
  886. * @typedef {object} updateThemeError
  887. * @param {object} response Response from the server.
  888. * @param {string} response.slug Slug of the theme to be updated.
  889. * @param {string} response.errorCode Error code for the error that occurred.
  890. * @param {string} response.errorMessage The error that occurred.
  891. */
  892. wp.updates.updateThemeError = function( response ) {
  893. var $theme = $( '[data-slug="' + response.slug + '"]' ),
  894. errorMessage = wp.updates.l10n.updateFailed.replace( '%s', response.errorMessage ),
  895. $notice;
  896. if ( ! wp.updates.isValidResponse( response, 'update' ) ) {
  897. return;
  898. }
  899. if ( wp.updates.maybeHandleCredentialError( response, 'update-theme' ) ) {
  900. return;
  901. }
  902. if ( 'customize' === pagenow ) {
  903. $theme = wp.customize.control( 'installed_theme_' + response.slug ).container.find( '.theme' );
  904. }
  905. if ( 'themes-network' === pagenow ) {
  906. $notice = $theme.find( '.update-message ' );
  907. } else {
  908. $notice = $( '.theme-info .notice' ).add( $theme.find( '.notice' ) );
  909. $( 'body.modal-open' ).length ? $( '.load-customize:visible' ).focus() : $theme.find( '.load-customize' ).focus();
  910. }
  911. wp.updates.addAdminNotice( {
  912. selector: $notice,
  913. className: 'update-message notice-error notice-alt is-dismissible',
  914. message: errorMessage
  915. } );
  916. wp.a11y.speak( errorMessage, 'polite' );
  917. $document.trigger( 'wp-theme-update-error', response );
  918. };
  919. /**
  920. * Sends an Ajax request to the server to install a theme.
  921. *
  922. * @since 4.6.0
  923. *
  924. * @param {object} args
  925. * @param {string} args.slug Theme stylesheet.
  926. * @param {installThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.installThemeSuccess
  927. * @param {installThemeError=} args.error Optional. Error callback. Default: wp.updates.installThemeError
  928. * @return {$.promise} A jQuery promise that represents the request,
  929. * decorated with an abort() method.
  930. */
  931. wp.updates.installTheme = function( args ) {
  932. var $message = $( '.theme-install[data-slug="' + args.slug + '"]' );
  933. args = _.extend( {
  934. success: wp.updates.installThemeSuccess,
  935. error: wp.updates.installThemeError
  936. }, args );
  937. $message.addClass( 'updating-message' );
  938. $message.parents( '.theme' ).addClass( 'focus' );
  939. if ( $message.html() !== wp.updates.l10n.installing ) {
  940. $message.data( 'originaltext', $message.html() );
  941. }
  942. $message
  943. .text( wp.updates.l10n.installing )
  944. .attr( 'aria-label', wp.updates.l10n.themeInstallingLabel.replace( '%s', $message.data( 'name' ) ) );
  945. wp.a11y.speak( wp.updates.l10n.installingMsg, 'polite' );
  946. // Remove previous error messages, if any.
  947. $( '.install-theme-info, [data-slug="' + args.slug + '"]' ).removeClass( 'theme-install-failed' ).find( '.notice.notice-error' ).remove();
  948. $document.trigger( 'wp-theme-installing', args );
  949. return wp.updates.ajax( 'install-theme', args );
  950. };
  951. /**
  952. * Updates the UI appropriately after a successful theme install.
  953. *
  954. * @since 4.6.0
  955. *
  956. * @typedef {object} installThemeSuccess
  957. * @param {object} response Response from the server.
  958. * @param {string} response.slug Slug of the theme to be installed.
  959. * @param {string} response.customizeUrl URL to the Customizer for the just installed theme.
  960. * @param {string} response.activateUrl URL to activate the just installed theme.
  961. */
  962. wp.updates.installThemeSuccess = function( response ) {
  963. var $card = $( '.wp-full-overlay-header, [data-slug=' + response.slug + ']' ),
  964. $message;
  965. $document.trigger( 'wp-theme-install-success', response );
  966. $message = $card.find( '.button-primary' )
  967. .removeClass( 'updating-message' )
  968. .addClass( 'updated-message disabled' )
  969. .attr( 'aria-label', wp.updates.l10n.themeInstalledLabel.replace( '%s', response.themeName ) )
  970. .text( wp.updates.l10n.themeInstalled );
  971. wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' );
  972. setTimeout( function() {
  973. if ( response.activateUrl ) {
  974. // Transform the 'Install' button into an 'Activate' button.
  975. $message
  976. .attr( 'href', response.activateUrl )
  977. .removeClass( 'theme-install updated-message disabled' )
  978. .addClass( 'activate' )
  979. .attr( 'aria-label', wp.updates.l10n.activateThemeLabel.replace( '%s', response.themeName ) )
  980. .text( wp.updates.l10n.activateTheme );
  981. }
  982. if ( response.customizeUrl ) {
  983. // Transform the 'Preview' button into a 'Live Preview' button.
  984. $message.siblings( '.preview' ).replaceWith( function () {
  985. return $( '<a>' )
  986. .attr( 'href', response.customizeUrl )
  987. .addClass( 'button load-customize' )
  988. .text( wp.updates.l10n.livePreview );
  989. } );
  990. }
  991. }, 1000 );
  992. };
  993. /**
  994. * Updates the UI appropriately after a failed theme install.
  995. *
  996. * @since 4.6.0
  997. *
  998. * @typedef {object} installThemeError
  999. * @param {object} response Response from the server.
  1000. * @param {string} response.slug Slug of the theme to be installed.
  1001. * @param {string} response.errorCode Error code for the error that occurred.
  1002. * @param {string} response.errorMessage The error that occurred.
  1003. */
  1004. wp.updates.installThemeError = function( response ) {
  1005. var $card, $button,
  1006. errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage ),
  1007. $message = wp.updates.adminNotice( {
  1008. className: 'update-message notice-error notice-alt',
  1009. message: errorMessage
  1010. } );
  1011. if ( ! wp.updates.isValidResponse( response, 'install' ) ) {
  1012. return;
  1013. }
  1014. if ( wp.updates.maybeHandleCredentialError( response, 'install-theme' ) ) {
  1015. return;
  1016. }
  1017. if ( 'customize' === pagenow ) {
  1018. if ( $document.find( 'body' ).hasClass( 'modal-open' ) ) {
  1019. $button = $( '.theme-install[data-slug="' + response.slug + '"]' );
  1020. $card = $( '.theme-overlay .theme-info' ).prepend( $message );
  1021. } else {
  1022. $button = $( '.theme-install[data-slug="' + response.slug + '"]' );
  1023. $card = $button.closest( '.theme' ).addClass( 'theme-install-failed' ).append( $message );
  1024. }
  1025. wp.customize.notifications.remove( 'theme_installing' );
  1026. } else {
  1027. if ( $document.find( 'body' ).hasClass( 'full-overlay-active' ) ) {
  1028. $button = $( '.theme-install[data-slug="' + response.slug + '"]' );
  1029. $card = $( '.install-theme-info' ).prepend( $message );
  1030. } else {
  1031. $card = $( '[data-slug="' + response.slug + '"]' ).removeClass( 'focus' ).addClass( 'theme-install-failed' ).append( $message );
  1032. $button = $card.find( '.theme-install' );
  1033. }
  1034. }
  1035. $button
  1036. .removeClass( 'updating-message' )
  1037. .attr( 'aria-label', wp.updates.l10n.themeInstallFailedLabel.replace( '%s', $button.data( 'name' ) ) )
  1038. .text( wp.updates.l10n.installFailedShort );
  1039. wp.a11y.speak( errorMessage, 'assertive' );
  1040. $document.trigger( 'wp-theme-install-error', response );
  1041. };
  1042. /**
  1043. * Sends an Ajax request to the server to delete a theme.
  1044. *
  1045. * @since 4.6.0
  1046. *
  1047. * @param {object} args
  1048. * @param {string} args.slug Theme stylesheet.
  1049. * @param {deleteThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.deleteThemeSuccess
  1050. * @param {deleteThemeError=} args.error Optional. Error callback. Default: wp.updates.deleteThemeError
  1051. * @return {$.promise} A jQuery promise that represents the request,
  1052. * decorated with an abort() method.
  1053. */
  1054. wp.updates.deleteTheme = function( args ) {
  1055. var $button;
  1056. if ( 'themes' === pagenow ) {
  1057. $button = $( '.theme-actions .delete-theme' );
  1058. } else if ( 'themes-network' === pagenow ) {
  1059. $button = $( '[data-slug="' + args.slug + '"]' ).find( '.row-actions a.delete' );
  1060. }
  1061. args = _.extend( {
  1062. success: wp.updates.deleteThemeSuccess,
  1063. error: wp.updates.deleteThemeError
  1064. }, args );
  1065. if ( $button && $button.html() !== wp.updates.l10n.deleting ) {
  1066. $button
  1067. .data( 'originaltext', $button.html() )
  1068. .text( wp.updates.l10n.deleting );
  1069. }
  1070. wp.a11y.speak( wp.updates.l10n.deleting, 'polite' );
  1071. // Remove previous error messages, if any.
  1072. $( '.theme-info .update-message' ).remove();
  1073. $document.trigger( 'wp-theme-deleting', args );
  1074. return wp.updates.ajax( 'delete-theme', args );
  1075. };
  1076. /**
  1077. * Updates the UI appropriately after a successful theme deletion.
  1078. *
  1079. * @since 4.6.0
  1080. *
  1081. * @typedef {object} deleteThemeSuccess
  1082. * @param {object} response Response from the server.
  1083. * @param {string} response.slug Slug of the theme that was deleted.
  1084. */
  1085. wp.updates.deleteThemeSuccess = function( response ) {
  1086. var $themeRows = $( '[data-slug="' + response.slug + '"]' );
  1087. if ( 'themes-network' === pagenow ) {
  1088. // Removes the theme and updates rows.
  1089. $themeRows.css( { backgroundColor: '#faafaa' } ).fadeOut( 350, function() {
  1090. var $views = $( '.subsubsub' ),
  1091. $themeRow = $( this ),
  1092. totals = settings.themes,
  1093. deletedRow = wp.template( 'item-deleted-row' );
  1094. if ( ! $themeRow.hasClass( 'plugin-update-tr' ) ) {
  1095. $themeRow.after(
  1096. deletedRow( {
  1097. slug: response.slug,
  1098. colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length,
  1099. name: $themeRow.find( '.theme-title strong' ).text()
  1100. } )
  1101. );
  1102. }
  1103. $themeRow.remove();
  1104. // Remove theme from update count.
  1105. if ( $themeRow.hasClass( 'update' ) ) {
  1106. totals.upgrade--;
  1107. wp.updates.decrementCount( 'theme' );
  1108. }
  1109. // Remove from views.
  1110. if ( $themeRow.hasClass( 'inactive' ) ) {
  1111. totals.disabled--;
  1112. if ( totals.disabled ) {
  1113. $views.find( '.disabled .count' ).text( '(' + totals.disabled + ')' );
  1114. } else {
  1115. $views.find( '.disabled' ).remove();
  1116. }
  1117. }
  1118. // There is always at least one theme available.
  1119. $views.find( '.all .count' ).text( '(' + --totals.all + ')' );
  1120. } );
  1121. }
  1122. wp.a11y.speak( wp.updates.l10n.themeDeleted, 'polite' );
  1123. $document.trigger( 'wp-theme-delete-success', response );
  1124. };
  1125. /**
  1126. * Updates the UI appropriately after a failed theme deletion.
  1127. *
  1128. * @since 4.6.0
  1129. *
  1130. * @typedef {object} deleteThemeError
  1131. * @param {object} response Response from the server.
  1132. * @param {string} response.slug Slug of the theme to be deleted.
  1133. * @param {string} response.errorCode Error code for the error that occurred.
  1134. * @param {string} response.errorMessage The error that occurred.
  1135. */
  1136. wp.updates.deleteThemeError = function( response ) {
  1137. var $themeRow = $( 'tr.inactive[data-slug="' + response.slug + '"]' ),
  1138. $button = $( '.theme-actions .delete-theme' ),
  1139. updateRow = wp.template( 'item-update-row' ),
  1140. $updateRow = $themeRow.siblings( '#' + response.slug + '-update' ),
  1141. errorMessage = wp.updates.l10n.deleteFailed.replace( '%s', response.errorMessage ),
  1142. $message = wp.updates.adminNotice( {
  1143. className: 'update-message notice-error notice-alt',
  1144. message: errorMessage
  1145. } );
  1146. if ( wp.updates.maybeHandleCredentialError( response, 'delete-theme' ) ) {
  1147. return;
  1148. }
  1149. if ( 'themes-network' === pagenow ) {
  1150. if ( ! $updateRow.length ) {
  1151. $themeRow.addClass( 'update' ).after(
  1152. updateRow( {
  1153. slug: response.slug,
  1154. colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length,
  1155. content: $message
  1156. } )
  1157. );
  1158. } else {
  1159. // Remove previous error messages, if any.
  1160. $updateRow.find( '.notice-error' ).remove();
  1161. $updateRow.find( '.plugin-update' ).append( $message );
  1162. }
  1163. } else {
  1164. $( '.theme-info .theme-description' ).before( $message );
  1165. }
  1166. $button.html( $button.data( 'originaltext' ) );
  1167. wp.a11y.speak( errorMessage, 'assertive' );
  1168. $document.trigger( 'wp-theme-delete-error', response );
  1169. };
  1170. /**
  1171. * Adds the appropriate callback based on the type of action and the current page.
  1172. *
  1173. * @since 4.6.0
  1174. * @private
  1175. *
  1176. * @param {object} data AJAX payload.
  1177. * @param {string} action The type of request to perform.
  1178. * @return {object} The AJAX payload with the appropriate callbacks.
  1179. */
  1180. wp.updates._addCallbacks = function( data, action ) {
  1181. if ( 'import' === pagenow && 'install-plugin' === action ) {
  1182. data.success = wp.updates.installImporterSuccess;
  1183. data.error = wp.updates.installImporterError;
  1184. }
  1185. return data;
  1186. };
  1187. /**
  1188. * Pulls available jobs from the queue and runs them.
  1189. *
  1190. * @since 4.2.0
  1191. * @since 4.6.0 Can handle multiple job types.
  1192. */
  1193. wp.updates.queueChecker = function() {
  1194. var job;
  1195. if ( wp.updates.ajaxLocked || ! wp.updates.queue.length ) {
  1196. return;
  1197. }
  1198. job = wp.updates.queue.shift();
  1199. // Handle a queue job.
  1200. switch ( job.action ) {
  1201. case 'install-plugin':
  1202. wp.updates.installPlugin( job.data );
  1203. break;
  1204. case 'update-plugin':
  1205. wp.updates.updatePlugin( job.data );
  1206. break;
  1207. case 'delete-plugin':
  1208. wp.updates.deletePlugin( job.data );
  1209. break;
  1210. case 'install-theme':
  1211. wp.updates.installTheme( job.data );
  1212. break;
  1213. case 'update-theme':
  1214. wp.updates.updateTheme( job.data );
  1215. break;
  1216. case 'delete-theme':
  1217. wp.updates.deleteTheme( job.data );
  1218. break;
  1219. default:
  1220. break;
  1221. }
  1222. };
  1223. /**
  1224. * Requests the users filesystem credentials if they aren't already known.
  1225. *
  1226. * @since 4.2.0
  1227. *
  1228. * @param {Event=} event Optional. Event interface.
  1229. */
  1230. wp.updates.requestFilesystemCredentials = function( event ) {
  1231. if ( false === wp.updates.filesystemCredentials.available ) {
  1232. /*
  1233. * After exiting the credentials request modal,
  1234. * return the focus to the element triggering the request.
  1235. */
  1236. if ( event && ! wp.updates.$elToReturnFocusToFromCredentialsModal ) {
  1237. wp.updates.$elToReturnFocusToFromCredentialsModal = $( event.target );
  1238. }
  1239. wp.updates.ajaxLocked = true;
  1240. wp.updates.requestForCredentialsModalOpen();
  1241. }
  1242. };
  1243. /**
  1244. * Requests the users filesystem credentials if needed and there is no lock.
  1245. *
  1246. * @since 4.6.0
  1247. *
  1248. * @param {Event=} event Optional. Event interface.
  1249. */
  1250. wp.updates.maybeRequestFilesystemCredentials = function( event ) {
  1251. if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
  1252. wp.updates.requestFilesystemCredentials( event );
  1253. }
  1254. };
  1255. /**
  1256. * Keydown handler for the request for credentials modal.
  1257. *
  1258. * Closes the modal when the escape key is pressed and
  1259. * constrains keyboard navigation to inside the modal.
  1260. *
  1261. * @since 4.2.0
  1262. *
  1263. * @param {Event} event Event interface.
  1264. */
  1265. wp.updates.keydown = function( event ) {
  1266. if ( 27 === event.keyCode ) {
  1267. wp.updates.requestForCredentialsModalCancel();
  1268. } else if ( 9 === event.keyCode ) {
  1269. // #upgrade button must always be the last focus-able element in the dialog.
  1270. if ( 'upgrade' === event.target.id && ! event.shiftKey ) {
  1271. $( '#hostname' ).focus();
  1272. event.preventDefault();
  1273. } else if ( 'hostname' === event.target.id && event.shiftKey ) {
  1274. $( '#upgrade' ).focus();
  1275. event.preventDefault();
  1276. }
  1277. }
  1278. };
  1279. /**
  1280. * Opens the request for credentials modal.
  1281. *
  1282. * @since 4.2.0
  1283. */
  1284. wp.updates.requestForCredentialsModalOpen = function() {
  1285. var $modal = $( '#request-filesystem-credentials-dialog' );
  1286. $( 'body' ).addClass( 'modal-open' );
  1287. $modal.show();
  1288. $modal.find( 'input:enabled:first' ).focus();
  1289. $modal.on( 'keydown', wp.updates.keydown );
  1290. };
  1291. /**
  1292. * Closes the request for credentials modal.
  1293. *
  1294. * @since 4.2.0
  1295. */
  1296. wp.updates.requestForCredentialsModalClose = function() {
  1297. $( '#request-filesystem-credentials-dialog' ).hide();
  1298. $( 'body' ).removeClass( 'modal-open' );
  1299. if ( wp.updates.$elToReturnFocusToFromCredentialsModal ) {
  1300. wp.updates.$elToReturnFocusToFromCredentialsModal.focus();
  1301. }
  1302. };
  1303. /**
  1304. * Takes care of the steps that need to happen when the modal is canceled out.
  1305. *
  1306. * @since 4.2.0
  1307. * @since 4.6.0 Triggers an event for callbacks to listen to and add their actions.
  1308. */
  1309. wp.updates.requestForCredentialsModalCancel = function() {
  1310. // Not ajaxLocked and no queue means we already have cleared things up.
  1311. if ( ! wp.updates.ajaxLocked && ! wp.updates.queue.length ) {
  1312. return;
  1313. }
  1314. _.each( wp.updates.queue, function( job ) {
  1315. $document.trigger( 'credential-modal-cancel', job );
  1316. } );
  1317. // Remove the lock, and clear the queue.
  1318. wp.updates.ajaxLocked = false;
  1319. wp.updates.queue = [];
  1320. wp.updates.requestForCredentialsModalClose();
  1321. };
  1322. /**
  1323. * Displays an error message in the request for credentials form.
  1324. *
  1325. * @since 4.2.0
  1326. *
  1327. * @param {string} message Error message.
  1328. */
  1329. wp.updates.showErrorInCredentialsForm = function( message ) {
  1330. var $filesystemForm = $( '#request-filesystem-credentials-form' );
  1331. // Remove any existing error.
  1332. $filesystemForm.find( '.notice' ).remove();
  1333. $filesystemForm.find( '#request-filesystem-credentials-title' ).after( '<div class="notice notice-alt notice-error"><p>' + message + '</p></div>' );
  1334. };
  1335. /**
  1336. * Handles credential errors and runs events that need to happen in that case.
  1337. *
  1338. * @since 4.2.0
  1339. *
  1340. * @param {object} response Ajax response.
  1341. * @param {string} action The type of request to perform.
  1342. */
  1343. wp.updates.credentialError = function( response, action ) {
  1344. // Restore callbacks.
  1345. response = wp.updates._addCallbacks( response, action );
  1346. wp.updates.queue.unshift( {
  1347. action: action,
  1348. /*
  1349. * Not cool that we're depending on response for this data.
  1350. * This would feel more whole in a view all tied together.
  1351. */
  1352. data: response
  1353. } );
  1354. wp.updates.filesystemCredentials.available = false;
  1355. wp.updates.showErrorInCredentialsForm( response.errorMessage );
  1356. wp.updates.requestFilesystemCredentials();
  1357. };
  1358. /**
  1359. * Handles credentials errors if it could not connect to the filesystem.
  1360. *
  1361. * @since 4.6.0
  1362. *
  1363. * @typedef {object} maybeHandleCredentialError
  1364. * @param {object} response Response from the server.
  1365. * @param {string} response.errorCode Error code for the error that occurred.
  1366. * @param {string} response.errorMessage The error that occurred.
  1367. * @param {string} action The type of request to perform.
  1368. * @returns {boolean} Whether there is an error that needs to be handled or not.
  1369. */
  1370. wp.updates.maybeHandleCredentialError = function( response, action ) {
  1371. if ( wp.updates.shouldRequestFilesystemCredentials && response.errorCode && 'unable_to_connect_to_filesystem' === response.errorCode ) {
  1372. wp.updates.credentialError( response, action );
  1373. return true;
  1374. }
  1375. return false;
  1376. };
  1377. /**
  1378. * Validates an AJAX response to ensure it's a proper object.
  1379. *
  1380. * If the response deems to be invalid, an admin notice is being displayed.
  1381. *
  1382. * @param {(object|string)} response Response from the server.
  1383. * @param {function=} response.always Optional. Callback for when the Deferred is resolved or rejected.
  1384. * @param {string=} response.statusText Optional. Status message corresponding to the status code.
  1385. * @param {string=} response.responseText Optional. Request response as text.
  1386. * @param {string} action Type of action the response is referring to. Can be 'delete',
  1387. * 'update' or 'install'.
  1388. */
  1389. wp.updates.isValidResponse = function( response, action ) {
  1390. var error = wp.updates.l10n.unknownError,
  1391. errorMessage;
  1392. // Make sure the response is a valid data object and not a Promise object.
  1393. if ( _.isObject( response ) && ! _.isFunction( response.always ) ) {
  1394. return true;
  1395. }
  1396. if ( _.isString( response ) && '-1' === response ) {
  1397. error = wp.updates.l10n.nonceError;
  1398. } else if ( _.isString( response ) ) {
  1399. error = response;
  1400. } else if ( 'undefined' !== typeof response.readyState && 0 === response.readyState ) {
  1401. error = wp.updates.l10n.connectionError;
  1402. } else if ( _.isString( response.responseText ) && '' !== response.responseText ) {
  1403. error = response.responseText;
  1404. } else if ( _.isString( response.statusText ) ) {
  1405. error = response.statusText;
  1406. }
  1407. switch ( action ) {
  1408. case 'update':
  1409. errorMessage = wp.updates.l10n.updateFailed;
  1410. break;
  1411. case 'install':
  1412. errorMessage = wp.updates.l10n.installFailed;
  1413. break;
  1414. case 'delete':
  1415. errorMessage = wp.updates.l10n.deleteFailed;
  1416. break;
  1417. }
  1418. // Messages are escaped, remove HTML tags to make them more readable.
  1419. error = error.replace( /<[\/a-z][^<>]*>/gi, '' );
  1420. errorMessage = errorMessage.replace( '%s', error );
  1421. // Add admin notice.
  1422. wp.updates.addAdminNotice( {
  1423. id: 'unknown_error',
  1424. className: 'notice-error is-dismissible',
  1425. message: _.escape( errorMessage )
  1426. } );
  1427. // Remove the lock, and clear the queue.
  1428. wp.updates.ajaxLocked = false;
  1429. wp.updates.queue = [];
  1430. // Change buttons of all running updates.
  1431. $( '.button.updating-message' )
  1432. .removeClass( 'updating-message' )
  1433. .removeAttr( 'aria-label' )
  1434. .prop( 'disabled', true )
  1435. .text( wp.updates.l10n.updateFailedShort );
  1436. $( '.updating-message:not(.button):not(.thickbox)' )
  1437. .removeClass( 'updating-message notice-warning' )
  1438. .addClass( 'notice-error' )
  1439. .find( 'p' )
  1440. .removeAttr( 'aria-label' )
  1441. .text( errorMessage );
  1442. wp.a11y.speak( errorMessage, 'assertive' );
  1443. return false;
  1444. };
  1445. /**
  1446. * Potentially adds an AYS to a user attempting to leave the page.
  1447. *
  1448. * If an update is on-going and a user attempts to leave the page,
  1449. * opens an "Are you sure?" alert.
  1450. *
  1451. * @since 4.2.0
  1452. */
  1453. wp.updates.beforeunload = function() {
  1454. if ( wp.updates.ajaxLocked ) {
  1455. return wp.updates.l10n.beforeunload;
  1456. }
  1457. };
  1458. $( function() {
  1459. var $pluginFilter = $( '#plugin-filter' ),
  1460. $bulkActionForm = $( '#bulk-action-form' ),
  1461. $filesystemForm = $( '#request-filesystem-credentials-form' ),
  1462. $filesystemModal = $( '#request-filesystem-credentials-dialog' ),
  1463. $pluginSearch = $( '.plugins-php .wp-filter-search' ),
  1464. $pluginInstallSearch = $( '.plugin-install-php .wp-filter-search' );
  1465. settings = _.extend( settings, window._wpUpdatesItemCounts || {} );
  1466. if ( settings.totals ) {
  1467. wp.updates.refreshCount();
  1468. }
  1469. /*
  1470. * Whether a user needs to submit filesystem credentials.
  1471. *
  1472. * This is based on whether the form was output on the page server-side.
  1473. *
  1474. * @see {wp_print_request_filesystem_credentials_modal() in PHP}
  1475. */
  1476. wp.updates.shouldRequestFilesystemCredentials = $filesystemModal.length > 0;
  1477. /**
  1478. * File system credentials form submit noop-er / handler.
  1479. *
  1480. * @since 4.2.0
  1481. */
  1482. $filesystemModal.on( 'submit', 'form', function( event ) {
  1483. event.preventDefault();
  1484. // Persist the credentials input by the user for the duration of the page load.
  1485. wp.updates.filesystemCredentials.ftp.hostname = $( '#hostname' ).val();
  1486. wp.updates.filesystemCredentials.ftp.username = $( '#username' ).val();
  1487. wp.updates.filesystemCredentials.ftp.password = $( '#password' ).val();
  1488. wp.updates.filesystemCredentials.ftp.connectionType = $( 'input[name="connection_type"]:checked' ).val();
  1489. wp.updates.filesystemCredentials.ssh.publicKey = $( '#public_key' ).val();
  1490. wp.updates.filesystemCredentials.ssh.privateKey = $( '#private_key' ).val();
  1491. wp.updates.filesystemCredentials.fsNonce = $( '#_fs_nonce' ).val();
  1492. wp.updates.filesystemCredentials.available = true;
  1493. // Unlock and invoke the queue.
  1494. wp.updates.ajaxLocked = false;
  1495. wp.updates.queueChecker();
  1496. wp.updates.requestForCredentialsModalClose();
  1497. } );
  1498. /**
  1499. * Closes the request credentials modal when clicking the 'Cancel' button or outside of the modal.
  1500. *
  1501. * @since 4.2.0
  1502. */
  1503. $filesystemModal.on( 'click', '[data-js-action="close"], .notification-dialog-background', wp.updates.requestForCredentialsModalCancel );
  1504. /**
  1505. * Hide SSH fields when not selected.
  1506. *
  1507. * @since 4.2.0
  1508. */
  1509. $filesystemForm.on( 'change', 'input[name="connection_type"]', function() {
  1510. $( '#ssh-keys' ).toggleClass( 'hidden', ( 'ssh' !== $( this ).val() ) );
  1511. } ).change();
  1512. /**
  1513. * Handles events after the credential modal was closed.
  1514. *
  1515. * @since 4.6.0
  1516. *
  1517. * @param {Event} event Event interface.
  1518. * @param {string} job The install/update.delete request.
  1519. */
  1520. $document.on( 'credential-modal-cancel', function( event, job ) {
  1521. var $updatingMessage = $( '.updating-message' ),
  1522. $message, originalText;
  1523. if ( 'import' === pagenow ) {
  1524. $updatingMessage.removeClass( 'updating-message' );
  1525. } else if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
  1526. if ( 'update-plugin' === job.action ) {
  1527. $message = $( 'tr[data-plugin="' + job.data.plugin + '"]' ).find( '.update-message' );
  1528. } else if ( 'delete-plugin' === job.action ) {
  1529. $message = $( '[data-plugin="' + job.data.plugin + '"]' ).find( '.row-actions a.delete' );
  1530. }
  1531. } else if ( 'themes' === pagenow || 'themes-network' === pagenow ) {
  1532. if ( 'update-theme' === job.action ) {
  1533. $message = $( '[data-slug="' + job.data.slug + '"]' ).find( '.update-message' );
  1534. } else if ( 'delete-theme' === job.action && 'themes-network' === pagenow ) {
  1535. $message = $( '[data-slug="' + job.data.slug + '"]' ).find( '.row-actions a.delete' );
  1536. } else if ( 'delete-theme' === job.action && 'themes' === pagenow ) {
  1537. $message = $( '.theme-actions .delete-theme' );
  1538. }
  1539. } else {
  1540. $message = $updatingMessage;
  1541. }
  1542. if ( $message && $message.hasClass( 'updating-message' ) ) {
  1543. originalText = $message.data( 'originaltext' );
  1544. if ( 'undefined' === typeof originalText ) {
  1545. originalText = $( '<p>' ).html( $message.find( 'p' ).data( 'originaltext' ) );
  1546. }
  1547. $message
  1548. .removeClass( 'updating-message' )
  1549. .html( originalText );
  1550. if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) {
  1551. if ( 'update-plugin' === job.action ) {
  1552. $message.attr( 'aria-label', wp.updates.l10n.pluginUpdateNowLabel.replace( '%s', $message.data( 'name' ) ) );
  1553. } else if ( 'install-plugin' === job.action ) {
  1554. $message.attr( 'aria-label', wp.updates.l10n.pluginInstallNowLabel.replace( '%s', $message.data( 'name' ) ) );
  1555. }
  1556. }
  1557. }
  1558. wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' );
  1559. } );
  1560. /**
  1561. * Click handler for plugin updates in List Table view.
  1562. *
  1563. * @since 4.2.0
  1564. *
  1565. * @param {Event} event Event interface.
  1566. */
  1567. $bulkActionForm.on( 'click', '[data-plugin] .update-link', function( event ) {
  1568. var $message = $( event.target ),
  1569. $pluginRow = $message.parents( 'tr' );
  1570. event.preventDefault();
  1571. if ( $message.hasClass( 'updating-message' ) || $message.hasClass( 'button-disabled' ) ) {
  1572. return;
  1573. }
  1574. wp.updates.maybeRequestFilesystemCredentials( event );
  1575. // Return the user to the input box of the plugin's table row after closing the modal.
  1576. wp.updates.$elToReturnFocusToFromCredentialsModal = $pluginRow.find( '.check-column input' );
  1577. wp.updates.updatePlugin( {
  1578. plugin: $pluginRow.data( 'plugin' ),
  1579. slug: $pluginRow.data( 'slug' )
  1580. } );
  1581. } );
  1582. /**
  1583. * Click handler for plugin updates in plugin install view.
  1584. *
  1585. * @since 4.2.0
  1586. *
  1587. * @param {Event} event Event interface.
  1588. */
  1589. $pluginFilter.on( 'click', '.update-now', function( event ) {
  1590. var $button = $( event.target );
  1591. event.preventDefault();
  1592. if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) {
  1593. return;
  1594. }
  1595. wp.updates.maybeRequestFilesystemCredentials( event );
  1596. wp.updates.updatePlugin( {
  1597. plugin: $button.data( 'plugin' ),
  1598. slug: $button.data( 'slug' )
  1599. } );
  1600. } );
  1601. /**
  1602. * Click handler for plugin installs in plugin install view.
  1603. *
  1604. * @since 4.6.0
  1605. *
  1606. * @param {Event} event Event interface.
  1607. */
  1608. $pluginFilter.on( 'click', '.install-now', function( event ) {
  1609. var $button = $( event.target );
  1610. event.preventDefault();
  1611. if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) {
  1612. return;
  1613. }
  1614. if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
  1615. wp.updates.requestFilesystemCredentials( event );
  1616. $document.on( 'credential-modal-cancel', function() {
  1617. var $message = $( '.install-now.updating-message' );
  1618. $message
  1619. .removeClass( 'updating-message' )
  1620. .text( wp.updates.l10n.installNow );
  1621. wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' );
  1622. } );
  1623. }
  1624. wp.updates.installPlugin( {
  1625. slug: $button.data( 'slug' )
  1626. } );
  1627. } );
  1628. /**
  1629. * Click handler for importer plugins installs in the Import screen.
  1630. *
  1631. * @since 4.6.0
  1632. *
  1633. * @param {Event} event Event interface.
  1634. */
  1635. $document.on( 'click', '.importer-item .install-now', function( event ) {
  1636. var $button = $( event.target ),
  1637. pluginName = $( this ).data( 'name' );
  1638. event.preventDefault();
  1639. if ( $button.hasClass( 'updating-message' ) ) {
  1640. return;
  1641. }
  1642. if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
  1643. wp.updates.requestFilesystemCredentials( event );
  1644. $document.on( 'credential-modal-cancel', function() {
  1645. $button
  1646. .removeClass( 'updating-message' )
  1647. .text( wp.updates.l10n.installNow )
  1648. .attr( 'aria-label', wp.updates.l10n.installNowLabel.replace( '%s', pluginName ) );
  1649. wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' );
  1650. } );
  1651. }
  1652. wp.updates.installPlugin( {
  1653. slug: $button.data( 'slug' ),
  1654. pagenow: pagenow,
  1655. success: wp.updates.installImporterSuccess,
  1656. error: wp.updates.installImporterError
  1657. } );
  1658. } );
  1659. /**
  1660. * Click handler for plugin deletions.
  1661. *
  1662. * @since 4.6.0
  1663. *
  1664. * @param {Event} event Event interface.
  1665. */
  1666. $bulkActionForm.on( 'click', '[data-plugin] a.delete', function( event ) {
  1667. var $pluginRow = $( event.target ).parents( 'tr' );
  1668. event.preventDefault();
  1669. if ( ! window.confirm( wp.updates.l10n.aysDeleteUninstall.replace( '%s', $pluginRow.find( '.plugin-title strong' ).text() ) ) ) {
  1670. return;
  1671. }
  1672. wp.updates.maybeRequestFilesystemCredentials( event );
  1673. wp.updates.deletePlugin( {
  1674. plugin: $pluginRow.data( 'plugin' ),
  1675. slug: $pluginRow.data( 'slug' )
  1676. } );
  1677. } );
  1678. /**
  1679. * Click handler for theme updates.
  1680. *
  1681. * @since 4.6.0
  1682. *
  1683. * @param {Event} event Event interface.
  1684. */
  1685. $document.on( 'click', '.themes-php.network-admin .update-link', function( event ) {
  1686. var $message = $( event.target ),
  1687. $themeRow = $message.parents( 'tr' );
  1688. event.preventDefault();
  1689. if ( $message.hasClass( 'updating-message' ) || $message.hasClass( 'button-disabled' ) ) {
  1690. return;
  1691. }
  1692. wp.updates.maybeRequestFilesystemCredentials( event );
  1693. // Return the user to the input box of the theme's table row after closing the modal.
  1694. wp.updates.$elToReturnFocusToFromCredentialsModal = $themeRow.find( '.check-column input' );
  1695. wp.updates.updateTheme( {
  1696. slug: $themeRow.data( 'slug' )
  1697. } );
  1698. } );
  1699. /**
  1700. * Click handler for theme deletions.
  1701. *
  1702. * @since 4.6.0
  1703. *
  1704. * @param {Event} event Event interface.
  1705. */
  1706. $document.on( 'click', '.themes-php.network-admin a.delete', function( event ) {
  1707. var $themeRow = $( event.target ).parents( 'tr' );
  1708. event.preventDefault();
  1709. if ( ! window.confirm( wp.updates.l10n.aysDelete.replace( '%s', $themeRow.find( '.theme-title strong' ).text() ) ) ) {
  1710. return;
  1711. }
  1712. wp.updates.maybeRequestFilesystemCredentials( event );
  1713. wp.updates.deleteTheme( {
  1714. slug: $themeRow.data( 'slug' )
  1715. } );
  1716. } );
  1717. /**
  1718. * Bulk action handler for plugins and themes.
  1719. *
  1720. * Handles both deletions and updates.
  1721. *
  1722. * @since 4.6.0
  1723. *
  1724. * @param {Event} event Event interface.
  1725. */
  1726. $bulkActionForm.on( 'click', '[type="submit"]:not([name="clear-recent-list"])', function( event ) {
  1727. var bulkAction = $( event.target ).siblings( 'select' ).val(),
  1728. itemsSelected = $bulkActionForm.find( 'input[name="checked[]"]:checked' ),
  1729. success = 0,
  1730. error = 0,
  1731. errorMessages = [],
  1732. type, action;
  1733. // Determine which type of item we're dealing with.
  1734. switch ( pagenow ) {
  1735. case 'plugins':
  1736. case 'plugins-network':
  1737. type = 'plugin';
  1738. break;
  1739. case 'themes-network':
  1740. type = 'theme';
  1741. break;
  1742. default:
  1743. return;
  1744. }
  1745. // Bail if there were no items selected.
  1746. if ( ! itemsSelected.length ) {
  1747. event.preventDefault();
  1748. $( 'html, body' ).animate( { scrollTop: 0 } );
  1749. return wp.updates.addAdminNotice( {
  1750. id: 'no-items-selected',
  1751. className: 'notice-error is-dismissible',
  1752. message: wp.updates.l10n.noItemsSelected
  1753. } );
  1754. }
  1755. // Determine the type of request we're dealing with.
  1756. switch ( bulkAction ) {
  1757. case 'update-selected':
  1758. action = bulkAction.replace( 'selected', type );
  1759. break;
  1760. case 'delete-selected':
  1761. if ( ! window.confirm( 'plugin' === type ? wp.updates.l10n.aysBulkDelete : wp.updates.l10n.aysBulkDeleteThemes ) ) {
  1762. event.preventDefault();
  1763. return;
  1764. }
  1765. action = bulkAction.replace( 'selected', type );
  1766. break;
  1767. default:
  1768. return;
  1769. }
  1770. wp.updates.maybeRequestFilesystemCredentials( event );
  1771. event.preventDefault();
  1772. // Un-check the bulk checkboxes.
  1773. $bulkActionForm.find( '.manage-column [type="checkbox"]' ).prop( 'checked', false );
  1774. $document.trigger( 'wp-' + type + '-bulk-' + bulkAction, itemsSelected );
  1775. // Find all the checkboxes which have been checked.
  1776. itemsSelected.each( function( index, element ) {
  1777. var $checkbox = $( element ),
  1778. $itemRow = $checkbox.parents( 'tr' );
  1779. // Only add update-able items to the update queue.
  1780. if ( 'update-selected' === bulkAction && ( ! $itemRow.hasClass( 'update' ) || $itemRow.find( 'notice-error' ).length ) ) {
  1781. // Un-check the box.
  1782. $checkbox.prop( 'checked', false );
  1783. return;
  1784. }
  1785. // Add it to the queue.
  1786. wp.updates.queue.push( {
  1787. action: action,
  1788. data: {
  1789. plugin: $itemRow.data( 'plugin' ),
  1790. slug: $itemRow.data( 'slug' )
  1791. }
  1792. } );
  1793. } );
  1794. // Display bulk notification for updates of any kind.
  1795. $document.on( 'wp-plugin-update-success wp-plugin-update-error wp-theme-update-success wp-theme-update-error', function( event, response ) {
  1796. var $itemRow = $( '[data-slug="' + response.slug + '"]' ),
  1797. $bulkActionNotice, itemName;
  1798. if ( 'wp-' + response.update + '-update-success' === event.type ) {
  1799. success++;
  1800. } else {
  1801. itemName = response.pluginName ? response.pluginName : $itemRow.find( '.column-primary strong' ).text();
  1802. error++;
  1803. errorMessages.push( itemName + ': ' + response.errorMessage );
  1804. }
  1805. $itemRow.find( 'input[name="checked[]"]:checked' ).prop( 'checked', false );
  1806. wp.updates.adminNotice = wp.template( 'wp-bulk-updates-admin-notice' );
  1807. wp.updates.addAdminNotice( {
  1808. id: 'bulk-action-notice',
  1809. className: 'bulk-action-notice',
  1810. successes: success,
  1811. errors: error,
  1812. errorMessages: errorMessages,
  1813. type: response.update
  1814. } );
  1815. $bulkActionNotice = $( '#bulk-action-notice' ).on( 'click', 'button', function() {
  1816. // $( this ) is the clicked button, no need to get it again.
  1817. $( this )
  1818. .toggleClass( 'bulk-action-errors-collapsed' )
  1819. .attr( 'aria-expanded', ! $( this ).hasClass( 'bulk-action-errors-collapsed' ) );
  1820. // Show the errors list.
  1821. $bulkActionNotice.find( '.bulk-action-errors' ).toggleClass( 'hidden' );
  1822. } );
  1823. if ( error > 0 && ! wp.updates.queue.length ) {
  1824. $( 'html, body' ).animate( { scrollTop: 0 } );
  1825. }
  1826. } );
  1827. // Reset admin notice template after #bulk-action-notice was added.
  1828. $document.on( 'wp-updates-notice-added', function() {
  1829. wp.updates.adminNotice = wp.template( 'wp-updates-admin-notice' );
  1830. } );
  1831. // Check the queue, now that the event handlers have been added.
  1832. wp.updates.queueChecker();
  1833. } );
  1834. if ( $pluginInstallSearch.length ) {
  1835. $pluginInstallSearch.attr( 'aria-describedby', 'live-search-desc' );
  1836. }
  1837. /**
  1838. * Handles changes to the plugin search box on the new-plugin page,
  1839. * searching the repository dynamically.
  1840. *
  1841. * @since 4.6.0
  1842. */
  1843. $pluginInstallSearch.on( 'keyup input', _.debounce( function( event, eventtype ) {
  1844. var $searchTab = $( '.plugin-install-search' ), data, searchLocation;
  1845. data = {
  1846. _ajax_nonce: wp.updates.ajaxNonce,
  1847. s: event.target.value,
  1848. tab: 'search',
  1849. type: $( '#typeselector' ).val(),
  1850. pagenow: pagenow
  1851. };
  1852. searchLocation = location.href.split( '?' )[ 0 ] + '?' + $.param( _.omit( data, [ '_ajax_nonce', 'pagenow' ] ) );
  1853. // Clear on escape.
  1854. if ( 'keyup' === event.type && 27 === event.which ) {
  1855. event.target.value = '';
  1856. }
  1857. if ( wp.updates.searchTerm === data.s && 'typechange' !== eventtype ) {
  1858. return;
  1859. } else {
  1860. $pluginFilter.empty();
  1861. wp.updates.searchTerm = data.s;
  1862. }
  1863. if ( window.history && window.history.replaceState ) {
  1864. window.history.replaceState( null, '', searchLocation );
  1865. }
  1866. if ( ! $searchTab.length ) {
  1867. $searchTab = $( '<li class="plugin-install-search" />' )
  1868. .append( $( '<a />', {
  1869. 'class': 'current',
  1870. 'href': searchLocation,
  1871. 'text': wp.updates.l10n.searchResultsLabel
  1872. } ) );
  1873. $( '.wp-filter .filter-links .current' )
  1874. .removeClass( 'current' )
  1875. .parents( '.filter-links' )
  1876. .prepend( $searchTab );
  1877. $pluginFilter.prev( 'p' ).remove();
  1878. $( '.plugins-popular-tags-wrapper' ).remove();
  1879. }
  1880. if ( 'undefined' !== typeof wp.updates.searchRequest ) {
  1881. wp.updates.searchRequest.abort();
  1882. }
  1883. $( 'body' ).addClass( 'loading-content' );
  1884. wp.updates.searchRequest = wp.ajax.post( 'search-install-plugins', data ).done( function( response ) {
  1885. $( 'body' ).removeClass( 'loading-content' );
  1886. $pluginFilter.append( response.items );
  1887. delete wp.updates.searchRequest;
  1888. if ( 0 === response.count ) {
  1889. wp.a11y.speak( wp.updates.l10n.noPluginsFound );
  1890. } else {
  1891. wp.a11y.speak( wp.updates.l10n.pluginsFound.replace( '%d', response.count ) );
  1892. }
  1893. } );
  1894. }, 500 ) );
  1895. if ( $pluginSearch.length ) {
  1896. $pluginSearch.attr( 'aria-describedby', 'live-search-desc' );
  1897. }
  1898. /**
  1899. * Handles changes to the plugin search box on the Installed Plugins screen,
  1900. * searching the plugin list dynamically.
  1901. *
  1902. * @since 4.6.0
  1903. */
  1904. $pluginSearch.on( 'keyup input', _.debounce( function( event ) {
  1905. var data = {
  1906. _ajax_nonce: wp.updates.ajaxNonce,
  1907. s: event.target.value,
  1908. pagenow: pagenow,
  1909. plugin_status: 'all'
  1910. },
  1911. queryArgs;
  1912. // Clear on escape.
  1913. if ( 'keyup' === event.type && 27 === event.which ) {
  1914. event.target.value = '';
  1915. }
  1916. if ( wp.updates.searchTerm === data.s ) {
  1917. return;
  1918. } else {
  1919. wp.updates.searchTerm = data.s;
  1920. }
  1921. queryArgs = _.object( _.compact( _.map( location.search.slice( 1 ).split( '&' ), function( item ) {
  1922. if ( item ) return item.split( '=' );
  1923. } ) ) );
  1924. data.plugin_status = queryArgs.plugin_status || 'all';
  1925. if ( window.history && window.history.replaceState ) {
  1926. window.history.replaceState( null, '', location.href.split( '?' )[ 0 ] + '?s=' + data.s + '&plugin_status=' + data.plugin_status );
  1927. }
  1928. if ( 'undefined' !== typeof wp.updates.searchRequest ) {
  1929. wp.updates.searchRequest.abort();
  1930. }
  1931. $bulkActionForm.empty();
  1932. $( 'body' ).addClass( 'loading-content' );
  1933. $( '.subsubsub .current' ).removeClass( 'current' );
  1934. wp.updates.searchRequest = wp.ajax.post( 'search-plugins', data ).done( function( response ) {
  1935. // Can we just ditch this whole subtitle business?
  1936. var $subTitle = $( '<span />' ).addClass( 'subtitle' ).html( wp.updates.l10n.searchResults.replace( '%s', _.escape( data.s ) ) ),
  1937. $oldSubTitle = $( '.wrap .subtitle' );
  1938. if ( ! data.s.length ) {
  1939. $oldSubTitle.remove();
  1940. $( '.subsubsub .' + data.plugin_status + ' a' ).addClass( 'current' );
  1941. } else if ( $oldSubTitle.length ) {
  1942. $oldSubTitle.replaceWith( $subTitle );
  1943. } else {
  1944. $( '.wp-header-end' ).before( $subTitle );
  1945. }
  1946. $( 'body' ).removeClass( 'loading-content' );
  1947. $bulkActionForm.append( response.items );
  1948. delete wp.updates.searchRequest;
  1949. if ( 0 === response.count ) {
  1950. wp.a11y.speak( wp.updates.l10n.noPluginsFound );
  1951. } else {
  1952. wp.a11y.speak( wp.updates.l10n.pluginsFound.replace( '%d', response.count ) );
  1953. }
  1954. } );
  1955. }, 500 ) );
  1956. /**
  1957. * Trigger a search event when the search form gets submitted.
  1958. *
  1959. * @since 4.6.0
  1960. */
  1961. $document.on( 'submit', '.search-plugins', function( event ) {
  1962. event.preventDefault();
  1963. $( 'input.wp-filter-search' ).trigger( 'input' );
  1964. } );
  1965. /**
  1966. * Trigger a search event when the "Try Again" button is clicked.
  1967. *
  1968. * @since 4.9.0
  1969. */
  1970. $document.on( 'click', '.try-again', function( event ) {
  1971. event.preventDefault();
  1972. $pluginInstallSearch.trigger( 'input' );
  1973. } );
  1974. /**
  1975. * Trigger a search event when the search type gets changed.
  1976. *
  1977. * @since 4.6.0
  1978. */
  1979. $( '#typeselector' ).on( 'change', function() {
  1980. var $search = $( 'input[name="s"]' );
  1981. if ( $search.val().length ) {
  1982. $search.trigger( 'input', 'typechange' );
  1983. }
  1984. } );
  1985. /**
  1986. * Click handler for updating a plugin from the details modal on `plugin-install.php`.
  1987. *
  1988. * @since 4.2.0
  1989. *
  1990. * @param {Event} event Event interface.
  1991. */
  1992. $( '#plugin_update_from_iframe' ).on( 'click', function( event ) {
  1993. var target = window.parent === window ? null : window.parent,
  1994. update;
  1995. $.support.postMessage = !! window.postMessage;
  1996. if ( false === $.support.postMessage || null === target || -1 !== window.parent.location.pathname.indexOf( 'update-core.php' ) ) {
  1997. return;
  1998. }
  1999. event.preventDefault();
  2000. update = {
  2001. action: 'update-plugin',
  2002. data: {
  2003. plugin: $( this ).data( 'plugin' ),
  2004. slug: $( this ).data( 'slug' )
  2005. }
  2006. };
  2007. target.postMessage( JSON.stringify( update ), window.location.origin );
  2008. } );
  2009. /**
  2010. * Click handler for installing a plugin from the details modal on `plugin-install.php`.
  2011. *
  2012. * @since 4.6.0
  2013. *
  2014. * @param {Event} event Event interface.
  2015. */
  2016. $( '#plugin_install_from_iframe' ).on( 'click', function( event ) {
  2017. var target = window.parent === window ? null : window.parent,
  2018. install;
  2019. $.support.postMessage = !! window.postMessage;
  2020. if ( false === $.support.postMessage || null === target || -1 !== window.parent.location.pathname.indexOf( 'index.php' ) ) {
  2021. return;
  2022. }
  2023. event.preventDefault();
  2024. install = {
  2025. action: 'install-plugin',
  2026. data: {
  2027. slug: $( this ).data( 'slug' )
  2028. }
  2029. };
  2030. target.postMessage( JSON.stringify( install ), window.location.origin );
  2031. } );
  2032. /**
  2033. * Handles postMessage events.
  2034. *
  2035. * @since 4.2.0
  2036. * @since 4.6.0 Switched `update-plugin` action to use the queue.
  2037. *
  2038. * @param {Event} event Event interface.
  2039. */
  2040. $( window ).on( 'message', function( event ) {
  2041. var originalEvent = event.originalEvent,
  2042. expectedOrigin = document.location.protocol + '//' + document.location.hostname,
  2043. message;
  2044. if ( originalEvent.origin !== expectedOrigin ) {
  2045. return;
  2046. }
  2047. try {
  2048. message = $.parseJSON( originalEvent.data );
  2049. } catch ( e ) {
  2050. return;
  2051. }
  2052. if ( ! message || 'undefined' === typeof message.action ) {
  2053. return;
  2054. }
  2055. switch ( message.action ) {
  2056. // Called from `wp-admin/includes/class-wp-upgrader-skins.php`.
  2057. case 'decrementUpdateCount':
  2058. /** @property {string} message.upgradeType */
  2059. wp.updates.decrementCount( message.upgradeType );
  2060. break;
  2061. case 'install-plugin':
  2062. case 'update-plugin':
  2063. /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
  2064. window.tb_remove();
  2065. /* jscs:enable */
  2066. message.data = wp.updates._addCallbacks( message.data, message.action );
  2067. wp.updates.queue.push( message );
  2068. wp.updates.queueChecker();
  2069. break;
  2070. }
  2071. } );
  2072. /**
  2073. * Adds a callback to display a warning before leaving the page.
  2074. *
  2075. * @since 4.2.0
  2076. */
  2077. $( window ).on( 'beforeunload', wp.updates.beforeunload );
  2078. } );
  2079. })( jQuery, window.wp, window._wpUpdatesSettings );