diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification.php index 667221acc185b..c0704d6bf6f06 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification.php @@ -10,10 +10,7 @@ abstract class Notification extends \Magento\Backend\App\AbstractAction { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_AdminNotification::show_list'); - } + const ADMIN_RESOURCE = 'Magento_AdminNotification::show_list'; } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php index 7575af3b3bea7..9103aea0fd850 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MarkAsRead.php @@ -8,6 +8,11 @@ class MarkAsRead extends \Magento\AdminNotification\Controller\Adminhtml\Notification { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_AdminNotification::mark_as_read'; + /** * @return void */ @@ -36,12 +41,4 @@ public function execute() } $this->_redirect('adminhtml/*/'); } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_AdminNotification::mark_as_read'); - } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php index 9629ed67a2b9b..8b3a2b24d2422 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassMarkAsRead.php @@ -8,6 +8,11 @@ class MassMarkAsRead extends \Magento\AdminNotification\Controller\Adminhtml\Notification { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_AdminNotification::mark_as_read'; + /** * @return void */ @@ -38,12 +43,4 @@ public function execute() } $this->_redirect('adminhtml/*/'); } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_AdminNotification::mark_as_read'); - } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php index a65fd8f4ac667..071742848fb0f 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php @@ -8,6 +8,11 @@ class MassRemove extends \Magento\AdminNotification\Controller\Adminhtml\Notification { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_AdminNotification::adminnotification_remove'; + /** * @return void */ @@ -33,12 +38,4 @@ public function execute() } $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl($this->getUrl('*'))); } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_AdminNotification::adminnotification_remove'); - } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php index fe06830cf6bb5..db93ff8c3cef9 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/Remove.php @@ -8,6 +8,11 @@ class Remove extends \Magento\AdminNotification\Controller\Adminhtml\Notification { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_AdminNotification::adminnotification_remove'; + /** * @return void */ @@ -35,12 +40,4 @@ public function execute() } $this->_redirect('adminhtml/*/'); } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_AdminNotification::adminnotification_remove'); - } } diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/System/Message/ListAction.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/System/Message/ListAction.php index c9fc32556606f..7040642d33188 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/System/Message/ListAction.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/System/Message/ListAction.php @@ -8,6 +8,13 @@ class ListAction extends \Magento\Backend\App\AbstractAction { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_AdminNotification::show_list'; + /** * @var \Magento\Framework\Json\Helper\Data */ diff --git a/app/code/Magento/AdminNotification/Model/Feed.php b/app/code/Magento/AdminNotification/Model/Feed.php index 4c7e3585c3f36..d48154d30aca0 100644 --- a/app/code/Magento/AdminNotification/Model/Feed.php +++ b/app/code/Magento/AdminNotification/Model/Feed.php @@ -146,9 +146,9 @@ public function checkUpdate() $feedData[] = [ 'severity' => (int)$item->severity, 'date_added' => date('Y-m-d H:i:s', $itemPublicationDate), - 'title' => (string)$item->title, - 'description' => (string)$item->description, - 'url' => (string)$item->link, + 'title' => $this->escapeString($item->title), + 'description' => $this->escapeString($item->description), + 'url' => $this->escapeString($item->link), ]; } } @@ -244,4 +244,15 @@ public function getFeedXml() return $xml; } + + /** + * Converts incoming data to string format and escapes special characters. + * + * @param \SimpleXMLElement $data + * @return string + */ + private function escapeString(\SimpleXMLElement $data) + { + return htmlspecialchars((string)$data); + } } diff --git a/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php b/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php index 890d45026de5e..952e1aea3c342 100644 --- a/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php +++ b/app/code/Magento/AdminNotification/Test/Unit/Model/FeedTest.php @@ -52,13 +52,25 @@ class FeedTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->inboxFactory = $this->getMock('Magento\AdminNotification\Model\InboxFactory', ['create'], [], '', false); - $this->curlFactory = $this->getMock('Magento\Framework\HTTP\Adapter\CurlFactory', ['create'], [], '', false); - $this->curl = $this->getMockBuilder('Magento\Framework\HTTP\Adapter\Curl') + $this->inboxFactory = $this->getMock( + \Magento\AdminNotification\Model\InboxFactory::class, + ['create'], + [], + '', + false + ); + $this->curlFactory = $this->getMock( + \Magento\Framework\HTTP\Adapter\CurlFactory::class, + ['create'], + [], + '', + false + ); + $this->curl = $this->getMockBuilder(\Magento\Framework\HTTP\Adapter\Curl::class) ->disableOriginalConstructor()->getMock(); - $this->appState = $this->getMock('Magento\Framework\App\State', ['getInstallDate'], [], '', false); + $this->appState = $this->getMock(\Magento\Framework\App\State::class, ['getInstallDate'], [], '', false); $this->inboxModel = $this->getMock( - 'Magento\AdminNotification\Model\Inbox', + \Magento\AdminNotification\Model\Inbox::class, [ '__wakeup', 'parse' @@ -68,7 +80,7 @@ protected function setUp() false ); $this->backendConfig = $this->getMock( - 'Magento\Backend\App\ConfigInterface', + \Magento\Backend\App\ConfigInterface::class, [ 'getValue', 'setValue', @@ -76,7 +88,7 @@ protected function setUp() ] ); $this->cacheManager = $this->getMock( - 'Magento\Framework\App\CacheInterface', + \Magento\Framework\App\CacheInterface::class, [ 'load', 'getFrontend', @@ -86,15 +98,15 @@ protected function setUp() ] ); - $this->deploymentConfig = $this->getMockBuilder('Magento\Framework\App\DeploymentConfig') + $this->deploymentConfig = $this->getMockBuilder(\Magento\Framework\App\DeploymentConfig::class) ->disableOriginalConstructor()->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->productMetadata = $this->getMock('Magento\Framework\App\ProductMetadata'); - $this->urlBuilder = $this->getMock('Magento\Framework\UrlInterface'); + $this->productMetadata = $this->getMock(\Magento\Framework\App\ProductMetadata::class); + $this->urlBuilder = $this->getMock(\Magento\Framework\UrlInterface::class); $this->feed = $this->objectManagerHelper->getObject( - 'Magento\AdminNotification\Model\Feed', + \Magento\AdminNotification\Model\Feed::class, [ 'backendConfig' => $this->backendConfig, 'cacheManager' => $this->cacheManager, @@ -145,8 +157,27 @@ public function testCheckUpdate($callInbox, $curlRequest) ->will($this->returnValue('Sat, 6 Sep 2014 16:46:11 UTC')); if ($callInbox) { $this->inboxFactory->expects($this->once())->method('create') - ->will(($this->returnValue($this->inboxModel))); - $this->inboxModel->expects($this->once())->method('parse')->will($this->returnSelf()); + ->will($this->returnValue($this->inboxModel)); + $this->inboxModel->expects($this->once()) + ->method('parse') + ->with( + $this->callback( + function ($data) { + $fieldsToCheck = ['title', 'description', 'url']; + return array_reduce( + $fieldsToCheck, + function ($initialValue, $item) use ($data) { + $haystack = (isset($data[0][$item]) ? $data[0][$item] : false); + return $haystack + ? $initialValue && !strpos($haystack, '<') && !strpos($haystack, '>') + : true; + }, + true + ); + } + ) + ) + ->will($this->returnSelf()); } else { $this->inboxFactory->expects($this->never())->method('create'); $this->inboxModel->expects($this->never())->method('parse'); @@ -196,7 +227,27 @@ public function checkUpdateDataProvider() ' - ] + ], + [ + true, + // @codingStandardsIgnoreStart + 'HEADER + + + + + MagentoCommerce + + <![CDATA[<script>alert("Hello!");</script>Test Title]]> + alert("Hello!");]]> + 4 + alert("Hello!");Description]]> + Tue, 20 Jun 2017 13:14:47 UTC + + + ' + // @codingStandardsIgnoreEnd + ], ]; } } diff --git a/app/code/Magento/AdminNotification/composer.json b/app/code/Magento/AdminNotification/composer.json index 942845e8331a6..a733e815a232f 100644 --- a/app/code/Magento/AdminNotification/composer.json +++ b/app/code/Magento/AdminNotification/composer.json @@ -10,7 +10,7 @@ "lib-libxml": "*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.7", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/AdminNotification/etc/config.xml b/app/code/Magento/AdminNotification/etc/config.xml index c088f7b5e11a7..f23962e0565f0 100644 --- a/app/code/Magento/AdminNotification/etc/config.xml +++ b/app/code/Magento/AdminNotification/etc/config.xml @@ -12,7 +12,7 @@ notifications.magentocommerce.com/magento2/community/notifications.rss widgets.magentocommerce.com/notificationPopup widgets.magentocommerce.com/%s/%s.gif - 0 + 1 1 0 diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php index 609e2f24a198b..e2772a71dadb6 100644 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php +++ b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/BackendResponse.php @@ -6,16 +6,6 @@ */ namespace Magento\Authorizenet\Controller\Directpost\Payment; -class BackendResponse extends \Magento\Authorizenet\Controller\Directpost\Payment +class BackendResponse extends \Magento\Authorizenet\Controller\Directpost\Payment\Response { - /** - * Response action. - * Action for Authorize.net SIM Relay Request. - * - * @return void - */ - public function execute() - { - $this->_responseAction('adminhtml'); - } } diff --git a/app/code/Magento/Authorizenet/Model/Source/Cctype.php b/app/code/Magento/Authorizenet/Model/Source/Cctype.php index 8dba80ddd85b1..38de1f6d0d24f 100644 --- a/app/code/Magento/Authorizenet/Model/Source/Cctype.php +++ b/app/code/Magento/Authorizenet/Model/Source/Cctype.php @@ -17,6 +17,6 @@ class Cctype extends PaymentCctype */ public function getAllowedTypes() { - return ['VI', 'MC', 'AE', 'DI', 'OT']; + return ['VI', 'MC', 'AE', 'DI']; } } diff --git a/app/code/Magento/Authorizenet/composer.json b/app/code/Magento/Authorizenet/composer.json index 002f5e480a752..acbc6608fccff 100644 --- a/app/code/Magento/Authorizenet/composer.json +++ b/app/code/Magento/Authorizenet/composer.json @@ -13,7 +13,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.8", + "version": "100.0.9", "license": [ "proprietary" ], diff --git a/app/code/Magento/Authorizenet/view/frontend/layout/authorizenet_directpost_payment_backendresponse.xml b/app/code/Magento/Authorizenet/view/frontend/layout/authorizenet_directpost_payment_backendresponse.xml index 1eedd5e26a3ed..2cc0558151282 100644 --- a/app/code/Magento/Authorizenet/view/frontend/layout/authorizenet_directpost_payment_backendresponse.xml +++ b/app/code/Magento/Authorizenet/view/frontend/layout/authorizenet_directpost_payment_backendresponse.xml @@ -7,6 +7,6 @@ --> - + diff --git a/app/code/Magento/Backend/App/AbstractAction.php b/app/code/Magento/Backend/App/AbstractAction.php index 0c7a45ef592f3..95045e0946831 100644 --- a/app/code/Magento/Backend/App/AbstractAction.php +++ b/app/code/Magento/Backend/App/AbstractAction.php @@ -102,7 +102,7 @@ public function __construct(Action\Context $context) */ protected function _isAllowed() { - return $this->_authorization->isAllowed(self::ADMIN_RESOURCE); + return $this->_authorization->isAllowed(static::ADMIN_RESOURCE); } /** diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Column.php b/app/code/Magento/Backend/Block/Widget/Grid/Column.php index c7ecd3290e20f..a5bd9184e5f2c 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Column.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Column.php @@ -5,6 +5,7 @@ */ namespace Magento\Backend\Block\Widget\Grid; +use Magento\Backend\Block\Widget; use Magento\Backend\Block\Widget\Grid\Column\Filter\AbstractFilter; /** @@ -12,7 +13,7 @@ * * @author Magento Core Team */ -class Column extends \Magento\Backend\Block\Widget +class Column extends Widget { /** * Parent grid @@ -287,12 +288,29 @@ public function getRowField(\Magento\Framework\DataObject $row) */ $frameCallback = $this->getFrameCallback(); if (is_array($frameCallback)) { + $this->validateFrameCallback($frameCallback); $renderedValue = call_user_func($frameCallback, $renderedValue, $row, $this, false); } return $renderedValue; } + /** + * Validate frame callback. + * + * @param array $callback + * @return void + * @throws \InvalidArgumentException + */ + private function validateFrameCallback(array $callback) + { + if (!is_object($callback[0]) || !$callback[0] instanceof Widget) { + throw new \InvalidArgumentException( + "Frame callback host must be instance of " . Widget::class + ); + } + } + /** * Retrieve row column field value for export * @@ -312,6 +330,7 @@ public function getRowFieldExport(\Magento\Framework\DataObject $row) */ $frameCallback = $this->getFrameCallback(); if (is_array($frameCallback)) { + $this->validateFrameCallback($frameCallback); $renderedValue = call_user_func($frameCallback, $renderedValue, $row, $this, true); } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php b/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php index 9c2301a814899..017cd636eac17 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Ajax/Translate.php @@ -10,6 +10,13 @@ class Translate extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::content_translation'; + /** * @var \Magento\Framework\Translate\Inline\ParserInterface */ diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache.php index 00cbaa614a92b..b48a018a13cd8 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache.php @@ -10,6 +10,11 @@ abstract class Cache extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Backend::cache'; + /** * @var \Magento\Framework\App\Cache\TypeListInterface */ @@ -69,14 +74,4 @@ protected function _validateTypes(array $types) throw new LocalizedException(__('Specified cache type(s) don\'t exist: %1', join(', ', $invalidTypes))); } } - - /** - * Check if cache management is allowed - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::cache'); - } } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard.php b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard.php index 881310acb6338..c8ec971996b60 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Dashboard.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Dashboard.php @@ -14,10 +14,7 @@ abstract class Dashboard extends \Magento\Backend\App\Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::dashboard'); - } + const ADMIN_RESOURCE = 'Magento_Backend::dashboard'; } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/System.php b/app/code/Magento/Backend/Controller/Adminhtml/System.php index 16217761a119a..2dad1b1672ec5 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/System.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/System.php @@ -15,10 +15,7 @@ abstract class System extends AbstractAction { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::system'); - } + const ADMIN_RESOURCE = 'Magento_Backend::system'; } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/System/Account.php b/app/code/Magento/Backend/Controller/Adminhtml/System/Account.php index cc47317380d1b..9b020d9f08e4c 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/System/Account.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/System/Account.php @@ -15,10 +15,7 @@ abstract class Account extends Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::myaccount'); - } + const ADMIN_RESOURCE = 'Magento_Backend::myaccount'; } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/System/Design.php b/app/code/Magento/Backend/Controller/Adminhtml/System/Design.php index 497816a1a753d..07092b8b62b5b 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/System/Design.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/System/Design.php @@ -9,6 +9,11 @@ abstract class Design extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Backend::design'; + /** * Core registry * @@ -59,12 +64,4 @@ public function __construct( $this->resultPageFactory = $resultPageFactory; $this->resultLayoutFactory = $resultLayoutFactory; } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::design'); - } } diff --git a/app/code/Magento/Backend/Controller/Adminhtml/System/Store.php b/app/code/Magento/Backend/Controller/Adminhtml/System/Store.php index e5a95f9d08350..9c4a0f740b88d 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/System/Store.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/System/Store.php @@ -19,6 +19,11 @@ */ abstract class Store extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Backend::store'; + /** * Core registry * @@ -77,14 +82,6 @@ protected function createPage() return $resultPage; } - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backend::store'); - } - /** * Backup database * diff --git a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php index c5af69f5390f8..654ad6c1e66ef 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php @@ -6,11 +6,17 @@ // @codingStandardsIgnoreFile +namespace Magento\Backend\Test\Unit\Model; + +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Url\HostChecker; +use Magento\Framework\Url\ParamEncoder; + /** * Test class for \Magento\Backend\Model\Url + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -namespace Magento\Backend\Test\Unit\Model; - class UrlTest extends \PHPUnit_Framework_TestCase { /** @@ -22,6 +28,7 @@ class UrlTest extends \PHPUnit_Framework_TestCase /** * Mock menu model + * * @var \PHPUnit_Framework_MockObject_MockObject */ protected $_menuMock; @@ -47,7 +54,7 @@ class UrlTest extends \PHPUnit_Framework_TestCase protected $_backendHelperMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $_requestMock; @@ -66,6 +73,21 @@ class UrlTest extends \PHPUnit_Framework_TestCase */ protected $_encryptor; + /** + * @var HostChecker + */ + private $hostChecker; + + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + + /** + * @var ParamEncoder + */ + private $paramEncoder; + /** * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -73,75 +95,55 @@ class UrlTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->_menuMock = $this->getMock( - 'Magento\Backend\Model\Menu', + \Magento\Backend\Model\Menu::class, [], - [$this->getMock('Psr\Log\LoggerInterface')] + [$this->getMock(\Psr\Log\LoggerInterface::class)] ); - $this->_menuConfigMock = $this->getMock('Magento\Backend\Model\Menu\Config', [], [], '', false); + $this->_menuConfigMock = $this->getMock(\Magento\Backend\Model\Menu\Config::class, [], [], '', false); $this->_menuConfigMock->expects($this->any())->method('getMenu')->will($this->returnValue($this->_menuMock)); $this->_formKey = $this->getMock( - 'Magento\Framework\Data\Form\FormKey', + \Magento\Framework\Data\Form\FormKey::class, ['getFormKey'], [], '', false ); $this->_formKey->expects($this->any())->method('getFormKey')->will($this->returnValue('salt')); - $mockItem = $this->getMock('Magento\Backend\Model\Menu\Item', [], [], '', false); + $mockItem = $this->getMock(\Magento\Backend\Model\Menu\Item::class, [], [], '', false); $mockItem->expects($this->any())->method('isDisabled')->will($this->returnValue(false)); $mockItem->expects($this->any())->method('isAllowed')->will($this->returnValue(true)); - $mockItem->expects( - $this->any() - )->method( - 'getId' - )->will( + $mockItem->expects($this->any())->method('getId')->will( $this->returnValue('Magento_Backend::system_acl_roles') ); $mockItem->expects($this->any())->method('getAction')->will($this->returnValue('adminhtml/user_role')); - $this->_menuMock->expects( - $this->any() - )->method( - 'get' - )->with( + $this->_menuMock->expects($this->any())->method('get')->with( $this->equalTo('Magento_Backend::system_acl_roles') - )->will( - $this->returnValue($mockItem) - ); + )->will($this->returnValue($mockItem)); - $helperMock = $this->getMock('Magento\Backend\Helper\Data', [], [], '', false); - $helperMock->expects( - $this->any() - )->method( - 'getAreaFrontName' - )->will( + $helperMock = $this->getMock(\Magento\Backend\Helper\Data::class, [], [], '', false); + $helperMock->expects($this->any())->method('getAreaFrontName')->will( $this->returnValue($this->_areaFrontName) ); - $this->_scopeConfigMock = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface'); - $this->_scopeConfigMock->expects( - $this->any() - )->method( - 'getValue' - )->with( + $this->_scopeConfigMock = $this->getMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $this->_scopeConfigMock->expects($this->any())->method('getValue')->with( \Magento\Backend\Model\Url::XML_PATH_STARTUP_MENU_ITEM - )->will( - $this->returnValue('Magento_Backend::system_acl_roles') - ); + )->will($this->returnValue('Magento_Backend::system_acl_roles')); $this->_authSessionMock = $this->getMock( - 'Magento\Backend\Model\Auth\Session', + \Magento\Backend\Model\Auth\Session::class, [], [], '', false, false ); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_encryptor = $this->getMock('Magento\Framework\Encryption\Encryptor', null, [], '', false); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_encryptor = $this->getMock(\Magento\Framework\Encryption\Encryptor::class, null, [], '', false); $this->_paramsResolverMock = $this->getMock( - 'Magento\Framework\Url\RouteParamsResolverFactory', + \Magento\Framework\Url\RouteParamsResolverFactory::class, [], [], '', @@ -153,53 +155,60 @@ protected function setUp() 'create' )->will( $this->returnValue( - $this->getMock('Magento\Framework\Url\RouteParamsResolver', [], [], '', false) + $this->getMock(\Magento\Framework\Url\RouteParamsResolver::class, [], [], '', false) ) ); - $this->_model = $helper->getObject( - 'Magento\Backend\Model\Url', + + $this->hostChecker = $this->getMockBuilder(HostChecker::class) + ->setMethods(['isOwnOrigin']) + ->disableOriginalConstructor() + ->getMock(); + + $this->paramEncoder = $this->objectManager->getObject(ParamEncoder::class); + + /** @var ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManagerMock */ + $objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->setMethods(['get']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $objectManagerMock->expects(self::at(0))->method('get')->with(HostChecker::class) + ->willReturn($this->hostChecker); + + $objectManagerMock->expects(self::at(1))->method('get')->with(ParamEncoder::class) + ->willReturn($this->paramEncoder); + + \Magento\Framework\App\ObjectManager::setInstance($objectManagerMock); + + $this->_model = $this->objectManager->getObject( + \Magento\Backend\Model\Url::class, [ - 'scopeConfig' => $this->_scopeConfigMock, - 'backendHelper' => $helperMock, - 'formKey' => $this->_formKey, - 'menuConfig' => $this->_menuConfigMock, - 'authSession' => $this->_authSessionMock, - 'encryptor' => $this->_encryptor, - 'routeParamsResolverFactory' => $this->_paramsResolverMock + 'scopeConfig' => $this->_scopeConfigMock, + 'backendHelper' => $helperMock, + 'formKey' => $this->_formKey, + 'menuConfig' => $this->_menuConfigMock, + 'authSession' => $this->_authSessionMock, + 'encryptor' => $this->_encryptor, + 'routeParamsResolverFactory' => $this->_paramsResolverMock, ] ); - $this->_paramsResolverMock->expects( - $this->any() - )->method( - 'create' - )->will( - $this->returnValue( - $this->getMock('Magento\Framework\Url\RouteParamsResolver', [], [], '', false) + $this->_paramsResolverMock->expects($this->any())->method('create') + ->will($this->returnValue( + $this->getMock(\Magento\Framework\Url\RouteParamsResolver::class, [], [], '', false) ) ); - $this->_model = $helper->getObject( - 'Magento\Backend\Model\Url', - [ - 'scopeConfig' => $this->_scopeConfigMock, - 'backendHelper' => $helperMock, - 'formKey' => $this->_formKey, - 'menuConfig' => $this->_menuConfigMock, - 'authSession' => $this->_authSessionMock, - 'encryptor' => $this->_encryptor, - 'routeParamsResolverFactory' => $this->_paramsResolverMock - ] - ); - $this->_requestMock = $this->getMock('Magento\Framework\App\Request\Http', [], [], '', false); + $this->_requestMock = $this->getMock(\Magento\Framework\App\Request\Http::class, [], [], '', false); $this->_model->setRequest($this->_requestMock); } public function testFindFirstAvailableMenuDenied() { - $user = $this->getMock('Magento\User\Model\User', [], [], '', false); + $user = $this->getMock(\Magento\User\Model\User::class, [], [], '', false); $user->expects($this->once())->method('setHasAvailableResources')->with($this->equalTo(false)); + /** @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject $mockSession */ $mockSession = $this->getMock( - 'Magento\Backend\Model\Auth\Session', + \Magento\Backend\Model\Auth\Session::class, ['getUser', 'isAllowed'], [], '', @@ -217,9 +226,10 @@ public function testFindFirstAvailableMenuDenied() public function testFindFirstAvailableMenu() { - $user = $this->getMock('Magento\User\Model\User', [], [], '', false); + $user = $this->getMock(\Magento\User\Model\User::class, [], [], '', false); + /** @var \Magento\Backend\Model\Auth\Session|\PHPUnit_Framework_MockObject_MockObject $mockSession */ $mockSession = $this->getMock( - 'Magento\Backend\Model\Auth\Session', + \Magento\Backend\Model\Auth\Session::class, ['getUser', 'isAllowed'], [], '', @@ -230,7 +240,7 @@ public function testFindFirstAvailableMenu() $this->_model->setSession($mockSession); - $itemMock = $this->getMock('Magento\Backend\Model\Menu\Item', [], [], '', false); + $itemMock = $this->getMock(\Magento\Backend\Model\Menu\Item::class, [], [], '', false); $itemMock->expects($this->once())->method('getAction')->will($this->returnValue('adminhtml/user')); $this->_menuMock->expects($this->any())->method('getFirstAvailable')->will($this->returnValue($itemMock)); @@ -244,21 +254,17 @@ public function testGetStartupPageUrl() public function testGetAreaFrontName() { - $helperMock = $this->getMock('Magento\Backend\Helper\Data', [], [], '', false); - $helperMock->expects( - $this->once() - )->method( - 'getAreaFrontName' - )->will( + $helperMock = $this->getMock(\Magento\Backend\Helper\Data::class, [], [], '', false); + $helperMock->expects($this->once())->method('getAreaFrontName')->will( $this->returnValue($this->_areaFrontName) ); $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $urlModel = $helper->getObject( - 'Magento\Backend\Model\Url', + \Magento\Backend\Model\Url::class, [ - 'backendHelper' => $helperMock, - 'authSession' => $this->_authSessionMock, + 'backendHelper' => $helperMock, + 'authSession' => $this->_authSessionMock, 'routeParamsResolverFactory' => $this->_paramsResolverMock ] ); @@ -310,19 +316,11 @@ public function testGetSecretKeyGenerationWithRouteNameInRequest() $keyFromParams = $this->_model->getSecretKey($routeName, $controllerName, $actionName); - $this->_requestMock->expects( - $this->exactly(3) - )->method( - 'getBeforeForwardInfo' - )->will( + $this->_requestMock->expects($this->exactly(3))->method('getBeforeForwardInfo')->will( $this->returnValue(null) ); $this->_requestMock->expects($this->once())->method('getRouteName')->will($this->returnValue($routeName)); - $this->_requestMock->expects( - $this->once() - )->method( - 'getControllerName' - )->will( + $this->_requestMock->expects($this->once())->method('getControllerName')->will( $this->returnValue($controllerName) ); $this->_requestMock->expects($this->once())->method('getActionName')->will($this->returnValue($actionName)); @@ -343,63 +341,27 @@ public function testGetSecretKeyGenerationWithRouteNameInForwardInfo() $keyFromParams = $this->_model->getSecretKey($routeName, $controllerName, $actionName); - $this->_requestMock->expects( - $this->at(0) - )->method( - 'getBeforeForwardInfo' - )->with( - 'route_name' - )->will( + $this->_requestMock->expects($this->at(0))->method('getBeforeForwardInfo')->with('route_name')->will( $this->returnValue('adminhtml') ); - $this->_requestMock->expects( - $this->at(1) - )->method( - 'getBeforeForwardInfo' - )->with( - 'route_name' - )->will( + $this->_requestMock->expects($this->at(1))->method('getBeforeForwardInfo')->with('route_name')->will( $this->returnValue('adminhtml') ); - $this->_requestMock->expects( - $this->at(2) - )->method( - 'getBeforeForwardInfo' - )->with( - 'controller_name' - )->will( + $this->_requestMock->expects($this->at(2))->method('getBeforeForwardInfo')->with('controller_name')->will( $this->returnValue('catalog') ); - $this->_requestMock->expects( - $this->at(3) - )->method( - 'getBeforeForwardInfo' - )->with( - 'controller_name' - )->will( + $this->_requestMock->expects($this->at(3))->method('getBeforeForwardInfo')->with('controller_name')->will( $this->returnValue('catalog') ); - $this->_requestMock->expects( - $this->at(4) - )->method( - 'getBeforeForwardInfo' - )->with( - 'action_name' - )->will( + $this->_requestMock->expects($this->at(4))->method('getBeforeForwardInfo')->with('action_name')->will( $this->returnValue('index') ); - $this->_requestMock->expects( - $this->at(5) - )->method( - 'getBeforeForwardInfo' - )->with( - 'action_name' - )->will( + $this->_requestMock->expects($this->at(5))->method('getBeforeForwardInfo')->with('action_name')->will( $this->returnValue('index') ); @@ -413,4 +375,16 @@ public function testGetUrlWithUrlInRoutePath() $routePath = 'https://localhost/index.php/catalog/product/view/id/100/?foo=bar#anchor'; static::assertEquals($routePath, $this->_model->getUrl($routePath)); } + + /** + * @inheritdoc + */ + protected function tearDown() + { + // reset ObjectManager instance. + $reflection = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); + $reflectionProperty = $reflection->getProperty('_instance'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue(null, null); + } } diff --git a/app/code/Magento/Backend/composer.json b/app/code/Magento/Backend/composer.json index 489a6fe765a1d..34183c95041ee 100644 --- a/app/code/Magento/Backend/composer.json +++ b/app/code/Magento/Backend/composer.json @@ -21,7 +21,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.10", + "version": "100.0.11", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Backend/etc/acl.xml b/app/code/Magento/Backend/etc/acl.xml index 6e92db98dcd11..07228de92d84d 100644 --- a/app/code/Magento/Backend/etc/acl.xml +++ b/app/code/Magento/Backend/etc/acl.xml @@ -22,6 +22,7 @@ + diff --git a/app/code/Magento/Backup/Controller/Adminhtml/Index.php b/app/code/Magento/Backup/Controller/Adminhtml/Index.php index 4919b3b726af1..dfe5e90c66e91 100644 --- a/app/code/Magento/Backup/Controller/Adminhtml/Index.php +++ b/app/code/Magento/Backup/Controller/Adminhtml/Index.php @@ -12,6 +12,11 @@ */ abstract class Index extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Backup::backup'; + /** * Core registry * @@ -62,14 +67,4 @@ public function __construct( $this->maintenanceMode = $maintenanceMode; parent::__construct($context); } - - /** - * Check Permissions for all actions - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Backup::backup'); - } } diff --git a/app/code/Magento/Backup/composer.json b/app/code/Magento/Backup/composer.json index fbe5772ca069c..d52f23f25ce11 100644 --- a/app/code/Magento/Backup/composer.json +++ b/app/code/Magento/Backup/composer.json @@ -9,7 +9,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.7", + "version": "100.0.8", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Grid.php b/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Grid.php index 66505f69f7517..917010ae930d8 100644 --- a/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Grid.php +++ b/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Grid.php @@ -6,7 +6,9 @@ */ namespace Magento\Bundle\Controller\Adminhtml\Bundle\Selection; -class Grid extends \Magento\Backend\App\Action +use Magento\Catalog\Controller\Adminhtml\Product; + +class Grid extends Product { /** * @return mixed @@ -20,7 +22,7 @@ public function execute() return $this->getResponse()->setBody( $this->_view->getLayout()->createBlock( - 'Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search\Grid', + \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search\Grid::class, 'adminhtml.catalog.product.edit.tab.bundle.option.search.grid' )->setIndex($index)->toHtml() ); diff --git a/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Search.php b/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Search.php index deb4358106134..a806a109eb943 100644 --- a/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Search.php +++ b/app/code/Magento/Bundle/Controller/Adminhtml/Bundle/Selection/Search.php @@ -6,7 +6,9 @@ */ namespace Magento\Bundle\Controller\Adminhtml\Bundle\Selection; -class Search extends \Magento\Backend\App\Action +use Magento\Catalog\Controller\Adminhtml\Product; + +class Search extends Product { /** * @return mixed @@ -15,7 +17,7 @@ public function execute() { return $this->getResponse()->setBody( $this->_view->getLayout()->createBlock( - 'Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search' + \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Bundle\Option\Search::class )->setIndex( $this->getRequest()->getParam('index') )->setFirstShow( diff --git a/app/code/Magento/Bundle/composer.json b/app/code/Magento/Bundle/composer.json index 17a889fa06840..d635b2c8b1b58 100644 --- a/app/code/Magento/Bundle/composer.json +++ b/app/code/Magento/Bundle/composer.json @@ -24,7 +24,7 @@ "magento/module-bundle-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.7", + "version": "100.0.8", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Bundle/view/frontend/templates/catalog/product/view/type/bundle/option/checkbox.phtml b/app/code/Magento/Bundle/view/frontend/templates/catalog/product/view/type/bundle/option/checkbox.phtml index 75641adf03a4c..f071f9f97bff7 100644 --- a/app/code/Magento/Bundle/view/frontend/templates/catalog/product/view/type/bundle/option/checkbox.phtml +++ b/app/code/Magento/Bundle/view/frontend/templates/catalog/product/view/type/bundle/option/checkbox.phtml @@ -8,7 +8,7 @@ ?> - + getOption() ?> getSelections() ?>
@@ -29,7 +29,7 @@ getRequired()) echo 'data-validate="{\'validate-one-required-by-name\':\'input[name^="bundle_option[' . $_option->getId() . ']"]:checked\'}"'?> + getRequired()) /* @escapeNotVerified */ echo 'data-validate="{\'validate-one-required-by-name\':\'input[name^="bundle_option[' . $_option->getId() . ']"]:checked\'}"'?> name="bundle_option[getId() ?>][getId() ?>]" isSelected($_selection)) echo ' checked="checked"' ?> isSaleable()) echo ' disabled="disabled"' ?> diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Category.php b/app/code/Magento/Catalog/Controller/Adminhtml/Category.php index 044459eb70131..f3038f61ac281 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Category.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Category.php @@ -10,6 +10,11 @@ */ abstract class Category extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::categories'; + /** * Initialize requested category and put it into registry. * Root category can be returned, if inappropriate store/category is specified @@ -53,14 +58,4 @@ protected function _initCategory($getRootInstead = false) ->setStoreId($this->getRequest()->getParam('store')); return $category; } - - /** - * Check if admin has permissions to visit related pages - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::categories'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Category/Widget.php b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Widget.php index add59c6b2a426..6e643dff1107e 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Category/Widget.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Widget.php @@ -14,6 +14,13 @@ */ abstract class Widget extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Catalog::categories'; + /** * @var \Magento\Framework\View\LayoutFactory */ @@ -37,7 +44,7 @@ public function __construct( protected function _getCategoryTreeBlock() { return $this->layoutFactory->create()->createBlock( - 'Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser', + \Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser::class, '', [ 'data' => [ diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Category/Wysiwyg.php b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Wysiwyg.php index 03958aa954931..834376095a570 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Category/Wysiwyg.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Category/Wysiwyg.php @@ -9,12 +9,7 @@ class Wysiwyg extends \Magento\Catalog\Controller\Adminhtml\Product\Wysiwyg { /** - * Check if admin has permissions to visit related pages - * - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::categories'); - } + const ADMIN_RESOURCE = 'Magento_Catalog::categories'; } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product.php index a3ca2c09d88f3..fb1750594ffef 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product.php @@ -13,6 +13,13 @@ */ abstract class Product extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var Product\Builder */ @@ -29,14 +36,4 @@ public function __construct( $this->productBuilder = $productBuilder; parent::__construct($context); } - - /** - * Check for is allowed - * - * @return boolean - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::products'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute.php index 27e360ec30c67..c2d6f9a51cb9b 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Action/Attribute.php @@ -15,6 +15,11 @@ */ abstract class Attribute extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::update_attributes'; + /** * @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute */ @@ -53,12 +58,4 @@ protected function _validateProducts() return !$error; } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::update_attributes'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute.php index 38d77553b0f4d..6538b7a0d8ab4 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute.php @@ -14,6 +14,11 @@ abstract class Attribute extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::attributes_attributes'; + /** * @var \Magento\Framework\Cache\FrontendInterface */ @@ -123,14 +128,4 @@ protected function generateCode($label) } return $code; } - - /** - * ACL check - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::attributes_attributes'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Datafeeds/Index.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Datafeeds/Index.php index 98c3b36effb3e..f6e843df30e03 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Datafeeds/Index.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Datafeeds/Index.php @@ -8,6 +8,13 @@ class Index extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @return void */ diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php index 0ee20abc5d389..fa91f5a9f5884 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php @@ -10,6 +10,11 @@ class Upload extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var \Magento\Framework\Controller\Result\RawFactory */ @@ -27,14 +32,6 @@ public function __construct( $this->resultRawFactory = $resultRawFactory; } - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::products'); - } - /** * @return \Magento\Framework\Controller\Result\Raw */ diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Group/Save.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Group/Save.php index 519c5231a5e74..b8c784f5468d4 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Group/Save.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Group/Save.php @@ -9,19 +9,16 @@ class Save extends \Magento\Backend\App\Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::products'); - } + const ADMIN_RESOURCE = 'Magento_Catalog::products'; /** * @return void */ public function execute() { - $model = $this->_objectManager->create('Magento\Eav\Model\Entity\Attribute\Group'); + $model = $this->_objectManager->create(\Magento\Eav\Model\Entity\Attribute\Group::class); $model->setAttributeGroupName( $this->getRequest()->getParam('attribute_group_name') diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php index 2301c88d717bb..4751f1d12d9a7 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Initialization/Helper.php @@ -151,7 +151,7 @@ public function initialize(\Magento\Catalog\Model\Product $product) foreach ($options as &$customOptionData) { if (isset($customOptionData['values'])) { $customOptionData['values'] = array_filter($customOptionData['values'], function ($valueData) { - return !($valueData['option_type_id'] == '-1' && !empty($valueData['is_delete'])); + return !((!isset($valueData['option_type_id']) || $valueData['option_type_id'] == '-1') && !empty($valueData['is_delete'])); }); } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Set.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Set.php index 1ad8a40ed5b94..147ccdae03049 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Set.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Set.php @@ -12,6 +12,11 @@ */ abstract class Set extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::sets'; + /** * Core registry * @@ -41,12 +46,4 @@ protected function _setTypeId() $this->_objectManager->create('Magento\Catalog\Model\Product')->getResource()->getTypeId() ); } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::sets'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributeSets.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributeSets.php index ea7b3f21e3c21..82600d4041875 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributeSets.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributeSets.php @@ -8,6 +8,11 @@ class SuggestAttributeSets extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var \Magento\Framework\Controller\Result\JsonFactory */ @@ -46,12 +51,4 @@ public function execute() ); return $resultJson; } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::products'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributes.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributes.php index 813c452c63881..0d1fff64355e2 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributes.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/SuggestAttributes.php @@ -8,6 +8,11 @@ class SuggestAttributes extends \Magento\Catalog\Controller\Adminhtml\Product { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var \Magento\Framework\Controller\Result\JsonFactory */ @@ -50,12 +55,4 @@ public function execute() ); return $resultJson; } - - /** - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::products'); - } } diff --git a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Widget/Chooser.php b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Widget/Chooser.php index 12a91e22035ff..15755761f6007 100644 --- a/app/code/Magento/Catalog/Controller/Adminhtml/Product/Widget/Chooser.php +++ b/app/code/Magento/Catalog/Controller/Adminhtml/Product/Widget/Chooser.php @@ -8,6 +8,13 @@ class Chooser extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Widget::widget_instance'; + /** * @var \Magento\Framework\Controller\Result\RawFactory */ @@ -46,7 +53,7 @@ public function execute() $layout = $this->layoutFactory->create(); $productsGrid = $layout->createBlock( - 'Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser', + \Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser::class, '', [ 'data' => [ @@ -62,7 +69,7 @@ public function execute() if (!$this->getRequest()->getParam('products_grid')) { $categoriesTree = $layout->createBlock( - 'Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser', + \Magento\Catalog\Block\Adminhtml\Category\Widget\Chooser::class, '', [ 'data' => [ @@ -73,7 +80,7 @@ public function execute() ] ); - $html = $layout->createBlock('Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser\Container') + $html = $layout->createBlock(\Magento\Catalog\Block\Adminhtml\Product\Widget\Chooser\Container::class) ->setTreeHtml($categoriesTree->toHtml()) ->setGridHtml($html) ->toHtml(); @@ -81,6 +88,7 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); + return $resultRaw->setContents($html); } } diff --git a/app/code/Magento/Catalog/Model/Product/Attribute/Backend/Media.php b/app/code/Magento/Catalog/Model/Product/Attribute/Backend/Media.php index c3ff863bf57ae..e3c3fde253a43 100644 --- a/app/code/Magento/Catalog/Model/Product/Attribute/Backend/Media.php +++ b/app/code/Magento/Catalog/Model/Product/Attribute/Backend/Media.php @@ -280,7 +280,7 @@ protected function removeDeletedImages(array $files) */ protected function moveImageFromTmp($file) { - $file = $this->getFilenameFromTmp($file); + $file = $this->getFilenameFromTmp($this->getSafeFilename($file)); $destinationFile = $this->getUniqueFileName($file); if ($this->fileStorageDb->checkDbUsage()) { @@ -326,6 +326,21 @@ protected function getUniqueFileName($file, $forTmp = false) } + /** + * Returns safe filename for posted image. + * + * @param string $file + * @return string + */ + private function getSafeFilename($file) + { + if (strpos($file, '..') === 0) { + $file = DIRECTORY_SEPARATOR . $file; + } + + return $this->mediaDirectory->getDriver()->getRealPathSafety($file); + } + /** * @param string $file * @return string diff --git a/app/code/Magento/Catalog/Model/Product/Pricing/Renderer/SalableResolver.php b/app/code/Magento/Catalog/Model/Product/Pricing/Renderer/SalableResolver.php index d0656990ded10..695f70e069128 100644 --- a/app/code/Magento/Catalog/Model/Product/Pricing/Renderer/SalableResolver.php +++ b/app/code/Magento/Catalog/Model/Product/Pricing/Renderer/SalableResolver.php @@ -19,6 +19,6 @@ class SalableResolver implements SalableResolverInterface */ public function isSalable(\Magento\Framework\Pricing\SaleableInterface $salableItem) { - return $salableItem->getCanShowPrice() !== false && $salableItem->isSalable(); + return $salableItem->getCanShowPrice() !== false; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php index c658258d5886a..99f824c3cc7da 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Pricing/Renderer/SalableResolverTest.php @@ -22,7 +22,7 @@ protected function setUp() { $this->product = $this->getMock( 'Magento\Catalog\Model\Product', - ['__wakeup', 'getCanShowPrice', 'isSalable'], + ['__wakeup', 'getCanShowPrice'], [], '', false @@ -40,8 +40,6 @@ public function testSalableItem() ->method('getCanShowPrice') ->willReturn(true); - $this->product->expects($this->any())->method('isSalable')->willReturn(true); - $result = $this->object->isSalable($this->product); $this->assertTrue($result); } @@ -50,9 +48,7 @@ public function testNotSalableItem() { $this->product->expects($this->any()) ->method('getCanShowPrice') - ->willReturn(true); - - $this->product->expects($this->any())->method('isSalable')->willReturn(false); + ->willReturn(false); $result = $this->object->isSalable($this->product); $this->assertFalse($result); diff --git a/app/code/Magento/Catalog/composer.json b/app/code/Magento/Catalog/composer.json index 47027a3ddcc76..ff16a24f92820 100644 --- a/app/code/Magento/Catalog/composer.json +++ b/app/code/Magento/Catalog/composer.json @@ -34,7 +34,7 @@ "magento/module-catalog-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.13", + "version": "100.0.15", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/set/main.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/set/main.phtml index c15257e8af70c..67863ae1928fe 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/set/main.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/set/main.phtml @@ -259,7 +259,7 @@ } var newNode = new Ext.tree.TreeNode({ - text : group_name.escapeHTML(), + text : group_name, cls : 'folder', allowDrop : true, allowDrag : true @@ -287,16 +287,21 @@ }, validateGroupName : function(name, exceptNodeId) { + var textNode, + result = true; + name = name.strip(); - var result = true; if (name === '') { result = false; } for (var i=0; i < TreePanels.root.childNodes.length; i++) { if (TreePanels.root.childNodes[i].text.toLowerCase() == name.toLowerCase() && TreePanels.root.childNodes[i].id != exceptNodeId) { errorText = ''; + errorText = errorText.replace("/name/", name); + textNode = jQuery('')[0]; + textNode.textContent = errorText; alert({ - content: errorText.replace("/name/",name) + content: textNode }); result = false; } diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/options/type/file.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/options/type/file.phtml index e3709958b67e0..95bbcaa12dc89 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/options/type/file.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/options/type/file.phtml @@ -40,7 +40,7 @@ - + x %2 px.', '', diff --git a/app/code/Magento/Catalog/view/adminhtml/ui_component/product_listing.xml b/app/code/Magento/Catalog/view/adminhtml/ui_component/product_listing.xml index fc90196002f72..6dfd418476cac 100644 --- a/app/code/Magento/Catalog/view/adminhtml/ui_component/product_listing.xml +++ b/app/code/Magento/Catalog/view/adminhtml/ui_component/product_listing.xml @@ -12,6 +12,7 @@ product_listing.product_listing_data_source product_columns + Magento_Catalog::products diff --git a/app/code/Magento/Catalog/view/adminhtml/web/catalog/apply-to-type-switcher.js b/app/code/Magento/Catalog/view/adminhtml/web/catalog/apply-to-type-switcher.js index 239d399ed45e0..be1699614c1f5 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/catalog/apply-to-type-switcher.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/catalog/apply-to-type-switcher.js @@ -4,13 +4,22 @@ */ define([ 'jquery', + 'uiRegistry', 'Magento_Catalog/js/product/weight-handler', 'Magento_Catalog/catalog/type-events' -], function ($, weight, productType) { +], function ($, registry, weight, productType) { 'use strict'; return { + /** + * Init + */ + init: function () { + this.bindAll(); + this._switchToTypeByApplyAttr(); + }, + /** * Bind event */ @@ -32,8 +41,7 @@ define([ * Constructor component */ 'Magento_Catalog/catalog/apply-to-type-switcher': function () { - this.bindAll(); - this._switchToTypeByApplyAttr(); + registry.get('typeSwitcher', this.init.bind(this)); }, /** diff --git a/app/code/Magento/Catalog/view/adminhtml/web/catalog/type-events.js b/app/code/Magento/Catalog/view/adminhtml/web/catalog/type-events.js index f541255ab045e..e98785aa5f561 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/catalog/type-events.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/catalog/type-events.js @@ -4,8 +4,9 @@ */ define([ 'jquery', + 'uiRegistry', 'Magento_Catalog/js/product/weight-handler' -], function ($, weight) { +], function ($, registry, weight) { 'use strict'; return { @@ -30,6 +31,7 @@ define([ this.type.current = this.$type.val(); this.bindAll(); + registry.set('typeSwitcher', this); }, /** diff --git a/app/code/Magento/Catalog/view/adminhtml/web/js/custom-options.js b/app/code/Magento/Catalog/view/adminhtml/web/js/custom-options.js index 3e610b6eedef7..648bbff8e89c6 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/js/custom-options.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/js/custom-options.js @@ -308,7 +308,7 @@ define([ */ _bindReadOnlyMode: function () { if (this.options.isReadonly) { - $('div.product-custom-options').find('button,input,select,textarea,').each(function () { + $('div.product-custom-options').find('button,input,select,textarea').each(function () { $(this).prop('disabled', true); if ($(this).is('button')) { @@ -339,7 +339,7 @@ define([ checkbox: 'input[id$=_price_use_default]', label: 'span' }); - //@TODO not work set default value for second field + // not work set default value for second field priceType.useDefault({ field: '.field', useDefault: 'label[for$=_price]', diff --git a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Catalog.php b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Catalog.php index a962dc539eb93..bc5c44d87ed52 100644 --- a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Catalog.php +++ b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Catalog.php @@ -18,6 +18,11 @@ abstract class Catalog extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_CatalogRule::promo_catalog'; + /** * Dirty rules notice message * @@ -71,16 +76,6 @@ protected function _initAction() return $this; } - /** - * Is access to section allowed - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CatalogRule::promo_catalog'); - } - /** * Set dirty rules notice message * diff --git a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Index.php b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Index.php index 8512243a894d5..e245cf2a413b3 100644 --- a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Index.php +++ b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Index.php @@ -9,12 +9,9 @@ class Index extends \Magento\Backend\App\Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CatalogRule::promo'); - } + const ADMIN_RESOURCE = 'Magento_CatalogRule::promo'; /** * @return void diff --git a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Widget.php b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Widget.php index a763110076404..60686ea642b48 100644 --- a/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Widget.php +++ b/app/code/Magento/CatalogRule/Controller/Adminhtml/Promo/Widget.php @@ -10,10 +10,7 @@ abstract class Widget extends Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CatalogRule::promo_catalog'); - } + const ADMIN_RESOURCE = 'Magento_CatalogRule::promo_catalog'; } diff --git a/app/code/Magento/CatalogRule/composer.json b/app/code/Magento/CatalogRule/composer.json index 9aabf7afebef4..4c0930e331ecf 100644 --- a/app/code/Magento/CatalogRule/composer.json +++ b/app/code/Magento/CatalogRule/composer.json @@ -16,7 +16,7 @@ "magento/module-catalog-rule-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.8", + "version": "100.0.9", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/CatalogSearch/composer.json b/app/code/Magento/CatalogSearch/composer.json index 737912d31de77..1775e5372a23a 100644 --- a/app/code/Magento/CatalogSearch/composer.json +++ b/app/code/Magento/CatalogSearch/composer.json @@ -14,7 +14,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.7", + "version": "100.0.8", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/CatalogSearch/etc/acl.xml b/app/code/Magento/CatalogSearch/etc/acl.xml new file mode 100644 index 0000000000000..09a4c51bc2f3d --- /dev/null +++ b/app/code/Magento/CatalogSearch/etc/acl.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/code/Magento/CatalogWidget/Controller/Adminhtml/Product/Widget.php b/app/code/Magento/CatalogWidget/Controller/Adminhtml/Product/Widget.php index 57e4da3de6685..e92382f76c14a 100644 --- a/app/code/Magento/CatalogWidget/Controller/Adminhtml/Product/Widget.php +++ b/app/code/Magento/CatalogWidget/Controller/Adminhtml/Product/Widget.php @@ -13,10 +13,7 @@ abstract class Widget extends Action { /** - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Widget::widget_instance'); - } + const ADMIN_RESOURCE = 'Magento_Widget::widget_instance'; } diff --git a/app/code/Magento/CatalogWidget/composer.json b/app/code/Magento/CatalogWidget/composer.json index 716b622a7fe54..91a5b1707a199 100644 --- a/app/code/Magento/CatalogWidget/composer.json +++ b/app/code/Magento/CatalogWidget/composer.json @@ -14,7 +14,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.7", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Checkout/Controller/Cart/Addgroup.php b/app/code/Magento/Checkout/Controller/Cart/Addgroup.php index 742df2e602472..6179a78054936 100644 --- a/app/code/Magento/Checkout/Controller/Cart/Addgroup.php +++ b/app/code/Magento/Checkout/Controller/Cart/Addgroup.php @@ -6,6 +6,11 @@ */ namespace Magento\Checkout\Controller\Cart; +use Magento\Sales\Model\Order\Item; + +/** + * Add "Recently Ordered" customer items to cart. + */ class Addgroup extends \Magento\Checkout\Controller\Cart { /** @@ -13,16 +18,16 @@ class Addgroup extends \Magento\Checkout\Controller\Cart */ public function execute() { - $orderItemIds = $this->getRequest()->getParam('order_items', []); + $orderItemIds = $this->getRequest()->getPost('order_items'); if (is_array($orderItemIds)) { - $itemsCollection = $this->_objectManager->create('Magento\Sales\Model\Order\Item') + $itemsCollection = $this->_objectManager->create(\Magento\Sales\Model\Order\Item::class) ->getCollection() ->addIdFilter($orderItemIds) ->load(); /* @var $itemsCollection \Magento\Sales\Model\ResourceModel\Order\Item\Collection */ foreach ($itemsCollection as $item) { try { - $this->cart->addOrderItem($item, 1); + $this->addOrderItem($item); } catch (\Magento\Framework\Exception\LocalizedException $e) { if ($this->_checkoutSession->getUseNotice(true)) { $this->messageManager->addNotice($e->getMessage()); @@ -34,12 +39,35 @@ public function execute() $e, __('We can\'t add this item to your shopping cart right now.') ); - $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e); + $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); + return $this->_goBack(); } } $this->cart->save(); } + return $this->_goBack(); } + + /** + * Add item to cart. + * + * Add item to cart only if it's belongs to customer. + * + * @param Item $item + * @return void + */ + private function addOrderItem(Item $item) + { + /** @var \Magento\Customer\Model\Session $session */ + $session = $this->cart->getCustomerSession(); + if ($session->isLoggedIn()) { + $orderCustomerId = $item->getOrder()->getCustomerId(); + $currentCustomerId = $session->getCustomer()->getId(); + if ($orderCustomerId == $currentCustomerId) { + $this->cart->addOrderItem($item, 1); + } + } + } } diff --git a/app/code/Magento/Checkout/composer.json b/app/code/Magento/Checkout/composer.json index 8e623d77bce19..6c9ecbf63016c 100644 --- a/app/code/Magento/Checkout/composer.json +++ b/app/code/Magento/Checkout/composer.json @@ -27,7 +27,7 @@ "magento/module-cookie": "100.0.*" }, "type": "magento2-module", - "version": "100.0.12", + "version": "100.0.14", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Checkout/view/frontend/web/js/model/shipping-rates-validator.js b/app/code/Magento/Checkout/view/frontend/web/js/model/shipping-rates-validator.js index f8ce4370ca75a..e0fa5ed977a28 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/model/shipping-rates-validator.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/model/shipping-rates-validator.js @@ -12,6 +12,7 @@ define( '../action/select-shipping-address', './postcode-validator', 'mage/translate', + 'uiRegistry', 'Magento_Checkout/js/model/quote' ], function ( @@ -22,6 +23,7 @@ define( selectShippingAddress, postcodeValidator, $t, + uiRegistry, quote ) { 'use strict'; @@ -29,7 +31,8 @@ define( var checkoutConfig = window.checkoutConfig, validators = [], observedElements = [], - postcodeElement = null; + postcodeElement = null, + postcodeElementName = 'postcode'; return { validateAddressTimeout: 0, @@ -55,26 +58,57 @@ define( }); }, + /** + * Perform postponed binding for fieldset elements + * + * @param {String} formPath + */ + initFields: function (formPath) { + var self = this, + elements = shippingRatesValidationRules.getObservableFields(); + + if ($.inArray(postcodeElementName, elements) === -1) { + // Add postcode field to observables if not exist for zip code validation support + elements.push(postcodeElementName); + } + + $.each(elements, function (index, field) { + uiRegistry.async(formPath + '.' + field)(self.doElementBinding.bind(self)); + }); + }, + + /** + * Bind shipping rates request to form element + * + * @param {Object} element + * @param {Boolean} force + * @param {Number} delay + */ + doElementBinding: function (element, force, delay) { + var observableFields = shippingRatesValidationRules.getObservableFields(); + + if (element && (observableFields.indexOf(element.index) !== -1 || force)) { + if (element.index !== postcodeElementName) { + this.bindHandler(element, delay); + } + } + + if (element.index === postcodeElementName) { + this.bindHandler(element, delay); + postcodeElement = element; + } + }, + /** * @param {*} elements * @param {Boolean} force * @param {Number} delay */ bindChangeHandlers: function (elements, force, delay) { - var self = this, - observableFields = shippingRatesValidationRules.getObservableFields(); + var self = this; $.each(elements, function (index, elem) { - if (elem && (observableFields.indexOf(elem.index) != -1 || force)) { - if (elem.index !== 'postcode') { - self.bindHandler(elem, delay); - } - } - - if (elem.index === 'postcode') { - self.bindHandler(elem, delay); - postcodeElement = elem; - } + self.doElementBinding(elem, force, delay); }); }, @@ -87,7 +121,7 @@ define( delay = typeof delay === "undefined" ? self.validateDelay : delay; - if (element.component.indexOf('/group') != -1) { + if (element.component.indexOf('/group') !== -1) { $.each(element.elems(), function (index, elem) { self.bindHandler(elem); }); diff --git a/app/code/Magento/Checkout/view/frontend/web/js/view/shipping.js b/app/code/Magento/Checkout/view/frontend/web/js/view/shipping.js index 037de39847c2f..abb252e0acacf 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/view/shipping.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/view/shipping.js @@ -69,8 +69,13 @@ define( quoteIsVirtual: quote.isVirtual(), initialize: function () { - var self = this; + var self = this, + hasNewAddress, + fieldsetName = 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset'; + this._super(); + shippingRatesValidator.initFields(fieldsetName); + if (!quote.isVirtual()) { stepNavigator.registerStep( 'shipping', @@ -82,7 +87,7 @@ define( } checkoutDataResolver.resolveShippingAddress(); - var hasNewAddress = addressList.some(function (address) { + hasNewAddress = addressList.some(function (address) { return address.getType() == 'new-customer-address'; }); @@ -94,7 +99,7 @@ define( } }); - quote.shippingMethod.subscribe(function (value) { + quote.shippingMethod.subscribe(function () { self.errorValidationMessage(false); }); @@ -118,13 +123,7 @@ define( //load data from server for shipping step }, - initElement: function(element) { - if (element.index === 'shipping-address-fieldset') { - shippingRatesValidator.bindChangeHandlers(element.elems(), false); - } - }, - - getPopUp: function() { + getPopUp: function () { var self = this; if (!popUp) { var buttons = this.popUpForm.options.buttons; diff --git a/app/code/Magento/CheckoutAgreements/Controller/Adminhtml/Agreement.php b/app/code/Magento/CheckoutAgreements/Controller/Adminhtml/Agreement.php index 4d32d3619930b..ceae8d2e3a56f 100644 --- a/app/code/Magento/CheckoutAgreements/Controller/Adminhtml/Agreement.php +++ b/app/code/Magento/CheckoutAgreements/Controller/Adminhtml/Agreement.php @@ -7,6 +7,11 @@ abstract class Agreement extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_CheckoutAgreements::checkoutagreement'; + /** * Core registry * @@ -44,13 +49,4 @@ protected function _initAction() ); return $this; } - - /** - * @return bool - * @codeCoverageIgnore - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CheckoutAgreements::checkoutagreement'); - } } diff --git a/app/code/Magento/CheckoutAgreements/composer.json b/app/code/Magento/CheckoutAgreements/composer.json index 4ccb76b8b9c87..8aebe767441b6 100644 --- a/app/code/Magento/CheckoutAgreements/composer.json +++ b/app/code/Magento/CheckoutAgreements/composer.json @@ -10,7 +10,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.7", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Block.php b/app/code/Magento/Cms/Controller/Adminhtml/Block.php index 26224c1d92724..85ae5e0164b71 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Block.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Block.php @@ -12,6 +12,11 @@ */ abstract class Block extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::block'; + /** * Core registry * @@ -42,14 +47,4 @@ protected function initPage($resultPage) ->addBreadcrumb(__('Static Blocks'), __('Static Blocks')); return $resultPage; } - - /** - * Check the permission to run it - * - * @return boolean - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::block'); - } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Block/InlineEdit.php b/app/code/Magento/Cms/Controller/Adminhtml/Block/InlineEdit.php index 12f4eda2a0436..f6c1eb26dd172 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Block/InlineEdit.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Block/InlineEdit.php @@ -12,6 +12,13 @@ class InlineEdit extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::block'; + /** @var BlockRepository */ protected $blockRepository; diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Block/MassDelete.php b/app/code/Magento/Cms/Controller/Adminhtml/Block/MassDelete.php index e007ccf3b1888..664816dc9e1ea 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Block/MassDelete.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Block/MassDelete.php @@ -16,6 +16,13 @@ */ class MassDelete extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::block'; + /** * @var Filter */ @@ -57,6 +64,7 @@ public function execute() /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + return $resultRedirect->setPath('*/*/'); } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Block/Widget/Chooser.php b/app/code/Magento/Cms/Controller/Adminhtml/Block/Widget/Chooser.php index c41661d57e440..4b2ef36fabaa4 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Block/Widget/Chooser.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Block/Widget/Chooser.php @@ -12,6 +12,13 @@ class Chooser extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Widget::widget_instance'; + /** * @var \Magento\Framework\View\LayoutFactory */ @@ -46,7 +53,7 @@ public function execute() $uniqId = $this->getRequest()->getParam('uniq_id'); $pagesGrid = $layout->createBlock( - 'Magento\Cms\Block\Adminhtml\Block\Widget\Chooser', + \Magento\Cms\Block\Adminhtml\Block\Widget\Chooser::class, '', ['data' => ['id' => $uniqId]] ); @@ -54,6 +61,7 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); $resultRaw->setContents($pagesGrid->toHtml()); + return $resultRaw; } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/Delete.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/Delete.php index a67e102fece99..8698cad58541c 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/Delete.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/Delete.php @@ -11,10 +11,7 @@ class Delete extends \Magento\Backend\App\Action /** * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::page_delete'); - } + const ADMIN_RESOURCE = 'Magento_Cms::page_delete'; /** * Delete action diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/Edit.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/Edit.php index 949e11ca53be3..093639f6bc1f6 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/Edit.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/Edit.php @@ -10,6 +10,11 @@ class Edit extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** * Core registry * @@ -37,14 +42,6 @@ public function __construct( parent::__construct($context); } - /** - * {@inheritdoc} - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::save'); - } - /** * Init actions * diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/Index.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/Index.php index 5ce039b98cafc..03cf3c820afae 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/Index.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/Index.php @@ -11,6 +11,11 @@ class Index extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::page'; + /** * @var PageFactory */ @@ -27,15 +32,6 @@ public function __construct( parent::__construct($context); $this->resultPageFactory = $resultPageFactory; } - /** - * Check the permission to run it - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::page'); - } /** * Index action diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/InlineEdit.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/InlineEdit.php index 875d03a371157..dcda79216696e 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/InlineEdit.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/InlineEdit.php @@ -17,6 +17,13 @@ */ class InlineEdit extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** @var PostDataProcessor */ protected $dataProcessor; @@ -105,6 +112,7 @@ protected function filterPost($postData = []) $pageData['custom_root_template'] = isset($pageData['custom_root_template']) ? $pageData['custom_root_template'] : null; + return $pageData; } @@ -150,6 +158,7 @@ protected function getErrorWithPageId(PageInterface $page, $errorText) public function setCmsPageData(\Magento\Cms\Model\Page $page, array $extendedPageData, array $pageData) { $page->setData(array_merge($page->getData(), $extendedPageData, $pageData)); + return $this; } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDelete.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDelete.php index c1897496e0361..04b0b4f1139be 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDelete.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDelete.php @@ -15,6 +15,13 @@ */ class MassDelete extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::page_delete'; + /** * @var Filter */ @@ -56,6 +63,7 @@ public function execute() /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + return $resultRedirect->setPath('*/*/'); } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDisable.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDisable.php index d6865cf1cdfd4..cb4c9b2135eda 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDisable.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassDisable.php @@ -15,6 +15,13 @@ */ class MassDisable extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** * @var Filter */ @@ -56,6 +63,7 @@ public function execute() /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + return $resultRedirect->setPath('*/*/'); } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassEnable.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassEnable.php index df8eedc221480..8d164aa1473b2 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/MassEnable.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/MassEnable.php @@ -15,6 +15,13 @@ */ class MassEnable extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** * @var Filter */ @@ -56,6 +63,7 @@ public function execute() /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + return $resultRedirect->setPath('*/*/'); } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/NewAction.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/NewAction.php index 094b242a49cff..a923196549122 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/NewAction.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/NewAction.php @@ -8,6 +8,11 @@ class NewAction extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** * @var \Magento\Backend\Model\View\Result\Forward */ @@ -25,14 +30,6 @@ public function __construct( parent::__construct($context); } - /** - * {@inheritdoc} - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::save'); - } - /** * Forward to edit * diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/Save.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/Save.php index d23109468517e..0e1b6a96c1953 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/Save.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/Save.php @@ -10,27 +10,35 @@ class Save extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::save'; + /** * @var PostDataProcessor */ protected $dataProcessor; + /** + * @var \Magento\Cms\Model\PageFactory + */ + private $pageFactory; + /** * @param Action\Context $context * @param PostDataProcessor $dataProcessor + * @param \Magento\Cms\Model\PageFactory $pageFactory */ - public function __construct(Action\Context $context, PostDataProcessor $dataProcessor) - { - $this->dataProcessor = $dataProcessor; + public function __construct( + Action\Context $context, + PostDataProcessor $dataProcessor, + \Magento\Cms\Model\PageFactory $pageFactory = null + ) { parent::__construct($context); - } + $this->dataProcessor = $dataProcessor; + $this->pageFactory = $pageFactory ?: $this->_objectManager->get(\Magento\Cms\Model\PageFactory::class); - /** - * {@inheritdoc} - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::save'); } /** @@ -45,11 +53,18 @@ public function execute() $resultRedirect = $this->resultRedirectFactory->create(); if ($data) { $data = $this->dataProcessor->filter($data); - $model = $this->_objectManager->create('Magento\Cms\Model\Page'); + + /** @var \Magento\Cms\Model\Page $model */ + $model = $this->pageFactory->create(); $id = $this->getRequest()->getParam('page_id'); if ($id) { $model->load($id); + if (!$model->getId()) { + $this->messageManager->addErrorMessage(__('This page no longer exists.')); + + return $resultRedirect->setPath('*/*/'); + } } $model->setData($data); diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Page/Widget/Chooser.php b/app/code/Magento/Cms/Controller/Adminhtml/Page/Widget/Chooser.php index cb17c3933a488..d136fb914113e 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Page/Widget/Chooser.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Page/Widget/Chooser.php @@ -10,6 +10,13 @@ class Chooser extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Widget::widget_instance'; + /** * @var \Magento\Framework\View\LayoutFactory */ @@ -46,7 +53,7 @@ public function execute() /** @var \Magento\Framework\View\Layout $layout */ $layout = $this->layoutFactory->create(); $pagesGrid = $layout->createBlock( - 'Magento\Cms\Block\Adminhtml\Page\Widget\Chooser', + \Magento\Cms\Block\Adminhtml\Page\Widget\Chooser::class, '', ['data' => ['id' => $uniqId]] ); diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php index 6614e81c42e6a..24fadf8bd81d1 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Directive.php @@ -10,6 +10,13 @@ class Directive extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Cms::media_gallery'; + /** * @var \Magento\Framework\Url\DecoderInterface */ @@ -44,9 +51,9 @@ public function execute() { $directive = $this->getRequest()->getParam('___directive'); $directive = $this->urlDecoder->decode($directive); - $imagePath = $this->_objectManager->create('Magento\Cms\Model\Template\Filter')->filter($directive); + $imagePath = $this->_objectManager->create(\Magento\Cms\Model\Template\Filter::class)->filter($directive); /** @var \Magento\Framework\Image\Adapter\AdapterInterface $image */ - $image = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create(); + $image = $this->_objectManager->get(\Magento\Framework\Image\AdapterFactory::class)->create(); /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); try { @@ -54,12 +61,13 @@ public function execute() $resultRaw->setHeader('Content-Type', $image->getMimeType()); $resultRaw->setContents($image->getImage()); } catch (\Exception $e) { - $imagePath = $this->_objectManager->get('Magento\Cms\Model\Wysiwyg\Config')->getSkinImagePlaceholderPath(); + $imagePath = $this->_objectManager->get(\Magento\Cms\Model\Wysiwyg\Config::class)->getSkinImagePlaceholderPath(); $image->open($imagePath); $resultRaw->setHeader('Content-Type', $image->getMimeType()); $resultRaw->setContents($image->getImage()); - $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e); + $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); } + return $resultRaw; } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images.php b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images.php index 8a3b6420cc5b2..59f3afe3d9f3d 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images.php @@ -12,6 +12,11 @@ */ abstract class Images extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Cms::media_gallery'; + /** * Core registry * @@ -53,14 +58,4 @@ public function getStorage() } return $this->_coreRegistry->registry('storage'); } - - /** - * Check current user permission on resource and privilege - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Cms::media_gallery'); - } } diff --git a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFiles.php b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFiles.php index 8093f840669ca..6356af9a67fe1 100644 --- a/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFiles.php +++ b/app/code/Magento/Cms/Controller/Adminhtml/Wysiwyg/Images/DeleteFiles.php @@ -1,6 +1,5 @@ getRequest()->getParam('files'); /** @var $helper \Magento\Cms\Helper\Wysiwyg\Images */ - $helper = $this->_objectManager->get('Magento\Cms\Helper\Wysiwyg\Images'); + $helper = $this->_objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class); $path = $this->getStorage()->getSession()->getCurrentPath(); foreach ($files as $file) { $file = $helper->idDecode($file); /** @var \Magento\Framework\Filesystem $filesystem */ - $filesystem = $this->_objectManager->get('Magento\Framework\Filesystem'); + $filesystem = $this->_objectManager->get(\Magento\Framework\Filesystem::class); $dir = $filesystem->getDirectoryRead(DirectoryList::MEDIA); - $filePath = $path . '/' . $file; + $filePath = $path . '/' . \Magento\Framework\File\Uploader::getCorrectFileName($file); if ($dir->isFile($dir->getRelativePath($filePath))) { $this->getStorage()->deleteFile($filePath); } } + return $this->resultRawFactory->create(); } catch (\Exception $e) { $result = ['error' => true, 'message' => $e->getMessage()]; /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); + return $resultJson->setData($result); } } diff --git a/app/code/Magento/Cms/Model/Wysiwyg/Config.php b/app/code/Magento/Cms/Model/Wysiwyg/Config.php index 1f0a7415bdc82..a7e9f45878acc 100644 --- a/app/code/Magento/Cms/Model/Wysiwyg/Config.php +++ b/app/code/Magento/Cms/Model/Wysiwyg/Config.php @@ -164,6 +164,7 @@ public function getConfig($data = []) ), 'width' => '100%', 'plugins' => [], + 'add_directives' => true, ] ); diff --git a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php b/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php deleted file mode 100644 index bd2e2068f2d47..0000000000000 --- a/app/code/Magento/Cms/Test/Unit/Ui/Component/Listing/Column/PageActionsTest.php +++ /dev/null @@ -1,95 +0,0 @@ -getMockBuilder('Magento\Framework\UrlInterface') - ->disableOriginalConstructor() - ->getMock(); - $contextMock = $this->getMockBuilder('Magento\Framework\View\Element\UiComponent\ContextInterface') - ->getMockForAbstractClass(); - $processor = $this->getMockBuilder('Magento\Framework\View\Element\UiComponent\Processor') - ->disableOriginalConstructor() - ->getMock(); - $contextMock->expects($this->any())->method('getProcessor')->willReturn($processor); - - /** @var \Magento\Cms\Ui\Component\Listing\Column\PageActions $model */ - $model = $objectManager->getObject( - 'Magento\Cms\Ui\Component\Listing\Column\PageActions', - [ - 'urlBuilder' => $urlBuilderMock, - 'context' => $contextMock, - ] - ); - - // Define test input and expectations - $items = [ - 'data' => [ - 'items' => [ - [ - 'page_id' => $pageId - ] - ] - ] - ]; - $name = 'item_name'; - $expectedItems = [ - [ - 'page_id' => $pageId, - $name => [ - 'edit' => [ - 'href' => 'test/url/edit', - 'label' => __('Edit'), - ], - 'delete' => [ - 'href' => 'test/url/delete', - 'label' => __('Delete'), - 'confirm' => [ - 'title' => __('Delete ${ $.$data.title }'), - 'message' => __('Are you sure you wan\'t to delete a ${ $.$data.title } record?') - ], - ] - ], - ] - ]; - - // Configure mocks and object data - $urlBuilderMock->expects($this->any()) - ->method('getUrl') - ->willReturnMap( - [ - [ - PageActions::CMS_URL_PATH_EDIT, - [ - 'page_id' => $pageId - ], - 'test/url/edit', - ], - [ - PageActions::CMS_URL_PATH_DELETE, - [ - 'page_id' => $pageId - ], - 'test/url/delete', - ], - ] - ); - - $model->setName($name); - $items = $model->prepareDataSource($items); - // Run test - $this->assertEquals($expectedItems, $items['data']['items']); - } -} diff --git a/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php b/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php index 500e95919081d..72aaee52ab308 100644 --- a/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php +++ b/app/code/Magento/Cms/Ui/Component/Listing/Column/BlockActions.php @@ -9,6 +9,8 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Escaper; /** * Class BlockActions @@ -27,6 +29,13 @@ class BlockActions extends Column */ protected $urlBuilder; + /** + * Escaper. + * + * @var Escaper + */ + private $escaper; + /** * Constructor * @@ -48,11 +57,7 @@ public function __construct( } /** - * @param array $items - * @return array - */ - /** - * Prepare Data Source + * Prepare Data Source. * * @param array $dataSource * @return array @@ -62,6 +67,7 @@ public function prepareDataSource(array $dataSource) if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (isset($item['block_id'])) { + $title = $this->getEscaper()->escapeHtml($item['title']); $item[$this->getData('name')] = [ 'edit' => [ 'href' => $this->urlBuilder->getUrl( @@ -72,15 +78,6 @@ public function prepareDataSource(array $dataSource) ), 'label' => __('Edit') ], - 'details' => [ - 'href' => $this->urlBuilder->getUrl( - static::URL_PATH_DETAILS, - [ - 'block_id' => $item['block_id'] - ] - ), - 'label' => __('Details') - ], 'delete' => [ 'href' => $this->urlBuilder->getUrl( static::URL_PATH_DELETE, @@ -90,10 +87,10 @@ public function prepareDataSource(array $dataSource) ), 'label' => __('Delete'), 'confirm' => [ - 'title' => __('Delete "${ $.$data.title }"'), - 'message' => __('Are you sure you wan\'t to delete a "${ $.$data.title }" record?') - ] - ] + 'title' => __('Delete %1', $title), + 'message' => __('Are you sure you wan\'t to delete a %1 record?', $title), + ], + ], ]; } } @@ -101,4 +98,19 @@ public function prepareDataSource(array $dataSource) return $dataSource; } + + /** + * Get instance of escaper. + * + * @return Escaper + * @deprecated + */ + private function getEscaper() + { + if (!$this->escaper) { + $this->escaper = ObjectManager::getInstance()->get(Escaper::class); + } + + return $this->escaper; + } } diff --git a/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php b/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php index ee51f6dd0247b..bc1fd75e76de0 100644 --- a/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php +++ b/app/code/Magento/Cms/Ui/Component/Listing/Column/PageActions.php @@ -5,11 +5,13 @@ */ namespace Magento\Cms\Ui\Component\Listing\Column; +use Magento\Cms\Block\Adminhtml\Page\Grid\Renderer\Action\UrlBuilder; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Escaper; +use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; -use Magento\Cms\Block\Adminhtml\Page\Grid\Renderer\Action\UrlBuilder; -use Magento\Framework\UrlInterface; /** * Class PageActions @@ -31,6 +33,13 @@ class PageActions extends Column */ private $editUrl; + /** + * Escaper. + * + * @var Escaper + */ + private $escaper; + /** * @param ContextInterface $context * @param UiComponentFactory $uiComponentFactory @@ -71,13 +80,14 @@ public function prepareDataSource(array $dataSource) 'href' => $this->urlBuilder->getUrl($this->editUrl, ['page_id' => $item['page_id']]), 'label' => __('Edit') ]; + $title = $this->getEscaper()->escapeHtml($item['title']); $item[$name]['delete'] = [ 'href' => $this->urlBuilder->getUrl(self::CMS_URL_PATH_DELETE, ['page_id' => $item['page_id']]), 'label' => __('Delete'), 'confirm' => [ - 'title' => __('Delete ${ $.$data.title }'), - 'message' => __('Are you sure you wan\'t to delete a ${ $.$data.title } record?') - ] + 'title' => __('Delete %1', $title), + 'message' => __('Are you sure you wan\'t to delete a %1 record?', $title), + ], ]; } if (isset($item['identifier'])) { @@ -95,4 +105,19 @@ public function prepareDataSource(array $dataSource) return $dataSource; } + + /** + * Get instance of escaper. + * + * @return Escaper + * @deprecated + */ + private function getEscaper() + { + if (!$this->escaper) { + $this->escaper = ObjectManager::getInstance()->get(Escaper::class); + } + + return $this->escaper; + } } diff --git a/app/code/Magento/Cms/Ui/Component/Listing/Columns.php b/app/code/Magento/Cms/Ui/Component/Listing/Columns.php new file mode 100644 index 0000000000000..99d970d814b76 --- /dev/null +++ b/app/code/Magento/Cms/Ui/Component/Listing/Columns.php @@ -0,0 +1,70 @@ +authorization = $authorization ?: + \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Framework\AuthorizationInterface::class); + } + + /** + * {@inheritdoc} + */ + public function prepare() + { + parent::prepare(); + $this->applyEditPermission(); + } + + /** + * Applying InlineEditor permission. + * + * @return void + */ + private function applyEditPermission() + { + if (!$this->authorization->isAllowed('Magento_Cms::save')) { + $editPermissions = [ + 'config' => [ + 'editorConfig' => [ + 'enabled' => false, + ], + ], + ]; + $data = $this->getData(); + $data = array_replace_recursive($data, $editPermissions); + $this->setData($data); + } + } +} diff --git a/app/code/Magento/Cms/composer.json b/app/code/Magento/Cms/composer.json index 0fe5a8540fd46..891d979bf047b 100644 --- a/app/code/Magento/Cms/composer.json +++ b/app/code/Magento/Cms/composer.json @@ -18,7 +18,7 @@ "magento/module-cms-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.8", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Cms/i18n/en_US.csv b/app/code/Magento/Cms/i18n/en_US.csv index 58485f3d9d2c5..1d947bc412f92 100644 --- a/app/code/Magento/Cms/i18n/en_US.csv +++ b/app/code/Magento/Cms/i18n/en_US.csv @@ -124,3 +124,5 @@ Blocks,Blocks Widgets,Widgets Themes,Themes Schedule,Schedule +"Delete %1","Delete %1" +"Are you sure you wan\'t to delete a %1 record?","Are you sure you wan\'t to delete a %1 record?" diff --git a/app/code/Magento/Cms/view/adminhtml/ui_component/cms_block_listing.xml b/app/code/Magento/Cms/view/adminhtml/ui_component/cms_block_listing.xml index b57deb5326259..d3514a680ae9f 100644 --- a/app/code/Magento/Cms/view/adminhtml/ui_component/cms_block_listing.xml +++ b/app/code/Magento/Cms/view/adminhtml/ui_component/cms_block_listing.xml @@ -20,6 +20,7 @@ */*/new + Magento_Cms::block diff --git a/app/code/Magento/Cms/view/adminhtml/ui_component/cms_page_listing.xml b/app/code/Magento/Cms/view/adminhtml/ui_component/cms_page_listing.xml index 5a4dee3a0fed3..184695706ef82 100644 --- a/app/code/Magento/Cms/view/adminhtml/ui_component/cms_page_listing.xml +++ b/app/code/Magento/Cms/view/adminhtml/ui_component/cms_page_listing.xml @@ -20,6 +20,7 @@ */*/new + Magento_Cms::page @@ -181,7 +182,7 @@ - + diff --git a/app/code/Magento/Config/Model/Config/Backend/Image/Favicon.php b/app/code/Magento/Config/Model/Config/Backend/Image/Favicon.php index 998e3b9f48312..ba86529419555 100644 --- a/app/code/Magento/Config/Model/Config/Backend/Image/Favicon.php +++ b/app/code/Magento/Config/Model/Config/Backend/Image/Favicon.php @@ -45,6 +45,6 @@ protected function _addWhetherScopeInfo() */ protected function _getAllowedExtensions() { - return ['ico', 'png', 'gif', 'jpg', 'jpeg', 'apng', 'svg']; + return ['ico', 'png', 'gif', 'jpg', 'jpeg', 'apng']; } } diff --git a/app/code/Magento/Config/Model/Config/Backend/Image/Logo.php b/app/code/Magento/Config/Model/Config/Backend/Image/Logo.php index d262311e2d762..72e598c606874 100644 --- a/app/code/Magento/Config/Model/Config/Backend/Image/Logo.php +++ b/app/code/Magento/Config/Model/Config/Backend/Image/Logo.php @@ -45,6 +45,6 @@ protected function _addWhetherScopeInfo() */ protected function _getAllowedExtensions() { - return ['jpg', 'jpeg', 'gif', 'png', 'svg']; + return ['jpg', 'jpeg', 'gif', 'png']; } } diff --git a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php index 9eee246aa04c2..9488db336dc47 100644 --- a/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/Config/Backend/Image/LogoTest.php @@ -30,11 +30,11 @@ class LogoTest extends \PHPUnit_Framework_TestCase public function setUp() { $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->uploaderFactoryMock = $this->getMockBuilder('\Magento\MediaStorage\Model\File\UploaderFactory') + $this->uploaderFactoryMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->uploaderMock = $this->getMockBuilder('\Magento\MediaStorage\Model\File\Uploader') + $this->uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) ->setMethods(['setAllowedExtensions', 'save']) ->disableOriginalConstructor() ->getMock(); @@ -43,13 +43,13 @@ public function setUp() ->method('create') ->will($this->returnValue($this->uploaderMock)); $this->requestDataMock = $this - ->getMockBuilder('\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface') + ->getMockBuilder(\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface::class) ->setMethods(['getTmpName']) ->getMockForAbstractClass(); - $mediaDirectoryMock = $this->getMockBuilder('\Magento\Framework\Filesystem\Directory\WriteInterface') + $mediaDirectoryMock = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $filesystemMock = $this->getMockBuilder('\Magento\Framework\Filesystem') + $filesystemMock = $this->getMockBuilder(\Magento\Framework\Filesystem::class) ->disableOriginalConstructor() ->setMethods(['getDirectoryWrite']) ->getMock(); @@ -57,7 +57,7 @@ public function setUp() ->method('getDirectoryWrite') ->will($this->returnValue($mediaDirectoryMock)); $this->model = $helper->getObject( - 'Magento\Config\Model\Config\Backend\Image\Logo', + \Magento\Config\Model\Config\Backend\Image\Logo::class, [ 'uploaderFactory' => $this->uploaderFactoryMock, 'requestData' => $this->requestDataMock, @@ -73,7 +73,7 @@ public function testBeforeSave() ->will($this->returnValue('/tmp/val')); $this->uploaderMock->expects($this->once()) ->method('setAllowedExtensions') - ->with($this->equalTo(['jpg', 'jpeg', 'gif', 'png', 'svg'])); + ->with($this->equalTo(['jpg', 'jpeg', 'gif', 'png'])); $this->model->beforeSave(); } } diff --git a/app/code/Magento/Config/composer.json b/app/code/Magento/Config/composer.json index 555e5c3942e87..64853fbd5572c 100644 --- a/app/code/Magento/Config/composer.json +++ b/app/code/Magento/Config/composer.json @@ -12,7 +12,7 @@ "magento/module-media-storage": "100.0.*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.7", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/AddAttribute.php b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/AddAttribute.php index 77aabc52e3e19..fa53550f1f18b 100644 --- a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/AddAttribute.php +++ b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/AddAttribute.php @@ -10,6 +10,13 @@ class AddAttribute extends Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var \Magento\Catalog\Controller\Adminhtml\Product\Builder */ @@ -37,7 +44,7 @@ public function execute() $this->_view->loadLayout('popup'); $this->productBuilder->build($this->getRequest()); $attributeBlock = $this->_view->getLayout()->createBlock( - 'Magento\ConfigurableProduct\Block\Adminhtml\Product\Attribute\NewAttribute\Product\Created' + \Magento\ConfigurableProduct\Block\Adminhtml\Product\Attribute\NewAttribute\Product\Created::class ); $this->_addContent($attributeBlock); $this->_view->renderLayout(); diff --git a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Associated/Grid.php b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Associated/Grid.php index 772e2ba3de976..dd088e3d7f726 100644 --- a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Associated/Grid.php +++ b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Associated/Grid.php @@ -12,6 +12,13 @@ class Grid extends Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Catalog::products'; + /** * @var LayoutFactory */ @@ -37,6 +44,7 @@ public function execute() { /** @var \Magento\Framework\View\Result\Layout $resultPage */ $resultPage = $this->resultPageFactory->create(); + return $resultPage; } } diff --git a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/CreateOptions.php b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/CreateOptions.php index 4a76951992be6..88abecd39ff91 100644 --- a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/CreateOptions.php +++ b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/CreateOptions.php @@ -12,6 +12,11 @@ class CreateOptions extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::attributes_attributes'; + /** * @var \Magento\Framework\Json\Helper\Data */ @@ -37,16 +42,6 @@ public function __construct( parent::__construct($context); } - /** - * ACL check - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::attributes_attributes'); - } - /** * Search for attributes by part of attribute's label in admin store * diff --git a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/GetAttributes.php b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/GetAttributes.php index 91c5d174e9804..11e99dad3d177 100644 --- a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/GetAttributes.php +++ b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/GetAttributes.php @@ -11,6 +11,11 @@ class GetAttributes extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::attributes_attributes'; + /** * Store manager * @@ -41,16 +46,6 @@ public function __construct( parent::__construct($context); } - /** - * ACL check - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::attributes_attributes'); - } - /** * Get attributes * diff --git a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributes.php b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributes.php index e2f553747b8ee..735f3d0cb3b4a 100644 --- a/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributes.php +++ b/app/code/Magento/ConfigurableProduct/Controller/Adminhtml/Product/Attribute/SuggestConfigurableAttributes.php @@ -11,6 +11,11 @@ class SuggestConfigurableAttributes extends Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Catalog::attributes_attributes'; + /** * @var \Magento\ConfigurableProduct\Model\SuggestedAttributeList */ @@ -46,16 +51,6 @@ public function __construct( parent::__construct($context); } - /** - * ACL check - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Catalog::attributes_attributes'); - } - /** * Search for attributes by part of attribute's label in admin store * diff --git a/app/code/Magento/ConfigurableProduct/composer.json b/app/code/Magento/ConfigurableProduct/composer.json index e6aa5d00899a7..fd94aad547b0a 100644 --- a/app/code/Magento/ConfigurableProduct/composer.json +++ b/app/code/Magento/ConfigurableProduct/composer.json @@ -23,7 +23,7 @@ "magento/module-product-links-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.9", + "version": "100.0.11", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/templates/catalog/product/edit/super/matrix.phtml b/app/code/Magento/ConfigurableProduct/view/adminhtml/templates/catalog/product/edit/super/matrix.phtml index f946bff4d474e..0e8568a497133 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/templates/catalog/product/edit/super/matrix.phtml +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/templates/catalog/product/edit/super/matrix.phtml @@ -287,7 +287,7 @@ $currencySymbol = $block->getCurrencySymbol(); "component": "Magento_ConfigurableProduct/js/variations/variations", "variations": helper('Magento\Framework\Json\Helper\Data')->jsonEncode($productMatrix) ?>, "productAttributes": helper('Magento\Framework\Json\Helper\Data')->jsonEncode($attributes) ?>, - "productUrl": "getUrl('catalog/product/edit', ['id' => '%id%']) ?>", + "productUrl": "getUrl('catalog/product/edit', ['id' => '%id%', '_escape_params' => false]) ?>", "currencySymbol": "", "configurableProductGrid": "configurableProductGrid" } diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/configurable_associated_product_listing.xml b/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/configurable_associated_product_listing.xml index 54e0f13ad6967..18d4bd444d6cf 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/configurable_associated_product_listing.xml +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/configurable_associated_product_listing.xml @@ -12,6 +12,7 @@ configurable_associated_product_listing.data_source product_columns + Magento_Catalog::products diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/product_attributes_listing.xml b/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/product_attributes_listing.xml index 2e1c895727cbb..f13b61e2398cc 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/product_attributes_listing.xml +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/ui_component/product_attributes_listing.xml @@ -12,6 +12,7 @@ product_attributes_listing.product_attributes_listing_data_source product_attributes_columns + Magento_Catalog::products diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/configurable-type-handler.js b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/configurable-type-handler.js index 11c83d6a0be05..37d5506a8b2da 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/configurable-type-handler.js +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/configurable-type-handler.js @@ -93,7 +93,6 @@ define([ suggestContainer.removeClass('disabled').removeProp('disabled'); $('#inventory_qty').removeProp('disabled'); $('#inventory_stock_availability').prop('disabled', true); - this._setElementDisabled($('#quantity_and_stock_status'), true, false); this._setElementDisabled($('#qty'), false, true); } diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/variations.js b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/variations.js index 29503e4be296f..64c1d34fbcd3e 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/variations.js +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/variations.js @@ -68,7 +68,7 @@ define([ */ initObservable: function () { var $form = $('[data-form="edit-product"]'), - formSubmitHandlers = $form.data('events').submit, + formSubmitHandlers, pagingObservables = { current: ko.getObservable(this.paging, 'current'), pageSize: ko.getObservable(this.paging, 'pageSize') @@ -102,7 +102,12 @@ define([ $form.validation('isValid'); } }.bind(this)); - formSubmitHandlers.splice(0, 0, formSubmitHandlers.pop()); + + formSubmitHandlers = $form.data('events').submit || []; + + if (formSubmitHandlers.length > 1) { + formSubmitHandlers.unshift(formSubmitHandlers.pop()); + } return this; }, diff --git a/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency.php b/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency.php index f489ffd5f1b3e..c40c03fd1a8da 100644 --- a/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency.php +++ b/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currency.php @@ -13,6 +13,11 @@ abstract class Currency extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_CurrencySymbol::currency_rates'; + /** * Core registry * @@ -29,14 +34,4 @@ public function __construct(\Magento\Backend\App\Action\Context $context, \Magen $this->_coreRegistry = $coreRegistry; parent::__construct($context); } - - /** - * Check if allowed - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CurrencySymbol::currency_rates'); - } } diff --git a/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol.php b/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol.php index da1f2e07f1ff2..c9fcf85186ff4 100644 --- a/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol.php +++ b/app/code/Magento/CurrencySymbol/Controller/Adminhtml/System/Currencysymbol.php @@ -14,12 +14,7 @@ abstract class Currencysymbol extends \Magento\Backend\App\Action { /** - * Check the permission to run it - * - * @return bool + * {@inheritdoc} */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_CurrencySymbol::symbols'); - } + const ADMIN_RESOURCE = 'Magento_CurrencySymbol::symbols'; } diff --git a/app/code/Magento/CurrencySymbol/composer.json b/app/code/Magento/CurrencySymbol/composer.json index a9f702700e19a..8535a7eb92ee1 100644 --- a/app/code/Magento/CurrencySymbol/composer.json +++ b/app/code/Magento/CurrencySymbol/composer.json @@ -11,7 +11,7 @@ "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.6", + "version": "100.0.7", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/CurrencySymbol/view/adminhtml/templates/grid.phtml b/app/code/Magento/CurrencySymbol/view/adminhtml/templates/grid.phtml index 2de297bbc7eb8..e55b46eb93d25 100644 --- a/app/code/Magento/CurrencySymbol/view/adminhtml/templates/grid.phtml +++ b/app/code/Magento/CurrencySymbol/view/adminhtml/templates/grid.phtml @@ -9,7 +9,7 @@ ?> @@ -27,7 +27,7 @@ name="custom_currency_symbol[]">
diff --git a/app/code/Magento/Customer/Block/Account/AuthenticationPopup.php b/app/code/Magento/Customer/Block/Account/AuthenticationPopup.php index b8fa937e23615..32e14b3bbf77b 100644 --- a/app/code/Magento/Customer/Block/Account/AuthenticationPopup.php +++ b/app/code/Magento/Customer/Block/Account/AuthenticationPopup.php @@ -5,6 +5,9 @@ */ namespace Magento\Customer\Block\Account; +use Magento\Customer\Model\Form; +use Magento\Store\Model\ScopeInterface; + class AuthenticationPopup extends \Magento\Framework\View\Element\Template { /** @@ -40,12 +43,26 @@ public function getJsLayout() public function getConfig() { return [ - 'customerRegisterUrl' => $this->getCustomerRegisterUrlUrl(), - 'customerForgotPasswordUrl' => $this->getCustomerForgotPasswordUrl(), - 'baseUrl' => $this->getBaseUrl() + 'autocomplete' => $this->escapeHtml($this->isAutocompleteEnabled()), + 'customerRegisterUrl' => $this->escapeUrl($this->getCustomerRegisterUrlUrl()), + 'customerForgotPasswordUrl' => $this->escapeUrl($this->getCustomerForgotPasswordUrl()), + 'baseUrl' => $this->escapeUrl($this->getBaseUrl()), ]; } + /** + * Is autocomplete enabled for storefront. + * + * @return string + */ + private function isAutocompleteEnabled() + { + return $this->_scopeConfig->getValue( + Form::XML_PATH_ENABLE_AUTOCOMPLETE, + ScopeInterface::SCOPE_WEBSITE + ) ? 'on' : 'off'; + } + /** * Return base url. * diff --git a/app/code/Magento/Customer/Controller/Account/CreatePost.php b/app/code/Magento/Customer/Controller/Account/CreatePost.php index 3c18a6a5e0e9d..bafd556560ad5 100644 --- a/app/code/Magento/Customer/Controller/Account/CreatePost.php +++ b/app/code/Magento/Customer/Controller/Account/CreatePost.php @@ -26,6 +26,7 @@ use Magento\Customer\Model\CustomerExtractor; use Magento\Framework\Exception\StateException; use Magento\Framework\Exception\InputException; +use Magento\Framework\Data\Form\FormKey\Validator; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -87,6 +88,13 @@ class CreatePost extends \Magento\Customer\Controller\AbstractAccount */ private $scopeConfig; + /** + * Form key validator. + * + * @var Validator + */ + private $formKeyValidator; + /** * @param Context $context * @param Session $customerSession @@ -106,6 +114,7 @@ class CreatePost extends \Magento\Customer\Controller\AbstractAccount * @param CustomerExtractor $customerExtractor * @param DataObjectHelper $dataObjectHelper * @param AccountRedirect $accountRedirect + * @param Validator $formKeyValidator * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -127,8 +136,11 @@ public function __construct( Escaper $escaper, CustomerExtractor $customerExtractor, DataObjectHelper $dataObjectHelper, - AccountRedirect $accountRedirect + AccountRedirect $accountRedirect, + Validator $formKeyValidator = null ) { + parent::__construct($context); + $this->session = $customerSession; $this->scopeConfig = $scopeConfig; $this->storeManager = $storeManager; @@ -146,7 +158,7 @@ public function __construct( $this->urlModel = $urlFactory->create(); $this->dataObjectHelper = $dataObjectHelper; $this->accountRedirect = $accountRedirect; - parent::__construct($context); + $this->formKeyValidator = $formKeyValidator ?: $this->_objectManager->get(Validator::class); } /** @@ -187,7 +199,7 @@ protected function extractAddress() $this->dataObjectHelper->populateWithArray( $addressDataObject, $addressData, - '\Magento\Customer\Api\Data\AddressInterface' + \Magento\Customer\Api\Data\AddressInterface::class ); $addressDataObject->setRegion($regionDataObject); @@ -196,13 +208,14 @@ protected function extractAddress() )->setIsDefaultShipping( $this->getRequest()->getParam('default_shipping', false) ); + return $addressDataObject; } /** * Create customer account action * - * @return void + * @return \Magento\Framework\App\ResponseInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ @@ -212,12 +225,14 @@ public function execute() $resultRedirect = $this->resultRedirectFactory->create(); if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) { $resultRedirect->setPath('*/*/'); + return $resultRedirect; } - if (!$this->getRequest()->isPost()) { + if (!$this->getRequest()->isPost() || !$this->formKeyValidator->validate($this->getRequest())) { $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]); $resultRedirect->setUrl($this->_redirect->error($url)); + return $resultRedirect; } @@ -268,10 +283,12 @@ public function execute() if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) { $resultRedirect->setUrl($this->_redirect->success($requestedRedirect)); $this->accountRedirect->clearRedirectCookie(); + return $resultRedirect; } $resultRedirect = $this->accountRedirect->getRedirect(); } + return $resultRedirect; } catch (StateException $e) { $url = $this->urlModel->getUrl('customer/account/forgotpassword'); @@ -294,6 +311,7 @@ public function execute() $this->session->setCustomerFormData($this->getRequest()->getPostValue()); $defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]); $resultRedirect->setUrl($this->_redirect->error($defaultUrl)); + return $resultRedirect; } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/Cart.php b/app/code/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/Cart.php index 8c76300509605..77bb0ec836045 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/Cart.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Cart/Product/Composite/Cart.php @@ -15,6 +15,11 @@ */ abstract class Cart extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** * Customer we're working with * @@ -93,14 +98,4 @@ protected function _initData() return $this; } - - /** - * Check the permission to Manage Customers - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::manage'); - } } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Group.php b/app/code/Magento/Customer/Controller/Adminhtml/Group.php index 86269dde60499..8c3ee6e8261e5 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Group.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Group.php @@ -13,6 +13,11 @@ */ abstract class Group extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::group'; + /** * Core registry * @@ -65,14 +70,4 @@ public function __construct( $this->resultForwardFactory = $resultForwardFactory; $this->resultPageFactory = $resultPageFactory; } - - /** - * Determine if authorized to perform group actions. - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::group'); - } } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index.php b/app/code/Magento/Customer/Controller/Adminhtml/Index.php index fb2a8389ad6d1..e1035af1ec295 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index.php @@ -26,6 +26,11 @@ */ abstract class Index extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** * @var \Magento\Framework\Validator */ @@ -299,14 +304,4 @@ protected function actUponMultipleCustomers(callable $singleAction, $customerIds } return $customersUpdated; } - - /** - * Customer access rights checking - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::manage'); - } } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index/AbstractMassAction.php b/app/code/Magento/Customer/Controller/Adminhtml/Index/AbstractMassAction.php index 78c2180e2c8af..191d07b4617c7 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index/AbstractMassAction.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index/AbstractMassAction.php @@ -18,6 +18,11 @@ */ abstract class AbstractMassAction extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** * @var string */ @@ -64,16 +69,6 @@ public function execute() } } - /** - * Check the permission to Manage Customers - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::manage'); - } - /** * Return component referer url * TODO: Technical dept referer url should be implement as a part of Action configuration in in appropriate way diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index/InlineEdit.php b/app/code/Magento/Customer/Controller/Adminhtml/Index/InlineEdit.php index 4fb522ae53ae4..acb5c82a8bb99 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index/InlineEdit.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index/InlineEdit.php @@ -15,6 +15,11 @@ */ class InlineEdit extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** @var CustomerInterface */ private $customer; @@ -250,14 +255,4 @@ protected function getErrorWithCustomerId($errorText) { return '[Customer ID: ' . $this->getCustomer()->getId() . '] ' . __($errorText); } - - /** - * Customer access rights checking - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::manage'); - } } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Online/Index.php b/app/code/Magento/Customer/Controller/Adminhtml/Online/Index.php index 6edce38fd0c3a..707e4e4e6e1c0 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Online/Index.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Online/Index.php @@ -11,6 +11,11 @@ class Index extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::online'; + /** * @var PageFactory */ @@ -28,16 +33,6 @@ public function __construct( $this->resultPageFactory = $resultPageFactory; } - /** - * Check the permission to run it - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::online'); - } - /** * Index action * diff --git a/app/code/Magento/Customer/Controller/Adminhtml/System/Config/Validatevat.php b/app/code/Magento/Customer/Controller/Adminhtml/System/Config/Validatevat.php index 068dba9225cf1..f9ac07b914d2c 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/System/Config/Validatevat.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/System/Config/Validatevat.php @@ -12,6 +12,13 @@ */ abstract class Validatevat extends \Magento\Backend\App\Action { + /** + * Authorization level of a basic admin session. + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** * Perform customer VAT ID validation * @@ -19,7 +26,7 @@ abstract class Validatevat extends \Magento\Backend\App\Action */ protected function _validate() { - return $this->_objectManager->get('Magento\Customer\Model\Vat') + return $this->_objectManager->get(\Magento\Customer\Model\Vat::class) ->checkVatNumber( $this->getRequest()->getParam('country'), $this->getRequest()->getParam('vat') diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Wishlist/Product/Composite/Wishlist.php b/app/code/Magento/Customer/Controller/Adminhtml/Wishlist/Product/Composite/Wishlist.php index f42c0aa085714..b3752e0e8a249 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Wishlist/Product/Composite/Wishlist.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Wishlist/Product/Composite/Wishlist.php @@ -12,6 +12,11 @@ */ abstract class Wishlist extends \Magento\Backend\App\Action { + /** + * {@inheritdoc} + */ + const ADMIN_RESOURCE = 'Magento_Customer::manage'; + /** * Wishlist we're working with. * @@ -53,14 +58,4 @@ protected function _initData() return $this; } - - /** - * Check the permission to Manage Customers - * - * @return bool - */ - protected function _isAllowed() - { - return $this->_authorization->isAllowed('Magento_Customer::manage'); - } } diff --git a/app/code/Magento/Customer/Model/Account/Redirect.php b/app/code/Magento/Customer/Model/Account/Redirect.php index 9a2ccf3fa21fc..68fcd1dfb154e 100644 --- a/app/code/Magento/Customer/Model/Account/Redirect.php +++ b/app/code/Magento/Customer/Model/Account/Redirect.php @@ -8,6 +8,7 @@ use Magento\Customer\Model\Session; use Magento\Customer\Model\Url as CustomerUrl; use Magento\Framework\App\RequestInterface; +use Magento\Framework\Url\HostChecker; use Magento\Framework\UrlInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; @@ -52,6 +53,7 @@ class Redirect protected $customerUrl; /** + * @deprecated * @var UrlInterface */ protected $url; @@ -67,6 +69,11 @@ class Redirect */ private $cookieManager; + /** + * @var HostChecker + */ + private $hostChecker; + /** * @param RequestInterface $request * @param Session $customerSession @@ -76,6 +83,7 @@ class Redirect * @param DecoderInterface $urlDecoder * @param CustomerUrl $customerUrl * @param RedirectFactory $resultRedirectFactory + * @param HostChecker|null $hostChecker */ public function __construct( RequestInterface $request, @@ -85,7 +93,8 @@ public function __construct( UrlInterface $url, DecoderInterface $urlDecoder, CustomerUrl $customerUrl, - RedirectFactory $resultRedirectFactory + RedirectFactory $resultRedirectFactory, + HostChecker $hostChecker = null ) { $this->request = $request; $this->session = $customerSession; @@ -95,6 +104,7 @@ public function __construct( $this->urlDecoder = $urlDecoder; $this->customerUrl = $customerUrl; $this->resultRedirectFactory = $resultRedirectFactory; + $this->hostChecker = $hostChecker ?: ObjectManager::getInstance()->get(HostChecker::class); } /** @@ -110,6 +120,7 @@ public function getRedirect() /** @var ResultRedirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setUrl($this->session->getBeforeAuthUrl(true)); + return $resultRedirect; } @@ -188,7 +199,7 @@ protected function processLoggedCustomer() $referer = $this->request->getParam(CustomerUrl::REFERER_QUERY_PARAM_NAME); if ($referer) { $referer = $this->urlDecoder->decode($referer); - if ($this->url->isOwnOriginUrl()) { + if ($this->hostChecker->isOwnOrigin($referer)) { $this->applyRedirect($referer); } } diff --git a/app/code/Magento/Customer/Model/Customer/DataProvider.php b/app/code/Magento/Customer/Model/Customer/DataProvider.php index 98ca1174c394e..c7dc08de32086 100644 --- a/app/code/Magento/Customer/Model/Customer/DataProvider.php +++ b/app/code/Magento/Customer/Model/Customer/DataProvider.php @@ -23,6 +23,7 @@ /** * Class DataProvider + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider @@ -98,6 +99,17 @@ class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider 'file', ]; + /** + * Customer fields that must be removed + * + * @var array + */ + private $forbiddenCustomerFields = [ + 'password_hash', + 'rp_token', + 'confirmation', + ]; + /** * DataProvider Constructor * @@ -159,6 +171,10 @@ public function getData() $this->overrideFileUploaderData($customer, $result['customer']); + $result['customer'] = array_diff_key( + $result['customer'], + array_flip($this->forbiddenCustomerFields) + ); unset($result['address']); /** @var Address $address */ diff --git a/app/code/Magento/Customer/Model/FileProcessor.php b/app/code/Magento/Customer/Model/FileProcessor.php index 78542fb79a7a3..2dbbd02985f7d 100644 --- a/app/code/Magento/Customer/Model/FileProcessor.php +++ b/app/code/Magento/Customer/Model/FileProcessor.php @@ -196,6 +196,7 @@ public function saveTemporaryFile($fileId) ); $result = $uploader->save($path); + unset($result['path']); if (!$result) { throw new LocalizedException(__('File can not be saved to the destination folder.')); } diff --git a/app/code/Magento/Customer/Model/Url.php b/app/code/Magento/Customer/Model/Url.php index 3ddb222d980e1..63a1fe5d063af 100644 --- a/app/code/Magento/Customer/Model/Url.php +++ b/app/code/Magento/Customer/Model/Url.php @@ -56,25 +56,43 @@ class Url */ protected $urlEncoder; + /** + * @var \Magento\Framework\Url\DecoderInterface + */ + private $urlDecoder; + + /** + * @var \Magento\Framework\Url\HostChecker + */ + private $hostChecker; + /** * @param Session $customerSession * @param ScopeConfigInterface $scopeConfig * @param RequestInterface $request * @param UrlInterface $urlBuilder * @param EncoderInterface $urlEncoder + * @param \Magento\Framework\Url\DecoderInterface|null $urlDecoder + * @param \Magento\Framework\Url\HostChecker|null $hostChecker */ public function __construct( Session $customerSession, ScopeConfigInterface $scopeConfig, RequestInterface $request, UrlInterface $urlBuilder, - EncoderInterface $urlEncoder + EncoderInterface $urlEncoder, + \Magento\Framework\Url\DecoderInterface $urlDecoder = null, + \Magento\Framework\Url\HostChecker $hostChecker = null ) { $this->request = $request; $this->urlBuilder = $urlBuilder; $this->scopeConfig = $scopeConfig; $this->customerSession = $customerSession; $this->urlEncoder = $urlEncoder; + $this->urlDecoder = $urlDecoder ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Url\DecoderInterface::class); + $this->hostChecker = $hostChecker ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Url\HostChecker::class); } /** @@ -95,7 +113,7 @@ public function getLoginUrl() public function getLoginUrlParams() { $params = []; - $referer = $this->request->getParam(self::REFERER_QUERY_PARAM_NAME); + $referer = $this->getRequestReferrer(); if (!$referer && !$this->scopeConfig->isSetFlag( self::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD, @@ -122,11 +140,13 @@ public function getLoginUrlParams() public function getLoginPostUrl() { $params = []; - if ($this->request->getParam(self::REFERER_QUERY_PARAM_NAME)) { + $referer = $this->getRequestReferrer(); + if ($referer) { $params = [ - self::REFERER_QUERY_PARAM_NAME => $this->request->getParam(self::REFERER_QUERY_PARAM_NAME), + self::REFERER_QUERY_PARAM_NAME => $referer, ]; } + return $this->urlBuilder->getUrl('customer/account/loginPost', $params); } @@ -220,4 +240,22 @@ public function getEmailConfirmationUrl($email = null) { return $this->urlBuilder->getUrl('customer/account/confirmation', ['email' => $email]); } + + /** + * Returns request referrer. + * + * Will return referrer in case referrer from the same origin. + * Otherwise NULL will be returned. + * + * @return mixed|null + */ + private function getRequestReferrer() + { + $referer = $this->request->getParam(self::REFERER_QUERY_PARAM_NAME); + if ($referer && $this->hostChecker->isOwnOrigin($this->urlDecoder->decode($referer))) { + return $referer; + } + + return null; + } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php b/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php deleted file mode 100644 index 4e91867a3d7bd..0000000000000 --- a/app/code/Magento/Customer/Test/Unit/Model/Account/RedirectTest.php +++ /dev/null @@ -1,265 +0,0 @@ -request = $this->getMockForAbstractClass('Magento\Framework\App\RequestInterface'); - - $this->customerSession = $this->getMockBuilder('Magento\Customer\Model\Session') - ->disableOriginalConstructor() - ->setMethods([ - 'getLastCustomerId', - 'isLoggedIn', - 'getId', - 'setLastCustomerId', - 'unsBeforeAuthUrl', - 'getBeforeAuthUrl', - 'setBeforeAuthUrl', - 'getAfterAuthUrl', - 'setAfterAuthUrl', - ]) - ->getMock(); - - $this->scopeConfig = $this->getMockForAbstractClass('Magento\Framework\App\Config\ScopeConfigInterface'); - - $this->store = $this->getMockBuilder('Magento\Store\Model\Store') - ->disableOriginalConstructor() - ->getMock(); - - $this->storeManager = $this->getMockForAbstractClass('Magento\Store\Model\StoreManagerInterface'); - $this->storeManager->expects($this->once()) - ->method('getStore') - ->willReturn($this->store); - - $this->url = $this->getMockForAbstractClass('Magento\Framework\UrlInterface'); - $this->urlDecoder = $this->getMockForAbstractClass('Magento\Framework\Url\DecoderInterface'); - - $this->customerUrl = $this->getMockBuilder('Magento\Customer\Model\Url') - ->disableOriginalConstructor() - ->getMock(); - - $this->resultRedirect = $this->getMockBuilder('Magento\Framework\Controller\Result\Redirect') - ->disableOriginalConstructor() - ->getMock(); - - $this->resultRedirectFactory = $this->getMockBuilder('Magento\Framework\Controller\Result\RedirectFactory') - ->disableOriginalConstructor() - ->getMock(); - $this->resultRedirectFactory->expects($this->once()) - ->method('create') - ->willReturn($this->resultRedirect); - - $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject( - 'Magento\Customer\Model\Account\Redirect', - [ - 'request' => $this->request, - 'customerSession' => $this->customerSession, - 'scopeConfig' => $this->scopeConfig, - 'storeManager' => $this->storeManager, - 'url' => $this->url, - 'urlDecoder' => $this->urlDecoder, - 'customerUrl' => $this->customerUrl, - 'resultRedirectFactory' => $this->resultRedirectFactory - ] - ); - } - - /** - * @dataProvider getRedirectDataProvider - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function testGetRedirect( - $customerId, - $lastCustomerId, - $referer, - $baseUrl, - $beforeAuthUrl, - $afterAuthUrl, - $accountUrl, - $loginUrl, - $logoutUrl, - $dashboardUrl, - $customerLoggedIn, - $redirectToDashboard - ) { - // Preparations for method updateLastCustomerId() - $this->customerSession->expects($this->once()) - ->method('getLastCustomerId') - ->willReturn($customerId); - $this->customerSession->expects($this->any()) - ->method('isLoggedIn') - ->willReturn($customerLoggedIn); - $this->customerSession->expects($this->any()) - ->method('getId') - ->willReturn($lastCustomerId); - $this->customerSession->expects($this->any()) - ->method('unsBeforeAuthUrl') - ->willReturnSelf(); - $this->customerSession->expects($this->any()) - ->method('setLastCustomerId') - ->with($lastCustomerId) - ->willReturnSelf(); - - // Preparations for method prepareRedirectUrl() - $this->store->expects($this->once()) - ->method('getBaseUrl') - ->willReturn($baseUrl); - - $this->customerSession->expects($this->any()) - ->method('getBeforeAuthUrl') - ->willReturn($beforeAuthUrl); - $this->customerSession->expects($this->any()) - ->method('setBeforeAuthUrl') - ->willReturnSelf(); - $this->customerSession->expects($this->any()) - ->method('getAfterAuthUrl') - ->willReturn($afterAuthUrl); - $this->customerSession->expects($this->any()) - ->method('setAfterAuthUrl') - ->with($beforeAuthUrl) - ->willReturnSelf(); - - $this->customerUrl->expects($this->any()) - ->method('getAccountUrl') - ->willReturn($accountUrl); - $this->customerUrl->expects($this->any()) - ->method('getLoginUrl') - ->willReturn($loginUrl); - $this->customerUrl->expects($this->any()) - ->method('getLogoutUrl') - ->willReturn($logoutUrl); - $this->customerUrl->expects($this->any()) - ->method('DashboardUrl') - ->willReturn($dashboardUrl); - - $this->scopeConfig->expects($this->any()) - ->method('isSetFlag') - ->with(CustomerUrl::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD, ScopeInterface::SCOPE_STORE) - ->willReturn($redirectToDashboard); - - $this->request->expects($this->any()) - ->method('getParam') - ->with(CustomerUrl::REFERER_QUERY_PARAM_NAME) - ->willReturn($referer); - - $this->urlDecoder->expects($this->any()) - ->method('decode') - ->with($referer) - ->willReturn($referer); - - $this->url->expects($this->any()) - ->method('isOwnOriginUrl') - ->willReturn(true); - - $this->resultRedirect->expects($this->once()) - ->method('setUrl') - ->willReturnSelf(); - - $this->model->getRedirect(); - } - - /** - * @return array - */ - public function getRedirectDataProvider() - { - /** - * Customer ID - * Last customer ID - * Referer - * Base URL - * BeforeAuth URL - * AfterAuth URL - * Account URL - * Login URL - * Logout URL - * Dashboard URL - * Is customer logged in flag - * Redirect to Dashboard flag - */ - return [ - // Loggend In, Redirect by Referer - [1, 2, 'referer', 'base', '', '', 'account', '', '', '', true, false], - // Loggend In, Redirect by AfterAuthUrl - [1, 2, 'referer', 'base', '', 'defined', 'account', '', '', '', true, true], - // Not logged In, Redirect by LoginUrl - [1, 2, 'referer', 'base', '', '', 'account', 'login', '', '', false, true], - // Logout, Redirect to Dashboard - [1, 2, 'referer', 'base', 'logout', '', 'account', 'login', 'logout', 'dashboard', false, true], - // Default redirect - [1, 2, 'referer', 'base', 'defined', '', 'account', 'login', 'logout', 'dashboard', true, true], - ]; - } -} diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php index f38c4e385e4ce..8f465e8617922 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderTest.php @@ -17,7 +17,7 @@ /** * Class DataProviderTest * - * Test for class \Magento\Customer\Model\Customer\DataProvider + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class DataProviderTest extends \PHPUnit_Framework_TestCase { @@ -56,26 +56,26 @@ class DataProviderTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - $this->eavConfigMock = $this->getMockBuilder('Magento\Eav\Model\Config') + $this->eavConfigMock = $this->getMockBuilder(\Magento\Eav\Model\Config::class) ->disableOriginalConstructor() ->getMock(); $this->customerCollectionFactoryMock = $this->getMock( - 'Magento\Customer\Model\ResourceModel\Customer\CollectionFactory', + \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory::class, ['create'], [], '', false ); $this->eavValidationRulesMock = $this - ->getMockBuilder('Magento\Ui\DataProvider\EavValidationRules') + ->getMockBuilder(\Magento\Ui\DataProvider\EavValidationRules::class) ->disableOriginalConstructor() ->getMock(); - $this->fileProcessor = $this->getMockBuilder('Magento\Customer\Model\FileProcessor') + $this->fileProcessor = $this->getMockBuilder(\Magento\Customer\Model\FileProcessor::class) ->disableOriginalConstructor() ->getMock(); - $this->fileProcessorFactory = $this->getMockBuilder('Magento\Customer\Model\FileProcessorFactory') + $this->fileProcessorFactory = $this->getMockBuilder(\Magento\Customer\Model\FileProcessorFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -159,7 +159,7 @@ public function getAttributesMetaDataProvider() */ protected function getCustomerCollectionFactoryMock() { - $collectionMock = $this->getMockBuilder('Magento\Customer\Model\ResourceModel\Customer\Collection') + $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -196,7 +196,7 @@ protected function getEavConfigMock() */ protected function getTypeCustomerMock() { - $typeCustomerMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $typeCustomerMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); @@ -212,7 +212,7 @@ protected function getTypeCustomerMock() */ protected function getTypeAddressMock() { - $typeAddressMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $typeAddressMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); @@ -228,11 +228,11 @@ protected function getTypeAddressMock() */ protected function getAttributeMock() { - $attributeMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Attribute\AbstractAttribute') + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) ->setMethods(['getAttributeCode', 'getDataUsingMethod', 'usesSource', 'getSource']) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $sourceMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Attribute\Source\AbstractSource') + $sourceMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); @@ -267,13 +267,48 @@ function ($origName) { public function testGetData() { - $customer = $this->getMockBuilder('Magento\Customer\Model\Customer') + $customerId = 1; + $addressId = 2; + $customerData = [ + 'email' => 'test@test.ua', + 'default_billing' => $addressId, + 'default_shipping' => $addressId, + 'password_hash' => 'password_hash', + 'rp_token' => 'rp_token', + 'confirmation' => 'confirmation', + ]; + $customerDataFiltered = [ + 'email' => 'test@test.ua', + 'default_billing' => $addressId, + 'default_shipping' => $addressId + ]; + $addressData = [ + 'firstname' => 'firstname', + 'lastname' => 'lastname', + 'street' => "street\nstreet", + ]; + $expectedAddressData = [ + $addressId => [ + 'firstname' => 'firstname', + 'lastname' => 'lastname', + 'street' => [ + 'street', + 'street', + ], + 'default_billing' => $addressId, + 'default_shipping' => $addressId, + ] + ]; + $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) + ->disableOriginalConstructor() + ->getMock(); + $customer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) ->disableOriginalConstructor() ->getMock(); - $address = $this->getMockBuilder('Magento\Customer\Model\Address') + $address = $this->getMockBuilder(\Magento\Customer\Model\Address::class) ->disableOriginalConstructor() ->getMock(); - $collectionMock = $this->getMockBuilder('Magento\Customer\Model\ResourceModel\Customer\Collection') + $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) ->disableOriginalConstructor() ->getMock(); @@ -290,24 +325,23 @@ public function testGetData() ->willReturn([$customer]); $customer->expects($this->once()) ->method('getData') - ->willReturn([ - 'email' => 'test@test.ua', - 'default_billing' => 2, - 'default_shipping' => 2, - ]); + ->willReturn($customerData); $customer->expects($this->once()) ->method('getAddresses') ->willReturn([$address]); $customer->expects($this->once()) ->method('getAttributes') ->willReturn([]); + $customer->expects($this->once()) + ->method('getId') + ->willReturn($customerId); $address->expects($this->atLeastOnce()) ->method('getId') - ->willReturn(2); + ->willReturn($addressId); $address->expects($this->once()) ->method('load') - ->with(2) + ->with($addressId) ->willReturnSelf(); $address->expects($this->once()) ->method('getData') @@ -330,29 +364,18 @@ public function testGetData() $this->fileProcessorFactory ); + $result = $dataProvider->getData(); + $this->assertArrayHasKey($customerId, $result); + $this->assertArrayHasKey('customer', $result[$customerId]); + $this->assertArrayHasKey('address', $result[$customerId]); + // assert that filtered fields are removed from the customer $this->assertEquals( - [ - '' => [ - 'customer' => [ - 'email' => 'test@test.ua', - 'default_billing' => 2, - 'default_shipping' => 2, - ], - 'address' => [ - 2 => [ - 'firstname' => 'firstname', - 'lastname' => 'lastname', - 'street' => [ - 'street', - 'street', - ], - 'default_billing' => 2, - 'default_shipping' => 2, - ] - ] - ] - ], - $dataProvider->getData() + $customerDataFiltered, + $result[$customerId]['customer'] + ); + $this->assertEquals( + $expectedAddressData, + $result[$customerId]['address'] ); } @@ -378,7 +401,7 @@ public function testGetDataWithCustomAttributeImage() ], ]; - $attributeMock = $this->getMockBuilder('Magento\Customer\Model\Attribute') + $attributeMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) ->disableOriginalConstructor() ->getMock(); $attributeMock->expects($this->any()) @@ -388,14 +411,14 @@ public function testGetDataWithCustomAttributeImage() ->method('getAttributeCode') ->willReturn('img1'); - $entityTypeMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $entityTypeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); $entityTypeMock->expects($this->once()) ->method('getEntityTypeCode') ->willReturn(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER); - $customerMock = $this->getMockBuilder('Magento\Customer\Model\Customer') + $customerMock = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) ->disableOriginalConstructor() ->getMock(); $customerMock->expects($this->once()) @@ -417,7 +440,7 @@ public function testGetDataWithCustomAttributeImage() ->method('getEntityType') ->willReturn($entityTypeMock); - $collectionMock = $this->getMockBuilder('Magento\Customer\Model\ResourceModel\Customer\Collection') + $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) @@ -468,7 +491,7 @@ public function testGetDataWithCustomAttributeImageNoData() ], ]; - $attributeMock = $this->getMockBuilder('Magento\Customer\Model\Attribute') + $attributeMock = $this->getMockBuilder(\Magento\Customer\Model\Attribute::class) ->disableOriginalConstructor() ->getMock(); $attributeMock->expects($this->once()) @@ -478,11 +501,11 @@ public function testGetDataWithCustomAttributeImageNoData() ->method('getAttributeCode') ->willReturn('img1'); - $entityTypeMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $entityTypeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); - $customerMock = $this->getMockBuilder('Magento\Customer\Model\Customer') + $customerMock = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) ->disableOriginalConstructor() ->getMock(); $customerMock->expects($this->once()) @@ -503,7 +526,7 @@ public function testGetDataWithCustomAttributeImageNoData() ->method('getEntityType') ->willReturn($entityTypeMock); - $collectionMock = $this->getMockBuilder('Magento\Customer\Model\ResourceModel\Customer\Collection') + $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) @@ -516,7 +539,7 @@ public function testGetDataWithCustomAttributeImageNoData() $objectManager = new ObjectManager($this); $dataProvider = $objectManager->getObject( - '\Magento\Customer\Model\Customer\DataProvider', + \Magento\Customer\Model\Customer\DataProvider::class, [ 'name' => 'test-name', 'primaryFieldName' => 'primary-field-name', @@ -538,7 +561,7 @@ public function testGetAttributesMetaWithCustomAttributeImage() $allowedExtension = 'ext1 ext2'; $attributeCode = 'img1'; - $collectionMock = $this->getMockBuilder('Magento\Customer\Model\ResourceModel\Customer\Collection') + $collectionMock = $this->getMockBuilder(\Magento\Customer\Model\ResourceModel\Customer\Collection::class) ->disableOriginalConstructor() ->getMock(); $collectionMock->expects($this->once()) @@ -549,7 +572,7 @@ public function testGetAttributesMetaWithCustomAttributeImage() ->method('create') ->willReturn($collectionMock); - $attributeMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Attribute\AbstractAttribute') + $attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute\AbstractAttribute::class) ->setMethods([ 'getAttributeCode', 'getFrontendInput', @@ -571,7 +594,7 @@ function ($origName) { } ); - $typeCustomerMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $typeCustomerMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); $typeCustomerMock->expects($this->once()) @@ -581,7 +604,7 @@ function ($origName) { ->method('getEntityTypeCode') ->willReturn(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER); - $typeAddressMock = $this->getMockBuilder('Magento\Eav\Model\Entity\Type') + $typeAddressMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) ->disableOriginalConstructor() ->getMock(); $typeAddressMock->expects($this->once()) diff --git a/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php b/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php index 5dd73254554d6..d3de65ecb6104 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/FileProcessorTest.php @@ -44,10 +44,10 @@ class FileProcessorTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->mediaDirectory = $this->getMockBuilder('Magento\Framework\Filesystem\Directory\WriteInterface') + $this->mediaDirectory = $this->getMockBuilder(\Magento\Framework\Filesystem\Directory\WriteInterface::class) ->getMockForAbstractClass(); - $this->filesystem = $this->getMockBuilder('Magento\Framework\Filesystem') + $this->filesystem = $this->getMockBuilder(\Magento\Framework\Filesystem::class) ->disableOriginalConstructor() ->getMock(); $this->filesystem->expects($this->any()) @@ -55,15 +55,15 @@ protected function setUp() ->with(DirectoryList::MEDIA) ->willReturn($this->mediaDirectory); - $this->uploaderFactory = $this->getMockBuilder('Magento\MediaStorage\Model\File\UploaderFactory') + $this->uploaderFactory = $this->getMockBuilder(\Magento\MediaStorage\Model\File\UploaderFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->urlBuilder = $this->getMockBuilder('Magento\Framework\UrlInterface') + $this->urlBuilder = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) ->getMockForAbstractClass(); - $this->urlEncoder = $this->getMockBuilder('Magento\Framework\Url\EncoderInterface') + $this->urlEncoder = $this->getMockBuilder(\Magento\Framework\Url\EncoderInterface::class) ->getMockForAbstractClass(); $this->mime = $this->getMockBuilder(\Magento\Framework\File\Mime::class) @@ -188,10 +188,13 @@ public function testSaveTemporaryFile() $expectedResult = [ 'file' => 'filename.ext1', - 'path' => 'filepath', + ]; + $resultWithPath = [ + 'file' => 'filename.ext1', + 'path' => 'filepath' ]; - $uploaderMock = $this->getMockBuilder('Magento\MediaStorage\Model\File\Uploader') + $uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) ->disableOriginalConstructor() ->getMock(); $uploaderMock->expects($this->once()) @@ -213,7 +216,7 @@ public function testSaveTemporaryFile() $uploaderMock->expects($this->once()) ->method('save') ->with($absolutePath) - ->willReturn($expectedResult); + ->willReturn($resultWithPath); $this->uploaderFactory->expects($this->once()) ->method('create') @@ -246,7 +249,7 @@ public function testSaveTemporaryFileWithError() $absolutePath = '/absolute/filepath'; - $uploaderMock = $this->getMockBuilder('Magento\MediaStorage\Model\File\Uploader') + $uploaderMock = $this->getMockBuilder(\Magento\MediaStorage\Model\File\Uploader::class) ->disableOriginalConstructor() ->getMock(); $uploaderMock->expects($this->once()) diff --git a/app/code/Magento/Customer/composer.json b/app/code/Magento/Customer/composer.json index 3144d0340848b..b64b55b541856 100644 --- a/app/code/Magento/Customer/composer.json +++ b/app/code/Magento/Customer/composer.json @@ -29,7 +29,7 @@ "magento/module-customer-sample-data": "Sample Data version:100.0.*" }, "type": "magento2-module", - "version": "100.0.11", + "version": "100.0.13", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Customer/view/adminhtml/templates/sales/order/create/address/form/renderer/vat.phtml b/app/code/Magento/Customer/view/adminhtml/templates/sales/order/create/address/form/renderer/vat.phtml index ddf64a2fa60e6..fb7f8aa806891 100644 --- a/app/code/Magento/Customer/view/adminhtml/templates/sales/order/create/address/form/renderer/vat.phtml +++ b/app/code/Magento/Customer/view/adminhtml/templates/sales/order/create/address/form/renderer/vat.phtml @@ -6,8 +6,8 @@ // @codingStandardsIgnoreFile -?> -getElement(); $_note = $_element->getNote(); $_class = $_element->getFieldsetHtmlClass(); @@ -23,7 +23,7 @@ $_validateButton = $block->getValidateButton(); getElementHtml(); ?>
" id="note_getId(); ?>"> - + escapeHtml($_note); ?>
diff --git a/app/code/Magento/Customer/view/adminhtml/templates/system/config/validatevat.phtml b/app/code/Magento/Customer/view/adminhtml/templates/system/config/validatevat.phtml index 03b8a7ea738a4..011c1a05c464f 100644 --- a/app/code/Magento/Customer/view/adminhtml/templates/system/config/validatevat.phtml +++ b/app/code/Magento/Customer/view/adminhtml/templates/system/config/validatevat.phtml @@ -9,7 +9,7 @@ ?> diff --git a/app/code/Magento/Customer/view/frontend/templates/account/customer.phtml b/app/code/Magento/Customer/view/frontend/templates/account/customer.phtml index 54230d18a40c9..6052e2b8bac5f 100644 --- a/app/code/Magento/Customer/view/frontend/templates/account/customer.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/account/customer.phtml @@ -5,7 +5,7 @@ */ // @codingStandardsIgnoreFile - +/** @var Magento\Customer\Block\Account\Customer $block */ ?> customerLoggedIn()): ?>
  • @@ -21,7 +21,7 @@ class="action switch" tabindex="-1" data-action="customer-menu-toggle"> - + escapeHtml(__('Change')) ?> diff --git a/app/code/Magento/Customer/view/frontend/templates/newcustomer.phtml b/app/code/Magento/Customer/view/frontend/templates/newcustomer.phtml index 0bdef626b3df7..0ea7562583734 100644 --- a/app/code/Magento/Customer/view/frontend/templates/newcustomer.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/newcustomer.phtml @@ -11,19 +11,19 @@ /** * New Customer block template * - * @var $block \Magento\Customer\Block\Form\Login\Info + * @var \Magento\Customer\Block\Form\Login\Info $block */ ?> getRegistration()->isAllowed()): ?>
    - + escapeHtml(__('New Customers')) ?>
    -

    +

    escapeHtml(__('Creating an account has many benefits: check out faster, keep more than one address, track orders and more.')) ?>

    diff --git a/app/code/Magento/Customer/view/frontend/templates/widget/dob.phtml b/app/code/Magento/Customer/view/frontend/templates/widget/dob.phtml index 4ca581415c4a7..e7a3f03272ca2 100644 --- a/app/code/Magento/Customer/view/frontend/templates/widget/dob.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/widget/dob.phtml @@ -11,17 +11,21 @@ USAGE: Simple: -getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') - ->setDate($block->getCustomer()->getDob()) - ->toHtml() ?> +getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') + ->setDate($block->getCustomer()->getDob()) + ->toHtml() +?> For checkout/onepage/billing.phtml: -getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') +getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') ->setDate($block->getCustomer()->getDob()) ->setFieldIdFormat('billing:%s') ->setFieldNameFormat('billing[%s]') - ->toHtml() ?> + ->toHtml() +?> NOTE: Regarding styles - if we leave it this way, we'll move it to boxes.css Alternatively we could calculate widths automatically using block input parameters. @@ -35,12 +39,12 @@ NOTE: Regarding styles - if we leave it this way, we'll move it to boxes.css $fieldCssClass = 'field date field-' . $block->getHtmlId(); $fieldCssClass .= $block->isRequired() ? ' required' : ''; ?> -
    - +
    +
    getFieldHtml(); ?> getAdditionalDescription()) : ?> -
    +
    escapeHtml($_message); ?>
    diff --git a/app/code/Magento/Customer/view/frontend/templates/widget/gender.phtml b/app/code/Magento/Customer/view/frontend/templates/widget/gender.phtml index fedb604bcfd4f..dee20246f5fef 100644 --- a/app/code/Magento/Customer/view/frontend/templates/widget/gender.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/widget/gender.phtml @@ -6,15 +6,16 @@ // @codingStandardsIgnoreFile +/** @var \Magento\Customer\Block\Widget\Gender $block */ ?>
    - +
    - isRequired()):?> class="validate-select" data-validate="{required:true}"> getGenderOptions(); ?> getGender();?> - +
    diff --git a/app/code/Magento/Customer/view/frontend/templates/widget/name.phtml b/app/code/Magento/Customer/view/frontend/templates/widget/name.phtml index ed9283723e3b8..44bf777df59a3 100644 --- a/app/code/Magento/Customer/view/frontend/templates/widget/name.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/widget/name.phtml @@ -11,29 +11,33 @@ USAGE: Simple: -getLayout()->createBlock('Magento\Customer\Block\Widget\Name') - ->setObject($block->getAddress()) - ->toHtml() ?> +getLayout()->createBlock('Magento\Customer\Block\Widget\Name') + ->setObject($block->getAddress()) + ->toHtml() +?> For checkout/onepage/shipping.phtml: -getLayout()->createBlock('Magento\Customer\Block\Widget\Name') - ->setObject($block->getAddress()) - ->setFieldIdFormat('shipping:%s') - ->setFieldNameFormat('shipping[%s]') - ->setFieldParams('onchange="shipping.setSameAsBilling(false);"') - ->toHtml() ?> +getLayout()->createBlock('Magento\Customer\Block\Widget\Name') + ->setObject($block->getAddress()) + ->setFieldIdFormat('shipping:%s') + ->setFieldNameFormat('shipping[%s]') + ->setFieldParams('onchange="shipping.setSameAsBilling(false);"') + ->toHtml() +?> */ -/* @var $block \Magento\Customer\Block\Widget\Name */ +/* @var \Magento\Customer\Block\Widget\Name $block */ $prefix = $block->showPrefix(); $middle = $block->showMiddlename(); $suffix = $block->showSuffix(); ?> getNoWrap()): ?> -
    -
  • "];if(_25!==true&&n.nextSibling&&n.nextSibling.ui.getEl()){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(),buf.join(""));}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",_27,buf.join(""));}this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.childNodes;this.indentNode=cs[0];this.ecNode=cs[1];this.iconNode=cs[2];this.anchor=cs[3];this.textNode=cs[3].firstChild;if(a.qtip){if(this.textNode.setAttributeNS){this.textNode.setAttributeNS("ext","qtip",a.qtip);if(a.qtipTitle){this.textNode.setAttributeNS("ext","qtitle",a.qtipTitle);}}else{this.textNode.setAttribute("ext:qtip",a.qtip);if(a.qtipTitle){this.textNode.setAttribute("ext:qtitle",a.qtipTitle);}}}this.initEvents();if(!this.node.expanded){this.updateExpandIcon();}}else{if(_25===true){_27.appendChild(this.wrap);}}},getAnchor:function(){return this.anchor;},getTextEl:function(){return this.textNode;},getIconEl:function(){return this.iconNode;},updateExpandIcon:function(){if(this.rendered){var n=this.node,c1,c2;var cls=n.isLast()?"x-tree-elbow-end":"x-tree-elbow";var _2f=n.hasChildNodes();if(_2f){if(n.expanded){cls+="-minus";c1="x-tree-node-collapsed";c2="x-tree-node-expanded";}else{cls+="-plus";c1="x-tree-node-expanded";c2="x-tree-node-collapsed";}if(this.wasLeaf){this.removeClass("x-tree-node-leaf");this.wasLeaf=false;}if(this.c1!=c1||this.c2!=c2){Ext.fly(this.elNode).replaceClass(c1,c2);this.c1=c1;this.c2=c2;}}else{if(!this.wasLeaf){Ext.fly(this.elNode).replaceClass("x-tree-node-expanded","x-tree-node-leaf");this.wasLeaf=true;}}var ecc="x-tree-ec-icon "+cls;if(this.ecc!=ecc){this.ecNode.className=ecc;this.ecc=ecc;}}},getChildIndent:function(){if(!this.childIndent){var buf=[];var p=this.node;while(p){if(!p.isRoot||(p.isRoot&&p.ownerTree.rootVisible)){if(!p.isLast()){buf.unshift("");}else{buf.unshift("");}}p=p.parentNode;}this.childIndent=buf.join("");}return this.childIndent;},renderIndent:function(){if(this.rendered){var _33="";var p=this.node.parentNode;if(p){_33=p.ui.getChildIndent();}if(this.indentMarkup!=_33){this.indentNode.innerHTML=_33;this.indentMarkup=_33;}this.updateExpandIcon();}}};Ext.tree.RootTreeNodeUI=function(){Ext.tree.RootTreeNodeUI.superclass.constructor.apply(this,arguments);};Ext.extend(Ext.tree.RootTreeNodeUI,Ext.tree.TreeNodeUI,{render:function(){if(!this.rendered){var _35=this.node.ownerTree.container.dom;this.node.expanded=true;_35.innerHTML="
    ";this.wrap=this.ctNode=_35.firstChild;}},collapse:function(){},expand:function(){}}); +Ext.tree.TreeNodeUI=function(_1){this.node=_1;this.rendered=false;this.animating=false;this.emptyIcon=Ext.BLANK_IMAGE_URL;};Ext.tree.TreeNodeUI.prototype={removeChild:function(_2){if(this.rendered){this.ctNode.removeChild(_2.ui.getEl());}},beforeLoad:function(){this.addClass("x-tree-node-loading");},afterLoad:function(){this.removeClass("x-tree-node-loading");},onTextChange:function(_3,_4,_5){if(this.rendered){this.textNode.textContent=_4;}},onDisableChange:function(_6,_7){this.disabled=_7;if(_7){this.addClass("x-tree-node-disabled");}else{this.removeClass("x-tree-node-disabled");}},onSelectedChange:function(_8){if(_8){this.focus();this.addClass("x-tree-selected");}else{this.removeClass("x-tree-selected");}},onMove:function(_9,_a,_b,_c,_d,_e){this.childIndent=null;if(this.rendered){var _f=_c.ui.getContainer();if(!_f){this.holder=document.createElement("div");this.holder.appendChild(this.wrap);return;}var _10=_e?_e.ui.getEl():null;if(_10){_f.insertBefore(this.wrap,_10);}else{_f.appendChild(this.wrap);}this.node.renderIndent(true);}},addClass:function(cls){if(this.elNode){Ext.fly(this.elNode).addClass(cls);}},removeClass:function(cls){if(this.elNode){Ext.fly(this.elNode).removeClass(cls);}},remove:function(){if(this.rendered){this.holder=document.createElement("div");this.holder.appendChild(this.wrap);}},fireEvent:function(){return this.node.fireEvent.apply(this.node,arguments);},initEvents:function(){this.node.on("move",this.onMove,this);var E=Ext.EventManager;var a=this.anchor;var el=Ext.fly(a);if(Ext.isOpera){el.setStyle("text-decoration","none");}el.on("click",this.onClick,this);el.on("dblclick",this.onDblClick,this);el.on("contextmenu",this.onContextMenu,this);var _16=Ext.fly(this.iconNode);_16.on("click",this.onClick,this);_16.on("dblclick",this.onDblClick,this);_16.on("contextmenu",this.onContextMenu,this);E.on(this.ecNode,"click",this.ecClick,this,true);if(this.node.disabled){this.addClass("x-tree-node-disabled");}if(this.node.hidden){this.addClass("x-tree-node-disabled");}var ot=this.node.getOwnerTree();var dd=ot.enableDD||ot.enableDrag||ot.enableDrop;if(dd&&(!this.node.isRoot||ot.rootVisible)){Ext.dd.Registry.register(this.elNode,{node:this.node,handles:[this.iconNode,this.textNode],isHandle:false});}},hide:function(){if(this.rendered){this.wrap.style.display="none";}},show:function(){if(this.rendered){this.wrap.style.display="";}},onContextMenu:function(e){e.preventDefault();this.focus();this.fireEvent("contextmenu",this.node,e);},onClick:function(e){if(this.dropping){return;}if(this.fireEvent("beforeclick",this.node,e)!==false){if(!this.disabled&&this.node.attributes.href){this.fireEvent("click",this.node,e);return;}e.preventDefault();if(this.disabled){return;}if(this.node.attributes.singleClickExpand&&!this.animating&&this.node.hasChildNodes()){this.node.toggle();}this.fireEvent("click",this.node,e);}else{e.stopEvent();}},onDblClick:function(e){e.preventDefault();if(this.disabled){return;}if(!this.animating&&this.node.hasChildNodes()){this.node.toggle();}this.fireEvent("dblclick",this.node,e);},ecClick:function(e){if(!this.animating&&this.node.hasChildNodes()){this.node.toggle();}},startDrop:function(){this.dropping=true;},endDrop:function(){setTimeout(function(){this.dropping=false;}.createDelegate(this),50);},expand:function(){this.updateExpandIcon();this.ctNode.style.display="";},focus:function(){if(!this.node.preventHScroll){try{this.anchor.focus();}catch(e){}}else{if(!Ext.isIE){try{var _1d=this.node.getOwnerTree().el.dom;var l=_1d.scrollLeft;this.anchor.focus();_1d.scrollLeft=l;}catch(e){}}}},blur:function(){try{this.anchor.blur();}catch(e){}},animExpand:function(_1f){var ct=Ext.get(this.ctNode);ct.stopFx();if(!this.node.hasChildNodes()){this.updateExpandIcon();this.ctNode.style.display="";Ext.callback(_1f);return;}this.animating=true;this.updateExpandIcon();ct.slideIn("t",{callback:function(){this.animating=false;Ext.callback(_1f);},scope:this,duration:this.node.ownerTree.duration||0.25});},highlight:function(){var _21=this.node.getOwnerTree();Ext.fly(this.wrap).highlight(_21.hlColor||"C3DAF9",{endColor:_21.hlBaseColor});},collapse:function(){this.updateExpandIcon();this.ctNode.style.display="none";},animCollapse:function(_22){var ct=Ext.get(this.ctNode);ct.enableDisplayMode("block");ct.stopFx();this.animating=true;this.updateExpandIcon();ct.slideOut("t",{callback:function(){this.animating=false;Ext.callback(_22);},scope:this,duration:this.node.ownerTree.duration||0.25});},getContainer:function(){return this.ctNode;},getEl:function(){return this.wrap;},appendDDGhost:function(_24){_24.appendChild(this.elNode.cloneNode(true));},getDDRepairXY:function(){return Ext.lib.Dom.getXY(this.iconNode);},onRender:function(){this.render();},render:function(_25){var n=this.node;var _27=n.parentNode?n.parentNode.ui.getContainer():n.ownerTree.container.dom;if(!this.rendered){this.rendered=true;var a=n.attributes;this.indentMarkup="";if(n.parentNode){this.indentMarkup=n.parentNode.ui.getChildIndent();}var buf=["
  • ","",this.indentMarkup,"","","","","
    ","
      ","
    • "];if(_25!==true&&n.nextSibling&&n.nextSibling.ui.getEl()){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(),buf.join(""));}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",_27,buf.join(""));}this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.childNodes;this.indentNode=cs[0];this.ecNode=cs[1];this.iconNode=cs[2];this.anchor=cs[3];this.textNode=cs[3].firstChild;this.textNode.textContent=n.text;if(a.qtip){if(this.textNode.setAttributeNS){this.textNode.setAttributeNS("ext","qtip",a.qtip);if(a.qtipTitle){this.textNode.setAttributeNS("ext","qtitle",a.qtipTitle);}}else{this.textNode.setAttribute("ext:qtip",a.qtip);if(a.qtipTitle){this.textNode.setAttribute("ext:qtitle",a.qtipTitle);}}}this.initEvents();if(!this.node.expanded){this.updateExpandIcon();}}else{if(_25===true){_27.appendChild(this.wrap);}}},getAnchor:function(){return this.anchor;},getTextEl:function(){return this.textNode;},getIconEl:function(){return this.iconNode;},updateExpandIcon:function(){if(this.rendered){var n=this.node,c1,c2;var cls=n.isLast()?"x-tree-elbow-end":"x-tree-elbow";var _2f=n.hasChildNodes();if(_2f){if(n.expanded){cls+="-minus";c1="x-tree-node-collapsed";c2="x-tree-node-expanded";}else{cls+="-plus";c1="x-tree-node-expanded";c2="x-tree-node-collapsed";}if(this.wasLeaf){this.removeClass("x-tree-node-leaf");this.wasLeaf=false;}if(this.c1!=c1||this.c2!=c2){Ext.fly(this.elNode).replaceClass(c1,c2);this.c1=c1;this.c2=c2;}}else{if(!this.wasLeaf){Ext.fly(this.elNode).replaceClass("x-tree-node-expanded","x-tree-node-leaf");this.wasLeaf=true;}}var ecc="x-tree-ec-icon "+cls;if(this.ecc!=ecc){this.ecNode.className=ecc;this.ecc=ecc;}}},getChildIndent:function(){if(!this.childIndent){var buf=[];var p=this.node;while(p){if(!p.isRoot||(p.isRoot&&p.ownerTree.rootVisible)){if(!p.isLast()){buf.unshift("");}else{buf.unshift("");}}p=p.parentNode;}this.childIndent=buf.join("");}return this.childIndent;},renderIndent:function(){if(this.rendered){var _33="";var p=this.node.parentNode;if(p){_33=p.ui.getChildIndent();}if(this.indentMarkup!=_33){this.indentNode.innerHTML=_33;this.indentMarkup=_33;}this.updateExpandIcon();}}};Ext.tree.RootTreeNodeUI=function(){Ext.tree.RootTreeNodeUI.superclass.constructor.apply(this,arguments);};Ext.extend(Ext.tree.RootTreeNodeUI,Ext.tree.TreeNodeUI,{render:function(){if(!this.rendered){var _35=this.node.ownerTree.container.dom;this.node.expanded=true;_35.innerHTML="
      ";this.wrap=this.ctNode=_35.firstChild;}},collapse:function(){},expand:function(){}}); diff --git a/lib/web/jquery.js b/lib/web/jquery.js index 3c88fa8b7fd3f..e845f7db2ae57 100644 --- a/lib/web/jquery.js +++ b/lib/web/jquery.js @@ -1,27 +1,27 @@ /*! - * jQuery JavaScript Library v1.11.0 + * jQuery JavaScript Library v1.12.4 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * - * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2014-01-23T21:02Z + * Date: 2016-05-20T17:17Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { - // For CommonJS and CommonJS-like environments where a proper window is present, - // execute the factory and get jQuery - // For environments that do not inherently posses a window with a document - // (such as Node.js), expose a jQuery-making factory as module.exports - // This accentuates the need for the creation of a real window + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info + // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { @@ -37,5824 +37,5976 @@ // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { -// Can't do this because several apps including ASP.NET trace +// Support: Firefox 18+ +// Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) -// Support: Firefox 18+ -// +//"use strict"; + var deletedIds = []; + + var document = window.document; -var deletedIds = []; + var slice = deletedIds.slice; -var slice = deletedIds.slice; + var concat = deletedIds.concat; -var concat = deletedIds.concat; + var push = deletedIds.push; -var push = deletedIds.push; + var indexOf = deletedIds.indexOf; -var indexOf = deletedIds.indexOf; + var class2type = {}; -var class2type = {}; + var toString = class2type.toString; -var toString = class2type.toString; + var hasOwn = class2type.hasOwnProperty; -var hasOwn = class2type.hasOwnProperty; + var support = {}; -var trim = "".trim; -var support = {}; + var + version = "1.12.4", + // Define a local copy of jQuery + jQuery = function( selector, context ) { -var - version = "1.11.0", + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, - // Define a local copy of jQuery - jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }, + // Support: Android<4.1, IE<9 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }; + jQuery.fn = jQuery.prototype = { -jQuery.fn = jQuery.prototype = { - // The current version of jQuery being used - jquery: version, + // The current version of jQuery being used + jquery: version, - constructor: jQuery, + constructor: jQuery, - // Start with an empty selector - selector: "", + // Start with an empty selector + selector: "", - // The default length of a jQuery object is 0 - length: 0, + // The default length of a jQuery object is 0 + length: 0, - toArray: function() { - return slice.call( this ); - }, + toArray: function() { + return slice.call( this ); + }, - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num != null ? + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? - // Return a 'clean' array - ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : - // Return just the object - slice.call( this ); - }, + // Return all the elements in a clean array + slice.call( this ); + }, - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: deletedIds.sort, - splice: deletedIds.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var src, copyIsArray, copy, name, options, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } + // Return the newly-formed element set + return ret; + }, - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, - // extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, - // Prevent never-ending loop - if ( target === copy ) { - continue; - } + first: function() { + return this.eq( 0 ); + }, - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; + last: function() { + return this.eq( -1 ); + }, - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice + }; + + jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; } - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } } } } - } - - // Return the modified object - return target; -}; -jQuery.extend({ - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + // Return the modified object + return target; + }; - // Assume jQuery is ready without the ready module - isReady: true, + jQuery.extend( { - error: function( msg ) { - throw new Error( msg ); - }, + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - noop: function() {}, + // Assume jQuery is ready without the ready module + isReady: true, - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, + error: function( msg ) { + throw new Error( msg ); + }, - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, + noop: function() {}, - isWindow: function( obj ) { - /* jshint eqeqeq: false */ - return obj != null && obj == obj.window; - }, + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, - isNumeric: function( obj ) { - // parseFloat NaNs numeric-cast false positives (null|true|false|"") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - return obj - parseFloat( obj ) >= 0; - }, + isArray: Array.isArray || function( obj ) { + return jQuery.type( obj ) === "array"; + }, - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, - isPlainObject: function( obj ) { - var key; + isNumeric: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + var realStringObj = obj && obj.toString(); + return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; + }, - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { return false; } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } + return true; + }, - // Support: IE<9 - // Handle iteration over inherited properties before own properties. - if ( support.ownLast ) { - for ( key in obj ) { - return hasOwn.call( obj, key ); - } - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - type: function( obj ) { - if ( obj == null ) { - return obj + ""; - } - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call(obj) ] || "object" : - typeof obj; - }, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && jQuery.trim( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); + isPlainObject: function( obj ) { + var key; - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } - if ( value === false ) { - break; - } + try { + + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call( obj, "constructor" ) && + !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); + } catch ( e ) { - if ( value === false ) { - break; - } + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( !support.ownFirst ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); } } - // A special, fast, case for the most common use of each - } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, - if ( value === false ) { + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } - } - return obj; - }, - - // Use native String.trim function wherever possible - trim: trim && !trim.call("\uFEFF\xA0") ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : + return obj; + }, - // Otherwise use our own trimming functionality - function( text ) { + // Support: Android<4.1, IE<9 + trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; - if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } } - } - return ret; - }, + return ret; + }, - inArray: function( elem, arr, i ) { - var len; + inArray: function( elem, arr, i ) { + var len; - if ( arr ) { - if ( indexOf ) { - return indexOf.call( arr, elem, i ); - } + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } - len = arr.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in arr && arr[ i ] === elem ) { - return i; + for ( ; i < len; i++ ) { + + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } } } - } - return -1; - }, - - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; + return -1; + }, - while ( j < len ) { - first[ i++ ] = second[ j++ ]; - } + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; - // Support: IE<9 - // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) - if ( len !== len ) { - while ( second[j] !== undefined ) { + while ( j < len ) { first[ i++ ] = second[ j++ ]; } - } - first.length = i; + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[ j ] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; - return first; - }, + return first; + }, - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } } - } - return matches; - }, + return matches; + }, - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, - i = 0, - length = elems.length, - isArray = isArraylike( elems ), - ret = []; + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; - // Go through the array, translating each of the items to their new values - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); - if ( value != null ) { - ret.push( value ); + if ( value != null ) { + ret.push( value ); + } } - } - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); - if ( value != null ) { - ret.push( value ); + if ( value != null ) { + ret.push( value ); + } } } - } - - // Flatten any nested arrays - return concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var args, proxy, tmp; + // Flatten any nested arrays + return concat.apply( [], ret ); + }, - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } + // A global GUID counter for objects + guid: 1, - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; - // Simulated bind - args = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); - }; + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } - return proxy; - }, + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; - now: function() { - return +( new Date() ); - }, + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -}); + return proxy; + }, -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); + now: function() { + return +( new Date() ); + }, -function isArraylike( obj ) { - var length = obj.length, - type = jQuery.type( obj ); + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support + } ); - if ( type === "function" || jQuery.isWindow( obj ) ) { - return false; +// JSHint would error on this code due to the Symbol not being defined in ES5. +// Defining this global in .jshintrc would create a danger of using the global +// unguarded in another place, it seems safer to just disable JSHint for these +// three lines. + /* jshint ignore: start */ + if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ]; } + /* jshint ignore: end */ - if ( obj.nodeType === 1 && length ) { - return true; - } +// Populate the class2type map + jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), + function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v1.10.16 - * http://sizzlejs.com/ - * - * Copyright 2013 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2014-01-13 - */ -(function( window ) { - -var i, - support, - Expr, - getText, - isXML, - compile, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + -(new Date()), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { - var i = 0, - len = this.length; - for ( ; i < len; i++ ) { - if ( this[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + - "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - - // Prefer arguments quoted, - // then not containing pseudos/brackets, - // then attribute selectors/non-parenthetical expressions, - // then anything else - // These preferences are here to reduce the number of selectors - // needing tokenize in the PSEUDO preFilter - pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - rescape = /'|\\/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; + function isArrayLike( obj ) { -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : + // Support: iOS 8.2 (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; } - }; -} -function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; + } + var Sizzle = + /*! + * Sizzle CSS Selector Engine v2.2.1 + * http://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2015-10-17 + */ + (function( window ) { + + var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, - context = context || document; - results = results || []; + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, - if ( !selector || typeof selector !== "string" ) { - return results; - } + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; - if ( documentIsHTML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document (jQuery #6963) - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; - } - } +// Optimize for push.apply( _, NodeList ) + try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; + } catch ( e ) { + push = { apply: arr.length ? - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { - push.apply( results, context.getElementsByClassName( m ) ); - return results; + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; } - } - // QSA path - if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; + function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, nidselect, match, groups, newSelector, + newContext = context && context.ownerDocument, - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; + results = results || []; - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); - } - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; - newSelector = groups.join(","); - } + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); - } } - } - } - } - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { -/** - * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key + " " ] = value); - } - return cache; -} + // Element context + } else { -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result - */ -function assert( fn ) { - var div = document.createElement("div"); + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { - try { - return !!fn( div ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); - } - // release memory in IE - div = null; - } -} + results.push( elem ); + return results; + } + } -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split("|"), - i = attrs.length; + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; - while ( i-- ) { - Expr.attrHandle[ arr[i] ] = handler; - } -} + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - return a ? 1 : -1; -} + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", (nid = expando) ); + } -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; + while ( i-- ) { + groups[i] = nidselect + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== strundefined && context; -} + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } -// Expose support vars for convenience -support = Sizzle.support = {}; + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, - doc = node ? node.ownerDocument || node : preferredDoc, - parent = doc.defaultView; - - // If no document and documentElement is available, return - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); + } - // Set our document - document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsHTML = !isXML( doc ); - - // Support: IE>8 - // If iframe document is assigned to "document" variable and if iframe has been reloaded, - // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 - // IE6-8 do not support the defaultView property so parent will be undefined - if ( parent && parent !== parent.top ) { - // IE11 does not have attachEvent, so all must suffer - if ( parent.addEventListener ) { - parent.addEventListener( "unload", function() { - setDocument(); - }, false ); - } else if ( parent.attachEvent ) { - parent.attachEvent( "onunload", function() { - setDocument(); - }); - } - } + /** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ + function createCache() { + var keys = []; - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) - support.attributes = assert(function( div ) { - div.className = "i"; - return !div.getAttribute("className"); - }); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( div ) { - div.appendChild( doc.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Check if getElementsByClassName can be trusted - support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { - div.innerHTML = "
      "; - - // Support: Safari<4 - // Catch class over-caching - div.firstChild.className = "i"; - // Support: Opera<10 - // Catch gEBCN failure to find non-leading classes - return div.getElementsByClassName("i").length === 2; - }); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( div ) { - docElem.appendChild( div ).id = expando; - return !doc.getElementsByName || !doc.getElementsByName( expando ).length; - }); - - // ID find and filter - if ( support.getById ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && documentIsHTML ) { - var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - // Support: IE6/7 - // getElementById is not reliable as a find shortcut - delete Expr.find["ID"]; - - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { - return context.getElementsByTagName( tag ); + /** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ + function markFunction( fn ) { + fn[ expando ] = true; + return fn; } - } : - function( tag, context ) { - var elem, - tmp = [], - i = 0, - results = context.getElementsByTagName( tag ); - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); + /** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ + function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); } + // release memory in IE + div = null; } - - return tmp; } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ + /** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ + function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; - // QSA and matchesSelector support + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } + } - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; + /** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ + function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See http://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } - if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - div.innerHTML = ""; + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } - // Support: IE8, Opera 10-12 - // Nothing should be selected when empty strings follow ^= or $= or *= - if ( div.querySelectorAll("[t^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + return a ? 1 : -1; } - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + /** + * Returns a function to use in pseudos for input types + * @param {String} type + */ + function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; } - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); + /** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ + function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; } - }); - assert(function( div ) { - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = doc.createElement("input"); - input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "name", "D" ); + /** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ + function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( div.querySelectorAll("[name=d]").length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); } - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); + /** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ + function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; } - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } +// Expose support vars for convenience + support = Sizzle.support = {}; + + /** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ + isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; + }; - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully does not implement inclusive descendent - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; + /** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ + setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( (parent = document.defaultView) && parent.top !== parent ) { + // Support: IE 11 + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); } } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { + /* Attributes + ---------------------------------------------------------------------- */ - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } + /* getElement(s)By* + ---------------------------------------------------------------------- */ - // Calculate position if both inputs belong to the same document - compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }); - // Otherwise we know they are disconnected - 1; + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + }); - // Choose the first element that is related to our preferred document - if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { - return -1; - } - if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { - return 1; - } + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + return m ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } - // Maintain original order - return sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - } + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } + return tmp; + } + return results; + }; - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } - return doc; -}; + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); - if ( support.matchesSelector && documentIsHTML && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } - try { - var ret = matches.call( elem, expr ); + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch(e) {} - } + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } - return Sizzle( expr, document, null, [elem] ).length > 0; -}; + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); -Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null; -}; + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; + /* Sorting + ---------------------------------------------------------------------- */ -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : - return results; -}; + // Otherwise we know they are disconnected + 1; -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - while ( (node = elem[i++]) ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - return ret; -}; + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } -Expr = Sizzle.selectors = { + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } - // Can be adjusted by the user - cacheLength: 50, + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } - createPseudo: markFunction, + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } - match: matchExpr, + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } - attrHandle: {}, + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } - find: {}, + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); + return document; + }; - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); + }; - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } + Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } - return match.slice( 0, 4 ); - }, + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} } - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + return Sizzle( expr, document, null, [ elem ] ).length > 0; + }; - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } + Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); + }; - return match; - }, + Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } - "PSEUDO": function( match ) { - var excess, - unquoted = !match[5] && match[2]; + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; + }; - // Accept quoted arguments as-is - if ( match[3] && match[4] !== undefined ) { - match[2] = match[4]; + Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); + }; - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + /** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ + Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, + return results; + }; - filter: { + /** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ + getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; + return ret; + }; - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); - }); - }, + Expr = Sizzle.selectors = { - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); + // Can be adjusted by the user + cacheLength: 50, - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } + createPseudo: markFunction, - result += ""; + match: matchExpr, - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, + attrHandle: {}, - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; + find: {}, - return first === 1 && last === 0 ? + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); - function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); - if ( parent ) { + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); } - return true; + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); } - start = [ forward ? parent.firstChild : parent.lastChild ]; + return match; + }, - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; - while ( (node = ++nodeIndex && node && node[ dir ] || + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) - } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; } - if ( node === elem ) { - break; + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); } - } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); } - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; } - }; - }, + }, - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - return !results.pop(); - }; - }), + return matchIndexes; + }), - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } }; - }), - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), + Expr.pseudos["nth"] = Expr.pseudos["eq"]; - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, +// Add button/input type pseudos + for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); + } + for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); + } - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } +// Easy API for creating new setFilters + function setFilters() {} + setFilters.prototype = Expr.filters = Expr.pseudos; + Expr.setFilters = new setFilters(); - return elem.selected === true; - }, + tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && + soFar = selector; + groups = []; + preFilters = Expr.preFilter; - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); - }, + while ( soFar ) { - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), + matched = false; - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), + if ( !matched ) { + break; + } + } - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); + }; - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); + function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; } - return matchIndexes; - }) - } -}; - -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -function tokenize( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - soFar = selector; - groups = []; - preFilters = Expr.preFilter; + function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( (oldCache = uniqueCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; } - groups.push( (tokens = []) ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); + function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -} - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); + function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); } + return results; } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, outerCache, - newCache = [ dirruns, doneName ]; - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (oldCache = outerCache[ dir ]) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return (newCache[ 2 ] = oldCache[ 2 ]); - } else { - // Reuse newcache so results back-propagate to previous elements - outerCache[ dir ] = newCache; + function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; - // A match means we're done; a fail means we have to keep checking - if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { - return true; + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); } } } } - } - }; -} -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } + return newUnmatched; } - return true; - } : - matchers[0]; -} -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); + function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); } - } - } - } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, - return newUnmatched; -} + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, + // ...intermediate processing is necessary + [] : - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + // ...otherwise use results directly + results : + matcherIn; - // ...intermediate processing is necessary - [] : + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } - // ...otherwise use results directly - results : - matcherIn; + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); + seed[temp] = !(results[temp] = elem); + } + } } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } } - } + }); } - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } + function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), - len = elems.length; - - if ( outermost ) { - outermostContext = context !== document && context; - } - - // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { - results.push( elem ); - break; + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); } - } - if ( outermost ) { - dirruns = dirrunsUnique; + matchers.push( matcher ); } } - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } + return elementMatcher( matchers ); } - // Apply set filters to unmatched elements - matchedCount += i; - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } + function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } + if ( outermost ) { + outermostContext = context === document || context || outermost; } - } - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } - // Add matches to results - push.apply( results, setMatched ); + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } - Sizzle.uniqueSort( results ); - } - } + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } - return unmatched; - }; + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} + // Add matches to results + push.apply( results, setMatched ); -compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !group ) { - group = tokenize( selector ); - } - i = group.length; - while ( i-- ) { - cached = matcherFromTokens( group[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } + Sizzle.uniqueSort( results ); + } + } - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - } - return cached; -}; - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } -function select( selector, context, results, seed ) { - var i, tokens, token, type, find, - match = tokenize( selector ); + return unmatched; + }; - if ( !seed ) { - // Try to minimize operations if there is only one group - if ( match.length === 1 ) { + return bySet ? + markFunction( superMatcher ) : + superMatcher; + } - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { + compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - } - selector = selector.slice( tokens.shift().value.length ); - } + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; + // Save selector and tokenization + cached.selector = selector; } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); + return cached; + }; + + /** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ + select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; } - break; + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } } } - } - } - } - // Compile and execute a filtering function - // Provide `match` to avoid retokenization if we modified the selector above - compile( selector, match )( - seed, - context, - !documentIsHTML, - results, - rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -} + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; + }; // One-time assignments // Sort stability -support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; -// Support: Chrome<14 +// Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; + support.detectDuplicates = !!hasDuplicate; // Initialize against the default document -setDocument(); + setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* -support.sortDetached = assert(function( div1 ) { - // Should return 1, but returns 4 (following) - return div1.compareDocumentPosition( document.createElement("div") ) & 1; -}); + support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; + }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert(function( div ) { - div.innerHTML = ""; - return div.firstChild.getAttribute("href") === "#" ; -}) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); -} + if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; + }) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); + } // Support: IE<9 // Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; -}) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); -} + if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; + }) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); + } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( div ) { - return div.getAttribute("disabled") == null; -}) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); -} + if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; + }) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); + } -return Sizzle; + return Sizzle; -})( window ); + })( window ); -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; + jQuery.find = Sizzle; + jQuery.expr = Sizzle.selectors; + jQuery.expr[ ":" ] = jQuery.expr.pseudos; + jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; + jQuery.text = Sizzle.getText; + jQuery.isXMLDoc = Sizzle.isXML; + jQuery.contains = Sizzle.contains; -var rneedsContext = jQuery.expr.match.needsContext; + var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; -var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; + }; + var siblings = function( n, elem ) { + var matched = []; -var risSimple = /^.[^:#\[\.,]*$/; + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - }); + return matched; + }; - } - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - }); + var rneedsContext = jQuery.expr.match.needsContext; - } + var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); + + + + var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not + function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + } ); - if ( typeof qualifier === "string" ) { - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); } - qualifier = jQuery.filter( qualifier, elements ); - } + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + + } - return jQuery.grep( elements, function( elem ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; - }); -} + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; + qualifier = jQuery.filter( qualifier, elements ); + } - if ( not ) { - expr = ":not(" + expr + ")"; + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not; + } ); } - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - })); -}; - -jQuery.fn.extend({ - find: function( selector ) { - var i, - ret = [], - self = this, - len = self.length; + jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); + if ( not ) { + expr = ":not(" + expr + ")"; } - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); + }; - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, - filter: function( selector ) { - return this.pushStack( winnow(this, selector || [], false) ); - }, - not: function( selector ) { - return this.pushStack( winnow(this, selector || [], true) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : + jQuery.fn.extend( { + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : selector || [], - false - ).length; - } -}); + false + ).length; + } + } ); // Initialize a jQuery object // A central reference to the root jQuery(document) -var rootjQuery, + var rootjQuery, - // Use the correct document accordingly with window argument (sandbox) - document = window.document, + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; - init = jQuery.fn.init = function( selector, context ) { - var match, elem; + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } + // init accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt( 0 ) === "<" && + selector.charAt( selector.length - 1 ) === ">" && + selector.length >= 3 ) { - } else { - match = rquickExpr.exec( selector ); - } + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; - // scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } } } - } - return this; + return this; - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[ 2 ] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[ 0 ] = elem; } - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; + this.context = document; + this.selector = selector; + return this; } - this.context = document; - this.selector = selector; - return this; - } + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[ 0 ] = selector; + this.length = 1; + return this; - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof root.ready !== "undefined" ? + root.ready( selector ) : - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return typeof rootjQuery.ready !== "undefined" ? - rootjQuery.ready( selector ) : - // Execute immediately if ready is not present - selector( jQuery ); - } + // Execute immediately if ready is not present + selector( jQuery ); + } - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } - return jQuery.makeArray( selector, this ); - }; + return jQuery.makeArray( selector, this ); + }; // Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; + init.prototype = jQuery.fn; // Initialize central reference -rootjQuery = jQuery( document ); + rootjQuery = jQuery( document ); -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; + var rparentsprev = /^(?:parents|prev(?:Until|All))/, -jQuery.extend({ - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, + jQuery.fn.extend( { + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, - sibling: function( n, elem ) { - var r = []; + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - return r; - } -}); + // Always skip document fragments + if ( cur.nodeType < 11 && ( pos ? + pos.index( cur ) > -1 : -jQuery.fn.extend({ - has: function( target ) { - var i, - targets = jQuery( target, this ), - len = targets.length; + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { - return this.filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; + matched.push( cur ); + break; + } } } - }); - }, - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, - for ( ; i < l; i++ ) { - for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { - // Always skip document fragments - if ( cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors)) ) { + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } - matched.push( cur ); - break; - } + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[ 0 ], jQuery( elem ) ); } - } - return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); - }, + // Locate the position of the desired element + return jQuery.inArray( - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem, this ); + }, - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; - } + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); } + } ); - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.unique( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, + function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } -}); - -function sibling( cur, dir ) { - do { - cur = cur[ dir ]; - } while ( cur && cur.nodeType !== 1 ); - - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.merge( [], elem.childNodes ); + return cur; } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - if ( name.slice( -5 ) !== "Until" ) { - selector = until; + jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); } + }, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } - if ( this.length > 1 ) { - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - ret = jQuery.unique( ret ); + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); } - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - ret = ret.reverse(); + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.uniqueSort( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } } - } - return this.pushStack( ret ); - }; -}); -var rnotwhite = (/\S+/g); + return this.pushStack( ret ); + }; + } ); + var rnotwhite = ( /\S+/g ); + + + +// Convert String-formatted options into Object-formatted ones + function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; + } + + /* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ + jQuery.Callbacks = function( options ) { + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + var // Flag to know if list is currently firing + firing, -// String to Object options format cache -var optionsCache = {}; + // Last fire value for non-forgettable lists + memory, -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} + // Flag to know if list was already fired + fired, -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // First callback to fire (used internally by add and fireWith) - firingStart, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; } } - return this; }, - // Remove a callback from the list - remove: function() { - if ( list ) { + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); + // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } + if ( index <= firingIndex ) { + firingIndex--; } } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( list && ( !fired || stack ) ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - + } ); + return this; + }, -jQuery.extend({ + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; }, - always: function() { - deferred.done( arguments ).fail( arguments ); + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; return this; }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); + disabled: function() { + return !list; }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - // Keep pipe for back-compat - promise.pipe = promise.then; + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = true; + if ( !memory ) { + self.disable(); + } + return this; + }, + locked: function() { + return !!locked; + }, - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } + return self; + }; - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - // Make the deferred a promise - promise.promise( deferred ); + jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], + [ "notify", "progress", jQuery.Callbacks( "memory" ) ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this === promise ? newDefer.promise() : this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } + // Keep pipe for back-compat + promise.pipe = promise.then; - // All done! - return deferred; - }, + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = slice.call( arguments ), - length = resolveValues.length, + // promise[ done | fail | progress ] = list.add + promise[ tuple[ 1 ] ] = list.add; - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + // Handle state + if ( stateString ) { + list.add( function() { - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + // state = [ resolved | rejected ] + state = stateString; - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( values === progressValues ) { - deferred.notifyWith( contexts, values ); + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } - } else if ( !(--remaining) ) { - deferred.resolveWith( contexts, values ); - } + // deferred[ resolve | reject | notify ] + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); + return this; }; - }, + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); - progressValues, progressContexts, resolveContexts; + // Make the deferred a promise + promise.promise( deferred ); - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); } - } - - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -}); + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || + ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. + // If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .progress( updateFunc( i, progressContexts, progressValues ) ) + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } + } ); // The deferred used on DOM ready -var readyList; + var readyList; -jQuery.fn.ready = function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); + jQuery.fn.ready = function( fn ) { - return this; -}; + // Add the callback + jQuery.ready.promise().done( fn ); -jQuery.extend({ - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, + return this; + }; - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, + jQuery.extend( { - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, - // Handle when the DOM is ready - ready: function( wait ) { + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready ); - } + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } - // Remember that the DOM is ready - jQuery.isReady = true; + // Remember that the DOM is ready + jQuery.isReady = true; - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } } + } ); - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); + /** + * Clean-up method for dom ready events + */ + function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger("ready").off("ready"); + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); } } -}); -/** - * Clean-up method for dom ready events - */ -function detach() { - if ( document.addEventListener ) { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); + /** + * The ready event handler and self cleanup method + */ + function completed() { - } else { - document.detachEvent( "onreadystatechange", completed ); - window.detachEvent( "onload", completed ); - } -} + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || + window.event.type === "load" || + document.readyState === "complete" ) { -/** - * The ready event handler and self cleanup method - */ -function completed() { - // readyState === "complete" is good enough for us to call the dom ready in oldIE - if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { - detach(); - jQuery.ready(); + detach(); + jQuery.ready(); + } } -} -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { + jQuery.ready.promise = function( obj ) { + if ( !readyList ) { - readyList = jQuery.Deferred(); + readyList = jQuery.Deferred(); - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); + // Catch cases where $(document).ready() is called + // after the browser event has already occurred. + // Support: IE6-10 + // Older IE sometimes signals "interactive" too soon + if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - // Standards-based browsers support DOMContentLoaded - } else if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { - // If IE event model is used - } else { - // Ensure firing before onload, maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", completed ); + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); - // A fallback to window.onload, that will always work - window.attachEvent( "onload", completed ); + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); - // If IE and not a frame - // continually check to see if the document is ready - var top = false; + // If IE event model is used + } else { - try { - top = window.frameElement == null && document.documentElement; - } catch(e) {} + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); - if ( top && top.doScroll ) { - (function doScrollCheck() { - if ( !jQuery.isReady ) { + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); - try { - // Use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - top.doScroll("left"); - } catch(e) { - return setTimeout( doScrollCheck, 50 ); - } + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch ( e ) {} - // detach all dom ready events - detach(); + if ( top && top.doScroll ) { + ( function doScrollCheck() { + if ( !jQuery.isReady ) { - // and execute any waiting functions - jQuery.ready(); - } - })(); + try { + + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll( "left" ); + } catch ( e ) { + return window.setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + } )(); + } } } - } - return readyList.promise( obj ); -}; + return readyList.promise( obj ); + }; +// Kick off the DOM ready check even if the user does not + jQuery.ready.promise(); -var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own -var i; -for ( i in jQuery( support ) ) { - break; -} -support.ownLast = i !== "0"; + var i; + for ( i in jQuery( support ) ) { + break; + } + support.ownFirst = i === "0"; // Note: most support tests are defined in their respective modules. // false until the test is run -support.inlineBlockNeedsLayout = false; + support.inlineBlockNeedsLayout = false; -jQuery(function() { - // We need to execute this one support test ASAP because we need to know - // if body.style.zoom needs to be set. +// Execute ASAP in case we need to set body.style.zoom + jQuery( function() { - var container, div, - body = document.getElementsByTagName("body")[0]; + // Minified: var a,b,c,d + var val, div, body, container; - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { - // Setup - container = document.createElement( "div" ); - container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + // Return for frameset docs that don't have a body + return; + } - div = document.createElement( "div" ); - body.appendChild( container ).appendChild( div ); + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); - if ( typeof div.style.zoom !== strundefined ) { - // Support: IE<8 - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - div.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1"; + if ( typeof div.style.zoom !== "undefined" ) { - if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) { - // Prevent IE 6 from affecting layout for positioned elements #11048 - // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 - body.style.zoom = 1; - } - } - - body.removeChild( container ); + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; - // Null elements to avoid leaks in IE - container = div = null; -}); + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + body.removeChild( container ); + } ); -(function() { - var div = document.createElement( "div" ); + ( function() { + var div = document.createElement( "div" ); - // Execute the test only if not already executed in another module. - if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; - } catch( e ) { + } catch ( e ) { support.deleteExpando = false; } - } - // Null elements to avoid leaks in IE. - div = null; -})(); + // Null elements to avoid leaks in IE. + div = null; + } )(); + var acceptData = function( elem ) { + var noData = jQuery.noData[ ( elem.nodeName + " " ).toLowerCase() ], + nodeType = +elem.nodeType || 1; + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : -/** - * Determines whether an object can have data - */ -jQuery.acceptData = function( elem ) { - var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], - nodeType = +elem.nodeType || 1; + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute( "classid" ) === noData; + }; - // Do not set data on non-element DOM nodes because it will not be cleared (#8335). - return nodeType !== 1 && nodeType !== 9 ? - false : - // Nodes accept data unless otherwise specified; rejection can be conditional - !noData || noData !== true && elem.getAttribute("classid") === noData; -}; -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /([A-Z])/g; + var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { + function dataAttr( elem, key, data ) { - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { - data = elem.getAttribute( name ); + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); + data = elem.getAttribute( name ); - } else { - data = undefined; - } - } + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : - return data; -} + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch ( e ) {} -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - var name; - for ( name in obj ) { + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; + } else { + data = undefined; + } } + + return data; } - return true; -} +// checks a cache object for emptiness + function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[ name ] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } -function internalData( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; + return true; } - var ret, thisCache, - internalKey = jQuery.expando, + function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !acceptData( elem ) ) { + return; + } - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, + var ret, thisCache, + internalKey = jQuery.expando, - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { - return; - } + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; - } else { - id = internalKey; + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( ( !id || !cache[ id ] || ( !pvt && !cache[ id ].data ) ) && + data === undefined && typeof name === "string" ) { + return; } - } - if ( !cache[ id ] ) { - // Avoid exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; - } + if ( !id ) { - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } } - } - thisCache = cache[ id ]; + if ( !cache[ id ] ) { - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( typeof name === "string" ) { + thisCache = cache[ id ]; - // First Try to find as-is property data - ret = thisCache[ name ]; + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } - // Test for null|undefined property data - if ( ret == null ) { + thisCache = thisCache.data; + } - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; } - } else { - ret = thisCache; - } - return ret; -} + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { -function internalRemoveData( elem, name, pvt ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } + // First Try to find as-is property data + ret = thisCache[ name ]; - var thisCache, i, - isNode = elem.nodeType, + // Test for null|undefined property data + if ( ret == null ) { - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; + return ret; } - if ( name ) { + function internalRemoveData( elem, name, pvt ) { + if ( !acceptData( elem ) ) { + return; + } - thisCache = pvt ? cache[ id ] : cache[ id ].data; + var thisCache, i, + isNode = elem.nodeType, - if ( thisCache ) { + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { + if ( name ) { - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { - name = name.split(" "); + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } } + } else { + + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } - } else { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = name.concat( jQuery.map( name, jQuery.camelCase ) ); - } - i = name.length; - while ( i-- ) { - delete thisCache[ name[i] ]; + i = name.length; + while ( i-- ) { + delete thisCache[ name[ i ] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject( thisCache ) : !jQuery.isEmptyObject( thisCache ) ) { + return; + } } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } - } - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject( cache[ id ] ) ) { - return; + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, undefined + } else { + cache[ id ] = undefined; } } - // Destroy the cache - if ( isNode ) { - jQuery.cleanData( [ elem ], true ); + jQuery.extend( { + cache: {}, - // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) - /* jshint eqeqeq: false */ - } else if ( support.deleteExpando || cache != cache.window ) { - /* jshint eqeqeq: true */ - delete cache[ id ]; + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, - // When all else fails, null - } else { - cache[ id ] = null; - } -} - -jQuery.extend({ - cache: {}, - - // The following elements (space-suffixed to avoid Object.prototype collisions) - // throw uncatchable exceptions if you attempt to set expando properties - noData: { - "applet ": true, - "embed ": true, - // ...but Flash objects (which have this classid) *can* handle expandos - "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data ) { - return internalData( elem, name, data ); - }, - - removeData: function( elem, name ) { - return internalRemoveData( elem, name ); - }, - - // For internal use only. - _data: function( elem, name, data ) { - return internalData( elem, name, data, true ); - }, - - _removeData: function( elem, name ) { - return internalRemoveData( elem, name, true ); - } -}); + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[ jQuery.expando ] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, -jQuery.fn.extend({ - data: function( key, value ) { - var i, name, data, - elem = this[0], - attrs = elem && elem.attributes; + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } + } ); - // Special expections of .data basically thwart jQuery.access, - // so implement the relevant behavior ourselves + jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - name = attrs[i].name; + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); - if ( name.indexOf("data-") === 0 ) { - name = jQuery.camelCase( name.slice(5) ); + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { - dataAttr( elem, name, data[ name ] ); + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } } + jQuery._data( elem, "parsedAttrs", true ); } - jQuery._data( elem, "parsedAttrs", true ); } + + return data; } - return data; - } + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + jQuery.data( this, key ); + } ); + } - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } + return arguments.length > 1 ? - return arguments.length > 1 ? + // Sets one value + this.each( function() { + jQuery.data( this, key, value ); + } ) : - // Sets one value - this.each(function() { - jQuery.data( this, key, value ); - }) : - - // Gets one value - // Try to fetch any internally stored data first - elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + removeData: function( key ) { + return this.each( function() { + jQuery.removeData( this, key ); + } ); + } + } ); -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = jQuery._data( elem, type ); + jQuery.extend( { + queue: function( elem, type, data ) { + var queue; - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray(data) ) { - queue = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = jQuery._data( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } } + return queue || []; } - return queue || []; - } - }, + }, - dequeue: function( elem, type ) { - type = type || "fx"; + dequeue: function( elem, type ) { + type = type || "fx"; - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { - if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); } - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, - if ( !startLength && hooks ) { - hooks.empty.fire(); + // not intended for public consumption - generates a queueHooks object, + // or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + } ) + } ); } - }, + } ); - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return jQuery._data( elem, key ) || jQuery._data( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - jQuery._removeData( elem, type + "queue" ); - jQuery._removeData( elem, key ); - }) - }); - } -}); + jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; - while ( i-- ) { - tmp = jQuery._data( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } } + resolve(); + return defer.promise( obj ); } - resolve(); - return defer.promise( obj ); - } -}); -var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + } ); -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; -var isHidden = function( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); - }; + ( function() { + var shrinkWrapBlocksVal; + support.shrinkWrapBlocks = function() { + if ( shrinkWrapBlocksVal != null ) { + return shrinkWrapBlocksVal; + } + // Will be changed later if needed. + shrinkWrapBlocksVal = false; -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - length = elems.length, - bulk = key == null; + // Minified: var b,c,d + var div, body, container; - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { - // Sets one value - } else if ( value !== undefined ) { - chainable = true; + // Test fired too early or in an unsupported environment, exit. + return; + } - if ( !jQuery.isFunction( value ) ) { - raw = true; - } + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; + // Support: IE6 + // Check if elements with layout shrink-wrap their children + if ( typeof div.style.zoom !== "undefined" ) { - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; + // Reset CSS: box-sizing; display; margin; border + div.style.cssText = + + // Support: Firefox<29, Android 2.3 + // Vendor-prefix box-sizing + "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + + "box-sizing:content-box;display:block;margin:0;border:0;" + + "padding:1px;width:1px;zoom:1"; + div.appendChild( document.createElement( "div" ) ).style.width = "5px"; + shrinkWrapBlocksVal = div.offsetWidth !== 3; } - } - if ( fn ) { - for ( ; i < length; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; -}; -var rcheckableType = (/^(?:checkbox|radio)$/i); - - - -(function() { - var fragment = document.createDocumentFragment(), - div = document.createElement("div"), - input = document.createElement("input"); - - // Setup - div.setAttribute( "className", "t" ); - div.innerHTML = "
      a"; - - // IE strips leading whitespace when .innerHTML is used - support.leadingWhitespace = div.firstChild.nodeType === 3; - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - support.tbody = !div.getElementsByTagName( "tbody" ).length; - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - support.html5Clone = - document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - input.type = "checkbox"; - input.checked = true; - fragment.appendChild( input ); - support.appendChecked = input.checked; - - // Make sure textarea (and checkbox) defaultValue is properly cloned - // Support: IE6-IE11+ - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - - // #11217 - WebKit loses check when the name is after the checked attribute - fragment.appendChild( div ); - div.innerHTML = ""; - - // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 - // old WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE<9 - // Opera does not clone events (and typeof div.attachEvent === undefined). - // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() - support.noCloneEvent = true; - if ( div.attachEvent ) { - div.attachEvent( "onclick", function() { - support.noCloneEvent = false; - }); - - div.cloneNode( true ).click(); - } + body.removeChild( container ); - // Execute the test only if not already executed in another module. - if (support.deleteExpando == null) { - // Support: IE<9 - support.deleteExpando = true; - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - } + return shrinkWrapBlocksVal; + }; - // Null elements to avoid leaks in IE. - fragment = div = input = null; -})(); + } )(); + var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); -(function() { - var i, eventName, - div = document.createElement( "div" ); - // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) - for ( i in { submit: true, change: true, focusin: true }) { - eventName = "on" + i; + var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - if ( !(support[ i + "Bubbles" ] = eventName in window) ) { - // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) - div.setAttribute( eventName, "t" ); - support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; - } - } + var isHidden = function( elem, el ) { - // Null elements to avoid leaks in IE. - div = null; -})(); + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || + !jQuery.contains( elem.ownerDocument, elem ); + }; -var rformElems = /^(?:input|select|textarea)$/i, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; -function returnTrue() { - return true; -} + function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { return tween.cur(); } : + function() { return jQuery.css( elem, prop, "" ); }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), -function returnFalse() { - return false; -} + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; - global: {}, + // Make sure we update the tween properties later on + valueParts = valueParts || []; - add: function( elem, types, handler, data, selector ) { - var tmp, events, t, handleObjIn, - special, eventHandle, handleObj, - handlers, type, namespaces, origType, - elemData = jQuery._data( elem ); + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } + do { - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); } - // Handle multiple events separated by a space - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; } + } + return adjusted; + } - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function + var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); + // Sets one value + } else if ( value !== undefined ) { + chainable = true; - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } + if ( !jQuery.isFunction( value ) ) { + raw = true; } - if ( special.add ) { - special.add.call( elem, handleObj ); + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; } } - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); + if ( fn ) { + for ( ; i < length; i++ ) { + fn( + elems[ i ], + key, + raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; } - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - var j, handleObj, tmp, - origCount, t, events, - special, handlers, type, - namespaces, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + return chainable ? + elems : - if ( !elemData || !(events = elemData.events) ) { - return; - } + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[ 0 ], key ) : emptyGet; + }; + var rcheckableType = ( /^(?:checkbox|radio)$/i ); - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); + var rtagName = ( /<([\w:-]+)/ ); - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } + var rscriptType = ( /^$|\/(?:java|ecma)script/i ); - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + var rleadingWhitespace = ( /^\s+/ ); - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; + var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" + + "details|dialog|figcaption|figure|footer|header|hgroup|main|" + + "mark|meter|nav|output|picture|progress|section|summary|template|time|video"; - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } + function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); - delete events[ type ]; + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); } } + return safeFrag; + } - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery._removeData( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - var handle, ontype, cur, - bubbleType, special, tmp, i, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - cur = tmp = elem = elem || document; + ( function() { + var div = document.createElement( "div" ), + fragment = document.createDocumentFragment(), + input = document.createElement( "input" ); - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } + // Setup + div.innerHTML = "
      a"; - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input = document.createElement( "input" ); + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } + div.appendChild( input ); - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + // Support: IE<9 + // Cloned elements keep attachEvent handlers, we use addEventListener on IE9+ + support.noCloneEvent = !!div.addEventListener; - event.type = i > 1 ? - bubbleType : - special.bindType || type; + // Support: IE<9 + // Since attributes and properties are the same in IE, + // cleanData must set properties to undefined rather than use removeAttribute + div[ jQuery.expando ] = 1; + support.attributes = !div.getAttribute( jQuery.expando ); + } )(); - // jQuery handler - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && jQuery.acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; +// We have to close these tags to support XHTML (#13200) + var wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
      ", "
      " ], + area: [ 1, "", "" ], - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { + // Support: IE8 + param: [ 1, "", "" ], + thead: [ 1, "", "
      " ], + tr: [ 2, "", "
      " ], + col: [ 2, "", "
      " ], + td: [ 3, "", "
      " ], - if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && - jQuery.acceptData( elem ) ) { + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
      ", "
      " ] + }; - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { +// Support: IE8-IE9 + wrapMap.optgroup = wrapMap.option; - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; + wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; + wrapMap.th = wrapMap.td; - if ( tmp ) { - elem[ ontype ] = null; - } - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - try { - elem[ type ](); - } catch ( e ) { - // IE<9 dies on focus/blur to hidden element (#1486,#12518) - // only reproducible on winXP IE8 native, not IE9 in IE8 mode - } - jQuery.event.triggered = undefined; + function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? + context.querySelectorAll( tag || "*" ) : + undefined; - if ( tmp ) { - elem[ ontype ] = tmp; - } + if ( !found ) { + for ( found = [], elems = context.childNodes || context; + ( elem = elems[ i ] ) != null; + i++ + ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); } } } - return event.result; - }, + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; + } - dispatch: function( event ) { - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); +// Mark scripts as having already been evaluated + function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; ( elem = elems[ i ] ) != null; i++ ) { + jQuery._data( + elem, + "globalEval", + !refElements || jQuery._data( refElements[ i ], "globalEval" ) + ); + } + } - var i, ret, handleObj, matched, j, - handlerQueue = [], - args = slice.call( arguments ), - handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; + var rhtml = /<|&#?\w+;/, + rtbody = / from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : - handlers: function( event, handlers ) { - var sel, handleObj, matches, i, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; + // String was a bare or + wrap[ 1 ] === "
      " && !rtbody.test( elem ) ? + tmp : + 0; - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( ( tbody = elem.childNodes[ j ] ), "tbody" ) && + !tbody.childNodes.length ) { - /* jshint eqeqeq: false */ - for ( ; cur != this; cur = cur.parentNode || this ) { - /* jshint eqeqeq: true */ - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); + elem.removeChild( tbody ); + } } } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; } } } - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); } - return handlerQueue; - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + continue; + } - event = new jQuery.Event( originalEvent ); + contains = jQuery.contains( elem.ownerDocument, elem ); - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); - // Support: IE<9 - // Fix target property (#1925) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } - // Support: Chrome 23+, Safari? - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } } - // Support: IE<9 - // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) - event.metaKey = !!event.metaKey; + tmp = null; + + return safe; + } - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + ( function() { + var i, eventName, + div = document.createElement( "div" ); - fixHooks: {}, + // Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events) + for ( i in { submit: true, change: true, focusin: true } ) { + eventName = "on" + i; - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { + if ( !( support[ i ] = eventName in window ) ) { - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i ] = div.attributes[ eventName ].expando === false; } - - return event; } - }, - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var body, eventDoc, doc, - button = original.button, - fromElement = original.fromElement; + // Null elements to avoid leaks in IE. + div = null; + } )(); - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } + var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } + function returnTrue() { + return true; + } - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } + function returnFalse() { + return false; + } - return event; - } - }, +// Support: IE9 +// See #13393 for more info + function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } + } - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - try { - this.focus(); - return false; - } catch ( e ) { - // Support: IE<9 - // If we error on focus to hidden element (#1486, #12518), - // let .trigger() run the handlers - } - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { - this.click(); - return false; - } - }, + function on( elem, types, selector, data, fn, one ) { + var origFn, type; - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); - } - }, + // Types can be a map of types/handlers + if ( typeof types === "object" ) { - beforeunload: { - postDispatch: function( event ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { - // Even when returnValue equals to undefined Firefox will still show alert - if ( event.result !== undefined ) { - event.originalEvent.returnValue = event.result; - } + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); } + return elem; } - }, - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true, - originalEvent: {} + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; } - } -}; -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } - } : - function( elem, type, handle ) { - var name = "on" + type; + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); + } + + /* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ + jQuery.event = { + + global: {}, - if ( elem.detachEvent ) { + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); - // #8545, #7054, preventing memory leaks for custom events in IE6-8 - // detachEvent needed property on element, by name of that event, to properly expose it to GC - if ( typeof elem[ name ] === strundefined ) { - elem[ name ] = null; + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; } - elem.detachEvent( name, handle ); - } - }; + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && ( - // Support: IE < 9 - src.returnValue === false || - // Support: Android < 4.0 - src.getPreventDefault && src.getPreventDefault() ) ? - returnTrue : - returnFalse; - - // Event type - } else { - this.type = src; - } + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && + ( !e || jQuery.event.triggered !== e.type ) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); + // Add elem as a property of the handle fn to prevent a memory leak + // with IE non-native events + eventHandle.elem = elem; + } - // Mark it as fixed - this[ jQuery.expando ] = true; -}; + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } - preventDefault: function() { - var e = this.originalEvent; + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; - this.isDefaultPrevented = returnTrue; - if ( !e ) { - return; - } + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; - // If preventDefault exists, run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; - // Support: IE - // Otherwise set the returnValue property of the original event to false - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - var e = this.originalEvent; + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } - this.isPropagationStopped = returnTrue; - if ( !e ) { - return; - } - // If stopPropagation exists, run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } + if ( special.add ) { + special.add.call( elem, handleObj ); - // Support: IE - // Set the cancelBubble property of the original event to true - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - } -}; + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; } - return ret; - } - }; -}); -// IE submit delegation -if ( !support.submitBubbles ) { + // Nullify elem to prevent memory leaks in IE + elem = null; + }, - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; } - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !jQuery._data( form, "submitBubbles" ) ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - jQuery._data( form, "submitBubbles", true ); + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; } - }); - // return undefined since we don't need an event listener - }, - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; } } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } }, - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; } - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } -// IE change delegation and checkbox/radio fix -if ( !support.changeBubbles ) { + if ( type.indexOf( "." ) > -1 ) { - jQuery.event.special.change = { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; - setup: function() { + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - } - // Allow triggered, simulated change events (#11500) - jQuery.event.simulate( "change", this, event, true ); - }); + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } - return false; } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && + jQuery._data( cur, "handle" ); + + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( + ( !special._default || + special._default.apply( eventPath.pop(), data ) === false + ) && acceptData( elem ) + ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; } - }); - jQuery._data( elem, "changeBubbles", true ); + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } } - }); + } + + return event.result; }, - handle: function( event ) { - var elem = event.target; + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; } - }, - teardown: function() { - jQuery.event.remove( this, "._change" ); + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - return !rformElems.test( this.nodeName ); - } - }; -} + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; -// Create "bubbling" focus and blur events -if ( !support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = jQuery._data( doc, fix ); + event.handleObj = handleObj; + event.data = handleObj.data; - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } } - jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = jQuery._data( doc, fix ) - 1; + } - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - jQuery._removeData( doc, fix ); - } else { - jQuery._data( doc, fix, attaches ); + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Support (at least): Chrome, IE9 + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // + // Support: Firefox<=42+ + // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) + if ( delegateCount && cur.nodeType && + ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push( { elem: cur, handlers: matches } ); + } + } } } - }; - }); -} -jQuery.fn.extend({ + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + } - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var type, origFn; + return handlerQueue; + }, - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; } - return this; - } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Safari 6-8+ + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -}); + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, - rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rtbody = /\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - option: [ 1, "" ], - legend: [ 1, "
      ", "
      " ], - area: [ 1, "", "" ], - param: [ 1, "", "" ], - thead: [ 1, "
      ", "
      " ], - tr: [ 2, "", "
      " ], - col: [ 2, "", "
      " ], - td: [ 3, "", "
      " ], + // Includes some event props shared by KeyEvent and MouseEvent + props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), - // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, - // unless wrapped in a div with non-breaking characters in front of it. - _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
      ", "
      " ] - }, - safeFragment = createSafeFragment( document ), - fragmentDiv = safeFragment.appendChild( document.createElement("div") ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -function getAll( context, tag ) { - var elems, elem, - i = 0, - found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : - typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : - undefined; - - if ( !found ) { - for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { - if ( !tag || jQuery.nodeName( elem, tag ) ) { - found.push( elem ); - } else { - jQuery.merge( found, getAll( elem, tag ) ); + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split( " " ), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; } - } - } + }, + + mouseHooks: { + props: ( "button buttons clientX clientY fromElement offsetX offsetY " + + "pageX pageY screenX screenY toElement" ).split( " " ), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - + ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - + ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? + original.toElement : + fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], found ) : - found; -} + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { -// Used in buildFragment, fixes the defaultChecked property -function fixDefaultChecked( elem ) { - if ( rcheckableType.test( elem.type ) ) { - elem.defaultChecked = elem.checked; - } -} + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { -// Support: IE<8 -// Manipulating tables requires a tbody -function manipulationTarget( elem, content ) { - return jQuery.nodeName( elem, "table" ) && - jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { - elem.getElementsByTagName("tbody")[0] || - elem.appendChild( elem.ownerDocument.createElement("tbody") ) : - elem; -} + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - if ( match ) { - elem.type = match[1]; - } else { - elem.removeAttribute("type"); - } - return elem; -} + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var elem, - i = 0; - for ( ; (elem = elems[i]) != null; i++ ) { - jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); - } -} + beforeunload: { + postDispatch: function( event ) { -function cloneCopyEvent( src, dest ) { + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, - if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { - return; - } + // Piggyback on a donor event to simulate a different one + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true - var type, i, l, - oldData = jQuery._data( src ), - curData = jQuery._data( dest, oldData ), - events = oldData.events; + // Previously, `originalEvent: {}` was set here, so stopPropagation call + // would not be triggered on donor event, since in our own + // jQuery.event.stopPropagation function we had a check for existence of + // originalEvent.stopPropagation method, so, consequently it would be a noop. + // + // Guard for simulated events was moved to jQuery.event.stopPropagation function + // since `originalEvent` should point to the original event for the + // constancy with other events and for more focused logic + } + ); - if ( events ) { - delete curData.handle; - curData.events = {}; + jQuery.event.trigger( e, null, elem ); - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); + if ( e.isDefaultPrevented() ) { + event.preventDefault(); } } - } + }; - // make the cloned public data object a copy from the original - if ( curData.data ) { - curData.data = jQuery.extend( {}, curData.data ); - } -} + jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; -function fixCloneNodeIssues( src, dest ) { - var nodeName, e, data; + if ( elem.detachEvent ) { - // We do not need to do anything for non-Elements - if ( dest.nodeType !== 1 ) { - return; - } + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, + // to properly expose it to GC + if ( typeof elem[ name ] === "undefined" ) { + elem[ name ] = null; + } - nodeName = dest.nodeName.toLowerCase(); + elem.detachEvent( name, handle ); + } + }; - // IE6-8 copies events bound via attachEvent when using cloneNode. - if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { - data = jQuery._data( dest ); + jQuery.Event = function( src, props ) { - for ( e in data.events ) { - jQuery.removeEvent( dest, e, data.handle ); + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); } - // Event data gets referenced instead of copied if the expando gets copied too - dest.removeAttribute( jQuery.expando ); - } + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; - // IE blanks contents when cloning scripts, and tries to evaluate newly-set text - if ( nodeName === "script" && dest.text !== src.text ) { - disableScript( dest ).text = src.text; - restoreScript( dest ); + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && - // IE6-10 improperly clones children of object elements using classid. - // IE10 throws NoModificationAllowedError if parent is null, #12132. - } else if ( nodeName === "object" ) { - if ( dest.parentNode ) { - dest.outerHTML = src.outerHTML; - } + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; - // This path appears unavoidable for IE9. When cloning an object - // element in IE9, the outerHTML strategy above is not sufficient. - // If the src has innerHTML and the destination does not, - // copy the src.innerHTML into the dest.innerHTML. #10324 - if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { - dest.innerHTML = src.innerHTML; + // Event type + } else { + this.type = src; } - } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - // IE6-8 fails to persist the checked state of a cloned checkbox - // or radio button. Worse, IE6-7 fail to give the cloned element - // a checked appearance if the defaultChecked value isn't also set + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } - dest.defaultChecked = dest.checked = src.checked; + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); - // IE6-7 get confused and end up setting the value of a cloned - // checkbox/radio button to an empty string instead of "on" - if ( dest.value !== src.value ) { - dest.value = src.value; - } + // Mark it as fixed + this[ jQuery.expando ] = true; + }; - // IE6-8 fails to return the selected option to the default selected - // state when cloning options - } else if ( nodeName === "option" ) { - dest.defaultSelected = dest.selected = src.defaultSelected; +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html + jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, - // IE6-8 fails to set the defaultValue to the correct value when - // cloning other types of input fields - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} + preventDefault: function() { + var e = this.originalEvent; -jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var destElements, node, clone, i, srcElements, - inPage = jQuery.contains( elem.ownerDocument, elem ); + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } - if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { - clone = elem.cloneNode( true ); + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); - // IE<=8 does not properly clone detached, unknown element nodes - } else { - fragmentDiv.innerHTML = elem.outerHTML; - fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); - } + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; - if ( (!support.noCloneEvent || !support.noCloneChecked) && - (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + this.isPropagationStopped = returnTrue; - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); + if ( !e || this.isSimulated ) { + return; + } - // Fix all IE cloning issues - for ( i = 0; (node = srcElements[i]) != null; ++i ) { - // Ensure that the destination node is not null; Fixes #9587 - if ( destElements[i] ) { - fixCloneNodeIssues( node, destElements[i] ); - } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); } - } - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; - for ( i = 0; (node = srcElements[i]) != null; i++ ) { - cloneCopyEvent( node, destElements[i] ); - } - } else { - cloneCopyEvent( elem, clone ); + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); } - } - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + this.stopPropagation(); } + }; - destElements = srcElements = node = null; +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://code.google.com/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). + jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" + }, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; + } ); - // Return the cloned set - return clone; - }, +// IE submit delegation + if ( !support.submit ) { - buildFragment: function( elems, context, scripts, selection ) { - var j, elem, contains, - tmp, tag, tbody, wrap, - l = elems.length, + jQuery.event.special.submit = { + setup: function() { - // Ensure a safe fragment - safe = createSafeFragment( context ), + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } - nodes = [], - i = 0; + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - for ( ; i < l; i++ ) { - elem = elems[ i ]; + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? - if ( elem || elem === 0 ) { + // Support: IE <=8 + // We use jQuery.prop instead of elem.form + // to allow fixing the IE8 delegated submit issue (gh-2332) + // by 3rd party polyfills/workarounds. + jQuery.prop( elem, "form" ) : + undefined; - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + if ( form && !jQuery._data( form, "submit" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submitBubble = true; + } ); + jQuery._data( form, "submit", true ); + } + } ); - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); + // return undefined since we don't need an event listener + }, - // Convert html into DOM nodes - } else { - tmp = tmp || safe.appendChild( context.createElement("div") ); + postDispatch: function( event ) { - // Deserialize a standard representation - tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; + // If form was submitted by the user, bubble the event up the tree + if ( event._submitBubble ) { + delete event._submitBubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event ); + } + } + }, - tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + teardown: function() { - // Descend through wrappers to the right content - j = wrap[0]; - while ( j-- ) { - tmp = tmp.lastChild; - } + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } - // Manually add leading whitespace removed by IE - if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { - nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); - } + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; + } - // Remove IE's autoinserted from table fragments - if ( !support.tbody ) { +// IE change delegation and checkbox/radio fix + if ( !support.change ) { - // String was a , *may* have spurious - elem = tag === "table" && !rtbody.test( elem ) ? - tmp.firstChild : + jQuery.event.special.change = { - // String was a bare or - wrap[1] === "
      " && !rtbody.test( elem ) ? - tmp : - 0; + setup: function() { - j = elem && elem.childNodes.length; - while ( j-- ) { - if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { - elem.removeChild( tbody ); + if ( rformElems.test( this.nodeName ) ) { + + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._justChanged = true; + } + } ); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._justChanged && !event.isTrigger ) { + this._justChanged = false; } - } - } - jQuery.merge( nodes, tmp.childNodes ); + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event ); + } ); + } + return false; + } - // Fix #12392 for WebKit and IE > 9 - tmp.textContent = ""; + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; - // Fix #12392 for oldIE - while ( tmp.firstChild ) { - tmp.removeChild( tmp.firstChild ); + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "change" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event ); + } + } ); + jQuery._data( elem, "change", true ); } + } ); + }, - // Remember the top-level container for proper cleanup - tmp = safe.lastChild; - } - } - } + handle: function( event ) { + var elem = event.target; - // Fix #11356: Clear elements from fragment - if ( tmp ) { - safe.removeChild( tmp ); - } + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || + ( elem.type !== "radio" && elem.type !== "checkbox" ) ) { - // Reset defaultChecked for any radios and checkboxes - // about to be appended to the DOM in IE 6/7 (#8060) - if ( !support.appendChecked ) { - jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); - } + return event.handleObj.handler.apply( this, arguments ); + } + }, - i = 0; - while ( (elem = nodes[ i++ ]) ) { + teardown: function() { + jQuery.event.remove( this, "._change" ); - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; + return !rformElems.test( this.nodeName ); } + }; + } - contains = jQuery.contains( elem.ownerDocument, elem ); +// Support: Firefox +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome, Safari +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 + if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; - // Append to fragment - tmp = getAll( safe.appendChild( elem ), "script" ); + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); } } - } - } - - tmp = null; + }; + } ); + } - return safe; - }, + jQuery.fn.extend( { - cleanData: function( elems, /* internal */ acceptData ) { - var elem, type, id, data, - i = 0, - internalKey = jQuery.expando, - cache = jQuery.cache, - deleteExpando = support.deleteExpando, - special = jQuery.event.special; + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { - for ( ; (elem = elems[i]) != null; i++ ) { - if ( acceptData || jQuery.acceptData( elem ) ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { - id = elem[ internalKey ]; - data = id && cache[ id ]; + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + }, - if ( data ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } + } ); - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - // Remove cache only if it was not already removed by jQuery.event.remove - if ( cache[ id ] ) { + var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ), + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, - delete cache[ id ]; + // Support: IE 10-11, Edge 10240+ + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) ); - } else if ( typeof elem.removeAttribute !== strundefined ) { - elem.removeAttribute( internalKey ); +// Support: IE<8 +// Manipulating tables requires a tbody + function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? - } else { - elem[ internalKey ] = null; - } + elem.getElementsByTagName( "tbody" )[ 0 ] || + elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : + elem; + } - deletedIds.push( id ); - } - } - } +// Replace/restore the type attribute of script elements for safe DOM manipulation + function disableScript( elem ) { + elem.type = ( jQuery.find.attr( elem, "type" ) !== null ) + "/" + elem.type; + return elem; + } + function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); } + return elem; } -}); - -jQuery.fn.extend({ - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); - }, null, value, arguments.length ); - }, - - append: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - remove: function( selector, keepData /* Internal Use Only */ ) { - var elem, - elems = selector ? jQuery.filter( selector, this ) : this, - i = 0; - - for ( ; (elem = elems[i]) != null; i++ ) { - - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } + function cloneCopyEvent( src, dest ) { + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; } - return this; - }, - - empty: function() { - var elem, - i = 0; + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; - for ( ; (elem = this[i]) != null; i++ ) { - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - } + if ( events ) { + delete curData.handle; + curData.events = {}; - // Remove any remaining nodes - while ( elem.firstChild ) { - elem.removeChild( elem.firstChild ); + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } } + } - // If this is a select, ensure that it displays empty (#12336) - // Support: IE<9 - if ( elem.options && jQuery.nodeName( elem, "select" ) ) { - elem.options.length = 0; - } + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); } + } - return this; - }, + function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } - return this.map(function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, + nodeName = dest.nodeName.toLowerCase(); - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); - if ( value === undefined ) { - return elem.nodeType === 1 ? - elem.innerHTML.replace( rinlinejQuery, "" ) : - undefined; + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); } - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - ( support.htmlSerialize || !rnoshimcache.test( value ) ) && - ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && - !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1>" ); - - try { - for (; i < l; i++ ) { - // Remove element nodes and prevent memory leaks - elem = this[i] || {}; - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } - elem = 0; + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); - // If using innerHTML throws an exception, use the fallback method - } catch(e) {} + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; } - if ( elem ) { - this.empty().append( value ); + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) ) { + dest.innerHTML = src.innerHTML; } - }, null, value, arguments.length ); - }, - replaceWith: function() { - var arg = arguments[ 0 ]; + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - // Make the changes, replacing each context element with the new content - this.domManip( arguments, function( elem ) { - arg = this.parentNode; + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set - jQuery.cleanData( getAll( this ) ); + dest.defaultChecked = dest.checked = src.checked; - if ( arg ) { - arg.replaceChild( elem, this ); + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; } - }); - // Force removal if there was no new content (e.g., from empty arguments) - return arg && (arg.length || arg.nodeType) ? this : this.remove(); - }, + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; - detach: function( selector ) { - return this.remove( selector, true ); - }, + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } + } - domManip: function( args, callback ) { + function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); @@ -5862,38 +6014,39 @@ jQuery.fn.extend({ var first, node, hasScripts, scripts, doc, fragment, i = 0, - l = this.length, - set = this, + l = collection.length, iNoClone = l - 1, - value = args[0], + value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); if ( isFunction ) { - args[0] = value.call( this, index, self.html() ); + args[ 0 ] = value.call( this, index, self.html() ); } - self.domManip( args, callback ); - }); + domManip( self, args, callback, ignored ); + } ); } if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } - if ( first ) { + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; - // Use the original fragment for the last item instead of the first because it can end up + // Use the original fragment for the last item + // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; @@ -5903,11 +6056,14 @@ jQuery.fn.extend({ // Keep references to cloned scripts for later restoration if ( hasScripts ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } - callback.call( this[i], node, i ); + callback.call( collection[ i ], node, i ); } if ( hasScripts ) { @@ -5920,15 +6076,20 @@ jQuery.fn.extend({ for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && - !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + !jQuery._data( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { - jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + jQuery.globalEval( + ( node.text || node.textContent || node.innerHTML || "" ) + .replace( rcleanScript, "" ) + ); } } } @@ -5939,4350 +6100,4858 @@ jQuery.fn.extend({ } } - return this; + return collection; } -}); - -jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - i = 0, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1; - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone(true); - jQuery( insert[i] )[ original ]( elems ); + function remove( elem, selector, keepData ) { + var node, + elems = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; - // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() - push.apply( ret, elems.get() ); - } + for ( ; ( node = elems[ i ] ) != null; i++ ) { - return this.pushStack( ret ); - }; -}); + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } -var iframe, - elemdisplay = {}; + return elem; + } -/** - * Retrieve the actual display of a element - * @param {String} name nodeName of the element - * @param {Object} doc Document object - */ -// Called only from within defaultDisplay -function actualDisplay( name, doc ) { - var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, - // getDefaultComputedStyle might be reliably used only on attached element - display = window.getDefaultComputedStyle ? + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); - // Use of this method is a temporary fix (more like optmization) until something better comes along, - // since it was removed from specification and supported only in FF - window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); + if ( support.html5Clone || jQuery.isXMLDoc( elem ) || + !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { - // We don't have any data stored on the element, - // so use "detach" method as fast way to get rid of the element - elem.detach(); + clone = elem.cloneNode( true ); - return display; -} + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } -/** - * Try to determine the default display value of an element - * @param {String} nodeName - */ -function defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; + if ( ( !support.noCloneEvent || !support.noCloneChecked ) && + ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { - if ( !display ) { - display = actualDisplay( nodeName, doc ); + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { + // Fix all IE cloning issues + for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) { - // Use the already-created iframe if possible - iframe = (iframe || jQuery( "